2014-12-03 73 views
0

我正在使用如果else語句,並且我想刪除創建在內部if語句旁邊的臨時表,但是當我執行語句時,我得到答案as,數據庫中已經有一個名爲'#table'的對象。 ---------------------我的代碼就像這裏輸入代碼如果其他循環,不能刪除相同的臨時表

DECLARE @RowCount INT; 

SET @RowCount = 1; 

IF @RowCount = 1 
BEGIN 
    IF OBJECT_ID('tempdb..#Guarantor_Details') IS NOT NULL 
     DROP TABLE #Guarantor_Details 

    SELECT DISTINCT TOP 1 GUARANTORS.GUARANTOR_CODE 
    INTO #Guarantor_Details 
    FROM GUARANTORS 
    WHERE ISNULL(GUARANTORS.deleted, 0) <> 1; 

    DECLARE @GuarantorCount INT; 

    SELECT @GuarantorCount = count(*) 
    FROM #Guarantor_Details; 

    IF (@GuarantorCount = 0) 
     DROP TABLE #Guarantor_Details 

    BEGIN 
     IF OBJECT_ID('tempdb..#Guarantor_Details') IS NOT NULL 
      SELECT TOP 1 CLIENT.Last_Name 
      INTO #Guarantor_Details 
      FROM CLIENT 
      LEFT JOIN GUARANTORS ON GUARANTORS.GUARANTOR_CODE = CLIENT.Financial_Guarantor 
    END 
END 
------------------------------------------------------------------------ 

回答

0

你不需要做這種類型的CREATE/DROP。您可以(也可能應該)在循環之前創建表格,並在必要時重置臨時表格TRUNCATE TABLEDELETE FROM以「重置」它。只需選擇一個適合GUARANTOR_CODELast_Name的數據類型。

如果您的INSERT操作中的@@ROWCOUNT已具有該值,那麼您也不需要在表上執行SELECT COUNT(*)操作。

本質:

CREATE TABLE #Guarantor_Details (Value NVARCHAR(50)); 

WHILE (something) 
BEGIN 

    IF (@RowCount = 1) 
    BEGIN 
    TRUNCATE TABLE #Guarantor_Details; 

    INSERT INTO #Guarantor_Details (Value) 
     SELECT DISTINCT TOP 1 GUARANTORS.GUARANTOR_CODE 
     FROM GUARANTORS 
     WHERE ISNULL(GUARANTORS.deleted, 0) <> 1; 

    IF (@@ROWCOUNT = 0) 
    BEGIN 
     INSERT INTO #Guarantor_Details (Value) 
     SELECT TOP 1 CLIENT.Last_Name 
     FROM CLIENT 
     LEFT JOIN GUARANTORS 
       ON GUARANTORS.GUARANTOR_CODE = CLIENT.Financial_Guarantor; 
    END; 
END; 

FYI,有出現是在原始代碼中的一些邏輯問題:在IF @RowCount = 1塊的底部

  • 有BEGIN/END標記,不與任何IF或WHILE關聯。這在技術上沒問題,但通常意味着缺少某些東西。

  • 如果這段代碼是所有的代碼,那麼IF @RowCount = 1在循環中不起作用,除非有什麼設置@RowCount超過此外部IF塊的末尾,這裏沒有在問題中顯示。