2013-07-29 102 views
2

我有以下兩個查詢,第一個按照您的預期工作。第二個引發了一個例外說無效列名稱ISDELETED。但我已經添加的if else結構正是爲了避免這種錯誤,我在做什麼錯在第二個查詢SQL語句調試

IF COL_LENGTH('vwAs', 'IsActive') IS NOT NULL 
select 1 
ELSE IF COL_LENGTH('vwABCs', 'IsDeleted') IS NOT NULL 
    select 0 
ELSE SELECT -1 

而且

IF COL_LENGTH('vwAs', 'IsActive') IS NOT NULL 
select Count(*) [vwB] from [vwAs] WHERE ISACTIVE = 1 
ELSE IF COL_LENGTH('vwABCs', 'IsDeleted') IS NOT NULL 
    select Count(*) [vwABCsActive] from [vwABCs] WHERE ISDELETED = 0  
ELSE SELECT -1 

回答

4

之前運行查詢數據庫引擎嘗試驗證自己的代碼,但不驗證你的邏輯。如果您的表格沒有ISDELETED列數據庫顯示錯誤。所以你必須隱藏從DB引擎你的錯誤代碼爲動態SQL。動態sql將不會被驗證。

IF COL_LENGTH('vwAs', 'IsActive') IS NOT NULL 
select Count(*) [vwB] from [vwAs] WHERE ISACTIVE = 1 
ELSE IF COL_LENGTH('vwABCs', 'IsDeleted') IS NOT NULL 
    exec('select Count(*) [vwABCsActive] from [vwABCs] WHERE ISDELETED = 0') 
ELSE SELECT -1 
+0

你是一個拯救生命的人謝謝你! – Yohannes