2011-06-02 83 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