临时表未创建

时间:2014-08-08 14:42:19

标签: sql sql-server plsqldeveloper

我正在尝试在以下代码中创建2个临时表。虽然我的条件是从else语句创建临时表,但对于tmp2,它​​表示已经创建了表。我这样做是因为我想要合并来自2个临时表的数据,无论它是否有数据。

以下脚本不会创建## tmp2表,而不考虑以下查询中的else条件......

DECLARE @@TOTALCOUNT  INT 
DECLARE @@DECRIPTION VARCHAR(100)
DECLARE @@ST VARCHAR(100)
DECLARE @@ZP VARCHAR(100)
DECLARE @@CT VARCHAR(100)
DECLARE @@GN  VARCHAR(100)

SET @@ST = 'IA'
SET @@CT = 'JOHNSTON'
SET @@ZP = '50131'
SET @@GN = 'FEMALE'

BEGIN TRY
    DROP TABLE ##TMP1;
    DROP TABLE ##TMP2;          

END TRY

BEGIN CATCH

    SET @@DECRIPTION =  ' VEHICLES ARE SOLD DURING LAST 3  MONTHS '

    SET @@TOTALCOUNT = ( SELECT COUNT(*)  FROM [TALK TRACK RAP].DBO.CARSEXCEL
    WHERE [SALE_DATE] >  DATEADD( DAY, -90 ,CONVERT (DATE , '01/01/2013',103)) 
    AND [SALE_DATE] < CONVERT (DATE , '01/01/2013',103)) ;

    SELECT  MAKE , ( (100 * COUNT(*)) /@@TOTALCOUNT ) CN , 
    CONVERT(VARCHAR, ( (100 * COUNT(*)) /@@TOTALCOUNT ))+ ' % ' + MAKE + @@DECRIPTION AS TALK INTO ##TMP1
    FROM [TALK TRACK RAP].DBO.CARSEXCEL
    WHERE [SALE_DATE] >  DATEADD( DAY, -90 ,CONVERT (DATE , '01/01/2013',103)) 
    AND [SALE_DATE] < CONVERT (DATE , '01/01/2013',103)
    GROUP BY MAKE 
END CATCH


IF @@ST IS NULL
BEGIN

    SET @@TOTALCOUNT = (SELECT COUNT(*) FROM [TALK TRACK RAP].DBO.CARSEXCEL
    WHERE [SALE_DATE] >  DATEADD( DAY, -90 ,CONVERT (DATE , '01/01/2013',103)) 
    AND [SALE_DATE] < CONVERT (DATE , '01/01/2013',103)
    AND  STATE= @@ST  )

    SET @@DECRIPTION =  ' VEHICLES ARE SOLD DURING LAST 3  MONTHS IN ' +  @@ST+ ' STATE '

    SELECT  MAKE , ( (100 * COUNT(*)) / @@TOTALCOUNT ) CN ,
    CONVERT(VARCHAR, ( (100 * COUNT(*)) /@@TOTALCOUNT ))+ ' % ' +MAKE + @@DECRIPTION  AS TALK INTO ##TMP2
    FROM [TALK TRACK RAP].DBO.CARSEXCEL
    WHERE [SALE_DATE] >  DATEADD( DAY, -90 ,CONVERT (DATE , '01/01/2013',103)) 
    AND [SALE_DATE] < CONVERT (DATE , '01/01/2013',103)
    AND  STATE= @@ST
    GROUP BY MAKE ;
END 

if @@ST IS NOT NULL
BEGIN

    IF EXISTS ( SELECT * FROM sys.tables WHERE name LIKE '##TMP2%' ) 
    DROP TABLE ##TMP2
    CREATE TABLE ##TMP2 (MAKE VARCHAR(30), CN VARCHAR(30), TALK VARCHAR(30))
END

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

临时表不会显示在sys.tables中。这是测试临时表的简单方法:

IF OBJECT_ID('tempdb..#TMP2') IS NOT NULL DROP TABLE #TMP2
GO