3

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 ?

1
  • You don't need to wrap the sub-query up with a CTE Commented Jan 21, 2015 at 5:50

1 Answer 1

7

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.