重复SQL指令,直到它获取所有数据
我在尝试获取一些SQL数据时遇到了一个小问题,我尝试了一个“for”循环,但没有成功,我感到很沮丧。我有一个名为“dbo.AccountTree”的表,它有两列,“ParentAccountID”和“SubAccountID” “ParentAccountID”可以有多个“SubAccountID”,即“ParentAccountID”101520有9个“SubAccountID”,但其中1个是相同的“ParentAccountID” 父帐户ID子帐户 101520 101520 101520 1201 101520 1202 101520 1203 101520 1204 101520 1205 101520 1206 101520 1207 101520 1208 一切都应该是好的,除了一些“子帐户”也是“父帐户ID”,我还需要为它们获取“子帐户” 父帐户子帐户 1204 1001 1205 1002 此外,这些“子帐户”也是“父帐户ID” 父帐户子帐户 1002 999重复SQL指令,直到它获取所有数据,sql,sql-server,Sql,Sql Server,我在尝试获取一些SQL数据时遇到了一个小问题,我尝试了一个“for”循环,但没有成功,我感到很沮丧。我有一个名为“dbo.AccountTree”的表,它有两列,“ParentAccountID”和“SubAccountID” “ParentAccountID”可以有多个“SubAccountID”,即“ParentAccountID”101520有9个“SubAccountID”,但其中1个是相同的“ParentAccountID” 父帐户ID子帐户 101520 10152
在上面的解释中,“ParentAccountID”101520在同一个表中有3个级别的数据,我需要指示SQL在每个级别下返回“SubAccountID”(将有一些“ParentAccountID”具有3个以上的级别,因此SQL需要运行,直到所有“SubAccountID”没有任何其他级别的数据)SQL没有“for循环”之类的过程概念;我知道你在试图将你需要的东西与你知道的东西联系起来,但重要的是要理解SQL是一种与C#、Java等截然不同的语言 SQL在这种情况下的功能是递归查询。对这些(以及语法)的支持往往取决于DBMS;从标签上看,您似乎正在使用SQL Server,因此这里有一个关于T-SQL递归查询的问题:
你应该使用CTE,这样的东西应该可以用
WITH AccountTreeCTE(ParentAccountID, SubAccountID, Depth) AS
(
SELECT ParentAccountID, SubAccountID, 0 AS Depth
FROM dbo.AccountTree
WHERE ParentAccountID IS NULL
UNION ALL
SELECT e.ParentAccountID, e.SubAccountID, Depth + 1
FROM dbo.AccountTree AS e
INNER JOIN AccountTreeCTE AS d
ON e.ParentAccountID = d.SubAccountID
)
SELECT ParentAccountID, SubAccountID, Depth
FROM AccountTreeCTE
ORDER BY ParentAccountID;
GO
请不要将图像用于文本数据,因为表格a
块工作得很好(图像太难读取)“图像太难读取”-特别是对于那些使用辅助技术(如屏幕阅读器)访问此网站的人。是否有最大级别数?幸运的是,如果有人真正阅读了问题,具体数据对于这个问题来说并不太重要;但是,上面的评论是正确的:文本图片没有任何用处。我已经改为使用图像,并且没有最大级别数。如果我执行该代码,我没有得到任何结果,我将“Where ParentAccountID为NULL”替换为“Where ParentAccountID=240345”,并且我得到以下错误:语句终止。在语句完成之前,最大递归100已用尽。@Samoya-我们需要停止追逐循环链接。在您的数据中,ParentAccountID
引用自身作为子帐户的周期是否唯一可能?如果是,则添加WHERE ParentAccountID!=将SubAccount
添加到两个union
ed查询就足够了。否则,我们需要一个周期检测器,这些都不是有趣的添加。
ParentAccount SubAccount
1204 1001
1205 1002
ParentAccount SubAccount
1002 999
WITH AccountTreeCTE(ParentAccountID, SubAccountID, Depth) AS
(
SELECT ParentAccountID, SubAccountID, 0 AS Depth
FROM dbo.AccountTree
WHERE ParentAccountID IS NULL
UNION ALL
SELECT e.ParentAccountID, e.SubAccountID, Depth + 1
FROM dbo.AccountTree AS e
INNER JOIN AccountTreeCTE AS d
ON e.ParentAccountID = d.SubAccountID
)
SELECT ParentAccountID, SubAccountID, Depth
FROM AccountTreeCTE
ORDER BY ParentAccountID;
GO