if和else语句都在执行

Sco*_*ain 4 sql sql-server-2005

我在我的SQL中有这个查询

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
Run Code Online (Sandbox Code Playgroud)

结果select count(*) from sys.columns where object_id = (select object_id from sys.tables where name = 'CLIENT_STATUS')是4,但它似乎总是执行else查询的5参数版本.

我的if语句我做错了什么?

更新:

它似乎正在运行这两个语句,因为如果我这样做

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
Run Code Online (Sandbox Code Playgroud)

我得到了同样的错误,但现在它说它正在做第一个声明.

更新2: 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
Run Code Online (Sandbox Code Playgroud)

Mik*_*son 6

SQL Server编译语句时出现错误.

有了这张桌子

create table TestTable(ID int)
Run Code Online (Sandbox Code Playgroud)

尝试运行此语句

if 1 = 1
  insert into TestTable values (1)
else
  insert into TestTable values(1, 2)  
Run Code Online (Sandbox Code Playgroud)

结果:

Msg 213, Level 16, State 1, Line 4
Column name or number of supplied values does not match table definition.
Run Code Online (Sandbox Code Playgroud)

显然,第二个语句永远不会被执行,但它将被编译.

  • @Scott - 一种方法是动态构建insert语句.想不出别的东西. (2认同)
  • (1)分支代码,根据列数调用一个或任一子进程.(2)如果在这些情况下总是保持相同,则在第5列上粘贴默认值.唉,就像动态SQL一样,这些感觉非常糟糕. (2认同)