即使丢弃两者的代码相同,也只有两个临时表中的一个被删除

时间:2014-06-20 15:35:49

标签: tsql sql-server-2005 temp-tables

我有一个代码块,用于检查临时表是否存在,如果存在,则将其删除,然后再次创建表以填充数据。然后再次运行此代码块,但是对于不同的表。

当我运行脚本时,我收到错误

  

已经有一个名为'#Adjustments'在数据库中。

即使我有一个drop命令。该脚本正在删除第一个表而没有任何问题,所以我不确定它为什么不删除第二个表。

--Create a temp table with the total Receipts
IF (OBJECT_ID('tempdb..#Receipts') IS NOT NULL)
BEGIN
    DROP TABLE #Receipts;
END

SELECT  TerminalId,
        ProductId,
        SUM(GrossGallons) AS [GrossGallons],
        SUM(NetGallons) AS [NetGallons]
INTO #Receipts
FROM dbo.ReceiptAdjustment WITH (NOLOCK)
WHERE IsReceipt = 1
AND ReceiptAdjustmentDate BETWEEN @StartDate AND @EndDate
GROUP BY    TerminalId,
            ProductId,
            ReceiptAdjustmentDate;

--Create a temp table wth the total Adjustments
IF (OBJECT_ID('tempd..#Adjustments') IS NOT NULL)
BEGIN
    DROP TABLE #Adjustments;
END

SELECT  TerminalId,
        ProductId,
        SUM(GrossGallons) AS [GrossGallons],
        SUM(NetGallons) AS [NetGallons]
INTO #Adjustments
FROM dbo.ReceiptAdjustment WITH (NOLOCK)
WHERE IsReceipt = 0
AND ReceiptAdjustmentDate BETWEEN @StartDate AND @EndDate
GROUP BY    TerminalId,
            ProductId,
            ReceiptAdjustmentDate;

1 个答案:

答案 0 :(得分:1)

有一个错字

更改

IF (OBJECT_ID('tempd..#Adjustments') IS NOT NULL)

IF (OBJECT_ID('tempdb..#Adjustments') IS NOT NULL)