unknown
unknown

Reputation: 5017

Insert query using CTE in SQL Server

I want to insert into one table from another table using a CTE. I have tried to put semicolon before with, but it's not working.

This is my query :

INSERT INTO [autoFIE2].[dbo].[tbl_article_type_parent_child] ([art_typ_parent_index], [art_typ_child_index])
WITH article_type_list AS
(
    SELECT 
       art_typ_child_index, art_typ_parent_index
    FROM
       [autoFIE2].[dbo].[tbl_article_type_parent_child]  
    WHERE 
       art_typ_parent_index IS NULL 
    UNION ALL
    SELECT 
       a.art_typ_child_index, a.art_typ_parent_index
    FROM
       [autoFIE2].[dbo].[tbl_article_type_parent_child] A 
    INNER JOIN 
       article_type_list as AL ON a.art_typ_parent_index = al.art_typ_child_index
    WHERE 
       a.art_typ_parent_index IS NOT NULL)
SELECT * 
FROM article_type_list;

Error while executing this statement :-

Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'with'.

Msg 319, Level 15, State 1, Line 4
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.

What should I do to insert this hierarchical data into another table. Any suggestion ?

Upvotes: 3

Views: 7448

Answers (1)

Mitch Wheat
Mitch Wheat

Reputation: 300549

Declare the cte first, then the insert from select list from cte:

;WITH article_type_list AS
(
    SELECT 
       art_typ_child_index, art_typ_parent_index
    FROM
       [autoFIE2].[dbo].[tbl_article_type_parent_child]  
    WHERE 
       art_typ_parent_index IS NULL 
    UNION ALL
    SELECT 
       a.art_typ_child_index, a.art_typ_parent_index
    FROM
       [autoFIE2].[dbo].[tbl_article_type_parent_child] A 
    INNER JOIN 
       article_type_list as AL ON a.art_typ_parent_index = al.art_typ_child_index
    WHERE 
       a.art_typ_parent_index IS NOT NULL
)
INSERT INTO [autoFIE2].[dbo].[tbl_article_type_parent_child] 
([art_typ_parent_index], [art_typ_child_index])
SELECT * FROM article_type_list;

Upvotes: 7

Related Questions