Possible Duplicate:
Incorrect syntax near the keyword 'with'…previous statement must be terminated with a semicolon
I want to select hierachical data and insert it in a table.
Therefore i need to use the WITH statment in my insert.
This works fine:
create table test_table
(
id int
)
with t_table
as
(select 12345 wert)
insert into test_table (id)
select wert from t_table
But this generates a “wrong syntax near WITH keyword” error:
CREATE PROCEDURE p_insert_test
AS
BEGIN
with t_table
as
(select 12345 wert)
insert into test_table (id)
select wert from t_table
END
I guess T-SQL doesn’t like the WITH keyword before the INSERT keyword.
How can i do this kind of insert in a stored procedure?
Thank you!
The CTE declaration needs to be the first command in the batch.
Just put a semicolon before the
WITHand you should be fine:;WITH t_Table...EDIT:
Just to clarify why this is the case, the
WITHkeyword is used for query hints as well, such asWITH RECOMPILE,WITH (NOLOCK), etc. The query engine needs to know the intent of theWITHkeyword, and the only way to signify that it represents aCTEis to ensure that theCTEdeclarations are the beginning of the batch.Otherwise, you could have something ambiguous like:
Without the statement terminator,
CteNamewill be inappropriately read as a query hint applied toMyTable.