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
 General SQL Server Forums
 New to SQL Server Programming
 if exists query runs twice

Author  Topic 

tpiazza55
Posting Yak Master

162 Posts

Posted - 2010-10-29 : 18:23:02
how do you do the following with running the query twice?

select @sql = '
if exists (select * from tbl)
select * from tbl
else
select * from tbl2'
exec (@sql)

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2010-10-29 : 18:41:26
select @sql = 'select * into #a from @tbl
if exists (select * from #a)
select * from #a
else
select * from tbl2'
exec (@sql)


==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

tpiazza55
Posting Yak Master

162 Posts

Posted - 2010-11-01 : 12:50:46
how would that work for a third case

if exists (select * from a)
select * from a
else if (select * from b)
select * from b
else
select * from c
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-11-01 : 12:54:27
it looks fine. why? isnt it working for you?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

tpiazza55
Posting Yak Master

162 Posts

Posted - 2010-11-01 : 13:08:11
building dynamic sql statement with a select from a temp table

the above was just an outline of what i need to do. I dont want to run the query twice each time. just once to see if it exists if so get reuslt. following the method running query and pushing to temp.

cant figure out how to get the sql to adjust in the "else if"
Go to Top of Page
   

- Advertisement -