[RESOLVED] Multiple selects in Stored Procedure
SQL SERVER 2008
I have a table "tbl1" and I would like to query the table 3 times.
e.g
Code:
Select MyVal from tbl1 where Title like 'Fred%'
Select MyVal from tbl1 where Title like 'Jane%'
Select MyVal from tbl1 where Title like 'Jimmy%'
I want to put these 3 selects into a stored procedure to return 3 values :
Code:
declare @MyVal1
declare @MyVal2
declare @MyVal3
Select @MyVal1 from tbl1 where Title like 'Fred%'
Select @MyVal2 from tbl1 where Title like 'Jane%'
Select @MyVal3 from tbl1 where Title like 'Jimmy%'
I think I'm confusing myself a bit here.
Is this possible and whats the syntax?
Thanks In Advance
Re: Multiple selects in Stored Procedure
Just do this:
Select MyVal from tbl1 where Title like 'Fred%' UNION ALL
Select MyVal from tbl1 where Title like 'Jane%' UNION ALL
Select MyVal from tbl1 where Title like 'Jimmy%'
Re: Multiple selects in Stored Procedure
Or...
Code:
Select MyVal from tbl1
where Title like 'Fred%'
OR Title like 'Jane%'
OR Title like 'Jimmy%'
Re: Multiple selects in Stored Procedure
As you have the same number of fields for each query (and the data type by position is the same), a simple way is to use UNION ALL, eg:
Code:
Select MyVal from tbl1 where Title like 'Fred%'
UNION ALL
Select MyVal from tbl1 where Title like 'Jane%'
UNION ALL
Select MyVal from tbl1 where Title like 'Jimmy%'
edit: ooops... should have refreshed my browser!
Re: Multiple selects in Stored Procedure
I basically just did this :
Code:
declare @MyVal1
declare @MyVal2
declare @MyVal3
Select @MyVal1 from tbl1 where Title like 'Fred%'
Select @MyVal2 from tbl1 where Title like 'Jane%'
Select @MyVal3 from tbl1 where Title like 'Jimmy%'
Select @MyVal1, @MyVal2, @MyVal3
and it works fine.
What I would likle to know now is how to I give these return values column names.
Any ideas folks?
Thanks In Advance:wave:
Re: Multiple selects in Stored Procedure
Specify aliases, eg:
Code:
Select @MyVal1 as Hello, @MyVal2, @MyVal3