I am using a SQL Server 2005 database, and I have an If statement that is behaving in two different manners against the same data set, depending on the actions to be taken in the begin…end block.
First, if I merely want to print to the console, the following code prints nothing, as expected:
if (not exists(select null from tblControls where Name = 'SOME_CONTROL_NAME'))
begin
print 'control not found'
end
Whereas this code prints ‘control found’ as expected:
if (exists(select null from tblControls where Name = 'SOME_CONTROL_NAME'))
begin
print 'control found'
end
However, if I change the code to this:
if (not exists(select null from tblControls where Name = 'SOME_CONTROL_NAME'))
begin
insert into tblControls values (632, 'NEW_CONTROL_NAME', 'New Control', 1, 1, NULL, 1, 'DataControls.CheckBox', NULL, NULL, 1)
end
The insert statement ALWAYS fires, even though a matching record exists in tblControls. Is there something special about insert statements in T-SQL 2005 that could be causing this behavior, or am I missing something obvious? I would understand if the logic of the code is wrong, but when I tested using the print statement it works as expected.
EDIT: Its generating an “Insert Error” message.
Any help with this frustrating problem is greatly appreciated.
It’s the NULL in the Exists..Select that’s confusing it. Try:
Also, it can be rewritten without the parentheses and Begin/End: