Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

UNION

Status
Not open for further replies.

sardinka2

Programmer
May 6, 2004
38
US
I have set of Union statements.I need to validate param if param='123'
then do one more union if not end of select.
When I ran the sp it gives me an error in the union in if statement.
What am I doing incorrect?
Select 1,2,3 from table1
UNION
Select 1,2,3 from table2
...
If @param='123'
Begin
Union
Select 1,2,3 from table3
END
 
Could use dynamic SQL

Code:
declare @i as int
declare @str as varchar(8000)
set @i = 2

set @str = 'select 34 as i'

if @i = 2
begin
set @str = @str +' union select 45 as i'
end

exec(@str)
 
You could also do something like so ...

select

Union

select

Union

select * from sometable where @parm = truevalue

The third union will only have a return data set if the conditional expression (where @parm = truevalue) resolves to true. Otherwise, nothing will get returned in the last select.

Save the hassle of trying to parse dynamic sql strings.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top