gpt4 book ai didi

sql - 选择从 CTE 使用 AS? SQL Server 2008

转载 作者:行者123 更新时间:2023-12-04 14:34:05 25 4
gpt4 key购买 nike

我正在尝试将 PostgreSQL 转换为 SQL Server。但是这个查询不起作用。

我究竟做错了什么?我试图在 WITH 之前添加一个分号,但没有运气。

   SELECT 
member_a AS you, member_b AS mightknow, shared_connection,
CASE
WHEN (n1.member_job_country = n2.member_job_country AND n1.member_job_country = n3.member_job_country) THEN 'country in common'
WHEN (n1.member_unvan_id = n2.member_unvan_id AND n1.member_unvan_id = n3.member_unvan_id) THEN 'unvan in common'
ELSE 'nothing in common'
END AS reason
FROM (
WITH transitive_closure(member_a, member_b, distance, path_string, direct_connection) AS
(SELECT
member_a, member_b, 1 AS distance,
CAST(member_a as varchar(MAX)) + '.' + CAST(member_b as varchar(MAX)) + '.' AS path_string,
member_b AS direct_connection
FROM Member_Contact_Edges
WHERE member_a = 45046 -- set the starting node

UNION ALL

SELECT
tc.member_a, e.member_b, tc.distance + 1,
CAST(tc.path_string as varchar(MAX)) + CAST(e.member_b as varchar(MAX)) + '.' AS path_string,
tc.direct_connection
FROM Member_Contact_Edges AS e
JOIN transitive_closure AS tc ON e.member_a = tc.member_b
WHERE tc.path_string NOT LIKE '%' + CAST(e.member_b as varchar(MAX)) + '.%'
AND tc.distance < 2
)

SELECT
member_a, member_b,direct_connection AS shared_connection
FROM transitive_closure
WHERE distance = 2
) AS youmightknow
LEFT JOIN Members AS n1 ON youmightknow.member_a = n1.memberID
LEFT JOIN Members AS n2 ON youmightknow.member_b = n2.memberID
LEFT JOIN Members AS n3 ON youmightknow.shared_connection = n3.memberID
WHERE (n1.member_job_country = n2.member_job_country
AND n1.member_job_country = n3.member_job_country)
OR (n1.member_unvan_id = n2.member_unvan_id
AND n1.member_unvan_id = n3.member_unvan_id);

我得到的错误:

Msg 156, Level 15, State 1, Line 11
Incorrect syntax near the keyword 'WITH'.
Msg 319, Level 15, State 1, Line 11
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.
Msg 102, Level 15, State 1, Line 34
Incorrect syntax near ')'.



这是引用; Graphs in the Database - SQL Meets Social Networks - 查看文章底部的 facebook 建议部分。

提前致谢

最佳答案

CTE 声明需要放在顶部。您还可以使用逗号声明和连接多个 CTE,而不是混合 CTE 和派生表。

尝试

;WITH 
/*First CTE declaration*/
transitive_closure(member_a, member_b, distance, path_string, direct_connection)
AS
(
...
),
/*Second CTE declaration*/
youmightknow AS
(
SELECT member_a, member_b,direct_connection AS shared_connection
FROM transitive_closure
WHERE distance = 2
)
SELECT member_a AS you,
...
FROM youmightknow

关于sql - 选择从 CTE 使用 AS? SQL Server 2008,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5851744/

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