I have the following SQL for which I want to backup the results in to a new table (using SELECT * INTO backup_table)...
WITH LIST AS
(SELECT column1
FROM table1
UNION
SELECT column1
FROM table2
UNION
SELECT column1
FROM table3
WHERE column1 IS NOT NULL
)
SELECT
a.column1
a.column2
a.column3
FROM table2 a
WHERE a.column6 NOT IN (SELECT field1 FROM LIST)
AND a.column3 ='1'
ORDER BY a.column3
So far I have tried this but get an error:
SELECT * INTO backup_table FROM (
WITH LIST AS
(SELECT column1
FROM table1
UNION
SELECT column1
FROM table2
UNION
SELECT column1
FROM table3
WHERE column1 IS NOT NULL
)
SELECT
a.column1
a.column2
a.column3
FROM table2 a
WHERE a.column6 NOT IN (SELECT field1 FROM LIST)
AND a.column3 ='1'
ORDER BY a.column3) a
The errors I get are:
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Incorrect syntax near ')'
I'm using SQL Server 2014 (12.0.6433.1)
with, similar to a view or a derived table defines a table expression - it is defined at the start of your query and then referenced, you don't define it within aselect; create your backup table first, then use that in your main query.SELECT/UPDATE/DELETE/etc statement goes after theWITHnot before it.