I have this query in my 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
The result of select count(*) from sys.columns where object_id = (select object_id from sys.tables where name = 'CLIENT_STATUS') is 4, however it always appears to be executing the 5 parameter else version of the query.
What am I doing wrong with my if statement?
UPDATE:
It appears to be running both statments because if I do
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
I get the same error but now it says it is doing the first statement.
UPDATE2:
Mikael Eriksson had the correct answer, I changed my code to this to fix it.
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
You get the error when SQL Server compiles your statements.
With this table
Try to run this statement
Result:
Clearly the second statement will never be executed but it will be compiled.