SQL Server Performance

dynamic Sql statement using Union operator(very urgent!!!)

Discussion in 'SQL Server 2005 General Developer Questions' started by arshadrocku, Mar 18, 2008.

  1. arshadrocku New Member

    I m facing problem while using union operator with dynamic sql statement...
    here is the error "Incorrect Syntax near UNION"
    Here is my code example....
    Set @FirstSql='select * from tableA'//complex query here
    set @SecondSql='select * from tableB'//Complex query here
    Exec(@FirstSql + @SecondSql)
    union
    Set @ThirdSql='select * from tableA'//complex query here
    set @FourthSql='select * from tableB'//Complex query here
    Exec(@ThirdSql+ @FourthSql)

  2. Adriaan New Member

    Say you have a script:
    SELECT * FROM Table1
    SELECT * FROM Table2

    This script will return two resultsets.
    Add the keyword UNION before the second SELECT. The script will now return one resultset (provided that the columns match up):
    SELECT * FROM Table1
    UNION SELECT * FROM Table2
    In other words, UNION is not a control-of-flow operator!
  3. ranjitjain New Member

    Hi,
    Do you mean something like this:declare
    @q1 varchar(900),@q2 varchar(900),@q3 varchar(900),@q4 varchar(900)set
    @q1='select 1'set
    @q2='select 2'set
    @q3='select 3'set
    @q4='select 4'exec
    (@q1+@q2+@q3+@q4)exec
    (@q1+' UNION ALL '+@q2+' UNION ALL '+@q3+' UNION ALL '+@q4)

Share This Page