gpt4 book ai didi

sql-server - 在 SQL Server 中使用 CTE 插入查询

转载 作者:行者123 更新时间:2023-12-05 01:20:45 29 4
gpt4 key购买 nike

我想使用 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
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.

我应该怎么做才能将这个分层数据插入到另一个表中。有什么建议吗?

最佳答案

首先声明 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;

关于sql-server - 在 SQL Server 中使用 CTE 插入查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28060434/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com