2011-06-02 131 views
4

我在SQL兩個if和else語句執行

if (select count(*) from sys.columns where object_id = (select object_id from sys.tables where name = 'CLIENT_STATUS')) = 4 
    insert into CLIENT_STATUS select 'NA', 'Inactive', 0, 0 --old version 
else 
    insert into CLIENT_STATUS select 'NA', 'Inactive', 0, 0, 1 --new version 

select count(*) from sys.columns where object_id = (select object_id from sys.tables where name = 'CLIENT_STATUS')結果是4有這個疑問,但是它總是出現被執行5參數else版本的查詢。

我在做什麼錯我的if語句?

UPDATE:

這似乎是同時運行statments因爲如果我這樣做

if (select count(*) from sys.columns where object_id = (select object_id from sys.tables where name = 'CLIENT_STATUS')) = 5 
    insert into CLIENT_STATUS select 'NA', 'Inactive', 0, 0, 1 --new version 
else 
    insert into CLIENT_STATUS select 'NA', 'Inactive', 0, 0 --old version 

我得到同樣的錯誤,但現在它說,它做的第一條語句。

UPDATE2: Mikael Eriksson有正確的答案,我改變了我的代碼以解決這個問題。

if ((select count(*) from sys.columns where object_id = (select object_id from sys.tables where name = 'CLIENT_STATUS')) = 5) 
    execute ('insert into CLIENT_STATUS select ''NA'', ''Inactive'', 0, 0, 1') --new version 
else 
    execute ('insert into CLIENT_STATUS select ''NA'', ''Inactive'', 0, 0') --old version 

回答

6

SQL Server編譯您的語句時出現錯誤。

有了這張表

create table TestTable(ID int) 

嘗試運行此聲明

if 1 = 1 
    insert into TestTable values (1) 
else 
    insert into TestTable values(1, 2) 

結果:

Msg 213, Level 16, State 1, Line 4 
Column name or number of supplied values does not match table definition. 

顯然,第二條語句將永遠不會被執行,但它會被編譯。

+0

有沒有辦法解決這個問題? – 2011-06-02 18:06:42

+2

@Scott - 一種方法是 – 2011-06-02 18:10:18

+2

(1)分支代碼,根據列計數調用一個或兩個子進程(2)如果它們總是相同,則在第5列上粘貼一個默認值在這些情況下。唉,像動態SQL,這些感覺很爛。 – 2011-06-02 18:14:58

0

我相信這與你的括號做的,你閉上你的if語句,然後比較,爲5

你可以試試這個調試:

declare @myCount as int 
select @myCount = select count(*) from sys.columns where object_id = (select object_id from sys.tables where name = 'CLIENT_STATUS'; 
print @myCount 

if (@myCount = 5) 
    insert into CLIENT_STATUS select 'NA', 'Inactive', 0, 0, 1 --new version 
else 
    insert into CLIENT_STATUS select 'NA', 'Inactive', 0, 0 --old version 

這將有助於你確保你從選擇中獲得的價值。

+0

添加聲明不會改變任何內容。 – 2011-06-02 18:07:15

+0

另外我嘗試添加開始/結束集,並沒有改變它。 – 2011-06-02 18:07:29

+0

聲明不會改變任何東西,但檢查輸出...在消息選項卡中打印了什麼值(假設您在SSMS – taylonr 2011-06-02 18:08:10