views:

27

answers:

1

Hi everyone, I am trying to solve this problem.

I have a series of SELECT statements like below.

SELECT Name FROM Table1 WHERE Name LIKE '%Tom%'

SELECT Name From Table2 WHERE Name LIKE '%Tom%'

.
.
.

SELECT Name FROM Table10 WHERE Name Like '%Tom%'

Without using IF ELSE statements, is there any way I can terminate this script halfway and return the selection as soon as something is selected without having to execute the rest of the SELECT statements?

Cheers.

+2  A: 

Instead of an IF..ELSE, you could check the value of @@Rowcount (or some other criteria) after each select, and either return or goto a label at the end of the script if the value is greater than 0. It will still be a lot of conditional checks, but the nesting won't be as difficult to manage.

e.g.

declare @vals table (id int)
Declare @rc int
Insert into @vals (id) values (1)
Select * from @vals
set @rc = @@ROWCOUNT
if @rc <> 0
Begin
    Print 'Exiting Early'
    return 
End
Select * from @vals
Select * from @vals
Select * from @vals
Select * from @vals
Select * from @vals

Or

declare @vals table (id int)
Declare @rc int
Insert into @vals (id) values (1)

Select * from @vals
set @rc = @@ROWCOUNT
if @rc <> 0
Begin
    Print 'Exiting Early'
    GOTO EarlyExit 
End


Select * from @vals
Select * from @vals
Select * from @vals
Select * from @vals
Select * from @vals


EarlyExit:
    Print 'We are done here'
cmsjr
OMG of course! Thanks for this. Having a slow Sunday here. lol
Nai
np, glad I could help.
cmsjr