I'm fairly new at SQL so I'm not sure if this is the correct way to write this. I have several queries that I want to join with UNIONs but I also need to run an IF EXISTS on each one first. The way I have it written now is
...so on with 4 more queries.
When I run it in Query Analyzer I get the following error:
Server: Msg 156, Level 15, State 1, Line 59
Incorrect syntax near the keyword 'IF'.
Each individual query runs with no problems but when I try to run them all with the UNIONs I get the error. All of the select statements pull the same data type and number of columns.
Any ideas or am I going in the wrong direction with this one? Thanks!
--tony
Code:
IF EXISTS(query 1)
BEGIN
query 1
END
ELSE
CREATE TABLE #1temp...
INSERT #1temp...
SELECT * from #1temp
UNION ALL
IF EXISTS(query 2)
BEGIN
query 2
END
ELSE
CREATE TABLE #2temp...
INSERT #2temp...
SELECT * from #2temp
...so on with 4 more queries.
When I run it in Query Analyzer I get the following error:
Server: Msg 156, Level 15, State 1, Line 59
Incorrect syntax near the keyword 'IF'.
Each individual query runs with no problems but when I try to run them all with the UNIONs I get the error. All of the select statements pull the same data type and number of columns.
Any ideas or am I going in the wrong direction with this one? Thanks!
--tony