Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 How are IF statements handled?

Author  Topic 

Blastrix
Posting Yak Master

208 Posts

Posted - 2003-11-06 : 13:15:41
If I have an IF statement such as:

IF (@ID > 0 And EXISTS(Select * From SomeTable Where ID = @ID))

Will the whole statement always be evaluated, or will SQL stop evaluating if @ID is 0 or less?

Thanks,
Steve

robvolk
Most Valuable Yak

15732 Posts

Posted - 2003-11-06 : 13:28:42
I believe SQL Server performs the short-circuit evaluation and will stop processing after it determines the expression is true. I can't remember where I read that though, but Inside SQL Server was probably it. I'd recommend writing your IF statements to take advantage of it, I do that with mine. It can't hurt.
Go to Top of Page

jsmith8858
Dr. Cross Join

7423 Posts

Posted - 2003-11-06 : 13:45:42
you know the trick how to test:

if (1=1 or (1/0)=0) print 'ok'

if it prints OK, it is short-circuiting. To save the suspense, i ran this and it printed OK, so it isn't evaluating any more than it needs to.

"Case" does the same thing:

select case when 1=1 then 1 else 2/0 end

that works fine.

Finally, what about WHERE clauses:

select 1 where 1=1 or 1/0 = 0

works fine as well !

- Jeff
Go to Top of Page
   

- Advertisement -