将 SQL Server 中的 FindAll 函数修改为DoesExist 函数
我有以下递归函数:
ALTER FUNCTION [dbo].[ListAncestors]
(
@Id int
)
RETURNS TABLE
As
RETURN
(
WITH cte As
(
SELECT
UserId,
ManagerId,
Forename,
Surname
FROM
dbo.Users
WHERE
UserId = @Id
UNION ALL
SELECT
T.UserID,
T.ManagerID,
T.Forename,
T.Surname
FROM
cte As C INNER JOIN dbo.Users As T
ON C.UserID = T.ManagerID
)
SELECT
Forename,
Surname
FROM
cte
);
基本上它的作用是返回指定用户下面的所有用户的名称(基于他们的 ID)。我想要做的是修改这个函数并创建另一个函数来检查特定用户 ID 是否是另一个用户 ID 的祖先。
我想签名会是这样的:
CREATE FUNCTION IsAncestor(@Id int, @AncestorId int) RETURNS BIT
I have the following recursive function:
ALTER FUNCTION [dbo].[ListAncestors]
(
@Id int
)
RETURNS TABLE
As
RETURN
(
WITH cte As
(
SELECT
UserId,
ManagerId,
Forename,
Surname
FROM
dbo.Users
WHERE
UserId = @Id
UNION ALL
SELECT
T.UserID,
T.ManagerID,
T.Forename,
T.Surname
FROM
cte As C INNER JOIN dbo.Users As T
ON C.UserID = T.ManagerID
)
SELECT
Forename,
Surname
FROM
cte
);
Basically what it does is returns the names of all users below the specified user (based on their ID). What I would like to do is modify this function and create another function which does a check if a specific userID is an ancestor of another.
I imagine the signature would look something like:
CREATE FUNCTION IsAncestor(@Id int, @AncestorId int) RETURNS BIT
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样:
How about:
如果我们接受初始 CTE 采用 ID 并列出该 ID 的所有“祖先”,我认为以下查询会测试此关系。
但这有点奇怪,因为给定初始功能,一个人与自己处于“祖先”关系。
顺便说一句,我从 CTE 的 select 语句中删除了 ManagerID,因为它不是必需的
If we accept that the initial CTE takes an ID and lists all the 'ancestors' of that ID, I think that the following query tests for this relation.
It's a bit odd though, since given the initial function a person is in the 'ancestor' relation with themselves.
Incidentally, I removed the ManagerID from the select statements in the CTE since it isn't necessary