在SQL Server中使用CTE插入查询

时间:2015-01-21 05:48:09

标签: sql-server common-table-expression sql-insert

我想使用CTE从另一个表中插入一个表。我曾尝试在with之前加分号,但它没有用。

这是我的疑问:

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;

执行此语句时出错: -

  

Msg 156,Level 15,State 1,Line 4
  关键字'与'附近的语法不正确。

     

Msg 319,Level 15,State 1,Line 4
  关键字'与'附近的语法不正确。如果此语句是公用表表达式,xmlnamespaces子句或更改跟踪   context子句,前一个语句必须以a结尾   分号。

如何将此分层数据插入另一个表中。有什么建议吗?

1 个答案:

答案 0 :(得分:4)

首先声明cte,然后从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;