SQL Server临时表已经存在?

mit*_*w16 2 t-sql sql-server stored-procedures

所以这很奇怪,我在这个SQL语句中声明了一个临时表,但我只是根据if else逻辑声明它.我在运行以下查询之前删除临时表,仍然得到相同的行为.

但是,There is already an object named '#ManifestTrackingBranches' in the database. 当我尝试使用我的ReportType设置为2 运行查询时,SQL Server正在抱怨.

我在这里错过了什么吗?

T-SQL

declare @ReportType int 
declare @CustomerNumber int 
declare @StartDate datetime
declare @EndDate datetime 

set @ReportType = 2
set @CustomerNumber = 81 
set @StartDate = '2014-04-27'
set @EndDate = '2014-05-04'

if @CustomerNumber = 81
begin
    if @ReportType = 1 -- roll up by location
    begin 
        select  InboundData.Tracking,
                InboundData.NegotiatedRate 
        into    #ManifestTrackingBranches
        from    InboundData
        where   Injected >= @StartDate and Injected <= @EndDate

        -- Match tracking numbers against Ebill Data 
        select      #ManifestTrackingBranches.Tracking,
                    SUM(isnull(cast(#ManifestTrackingBranches.NegotiatedRate as decimal(18,2)),0)) as ManifestAmount
        from        EBillData 
        group by    #ManifestTrackingBranches.Branch
    end

    else if  @ReportType = 2 -- Line Item Reports
    begin 
        select  InboundData.Tracking,
                InboundData.NegotiatedRate 
        into    #ManifestTrackingBranches
        from    InboundData
        where   Injected >= @StartDate and Injected <= @EndDate

        -- Match tracking numbers against Ebill Data 
        select      #ManifestTrackingBranches.Tracking,
                    SUM(isnull(cast(#ManifestTrackingBranches.NegotiatedRate as decimal(18,2)),0)) as ManifestAmount
        from        EBillData 
    end
end
Run Code Online (Sandbox Code Playgroud)

如果where ReportType设置为2,则错误发生在第二个,并且我尝试选择相同的临时表.

M.A*_*Ali 8

在任何变量声明之前添加这行代码.

IF OBJECT_ID('tempdb..#ManifestTrackingBranches') IS NOT NULL 
DROP TABLE #ManifestTrackingBranches
GO
Run Code Online (Sandbox Code Playgroud)

只有在使用GO关键字将此语句放在单独的批处理中时才会生效.当你实际编写程序并通过再次执行n来测试代码时,这已经足够了.

在您的过程中,您无法添加关键字,GO并且在从应用程序调用此过程时也不需要删除表.对此过程的每次调用都将拥有自己的连接,并将创建一个仅限于该连接范围的临时表.

  • 经过测试,这无济于事......我认为@Damien_The_Unbeliever 是对的。Tsql 不关心控制流。 (2认同)