我正在使用SQL Server R2。
两张桌子:
UserEntryAccess (EntryId, UserId)
ParentEntryRelation(Id, ParentType, ParentId, EntryId)
当记录插入ParentEntryRelation时,触发器需要通过向上走动ParentEntryRelation表来获取当前具有访问权限的用户ID列表,并将EntryId和UserId插入UserEntryAccess。我有一个函数与递归公用表表达式,检索这些用户ID。很棒,yippee。
问题: 我可以使用什么单个sql查询为INSERTED表中的每条记录调用该函数,并在单个sql语句中将EntryId的THOSE结果插入到UserEntryAccess中。
这是递归CTE:
CREATE FUNCTION [dbo].[GetUserAccessIds](@entryId as uniqueidentifier)
RETURNS @tempUserids table (userId uniqueidentifier)
AS
BEGIN
WITH RecursiveEntry (ParentId,EntryId,ParentType)
AS
(
-- Anchor member definition
SELECT ParentId,EntryId,ParentType from ParentEntryRelation
where ParentEntryRelation.EntryId = @entryId
UNION ALL
-- Recursive member definition
SELECT ParentEntryRelation.ParentId,
ParentEntryRelation.EntryId,
ParentEntryRelation.ParentType
from ParentEntryRelation
inner join RecursiveEntry on RecursiveEntry.ParentId = ParentEntryRelation.EntryId
)
insert into @tempUserids
SELECT distinct ParentId
from RecursiveEntry
where ((ParentType & 32) = 32) --32 is the ServerUser type
OPTION (MAXRECURSION 32767)
RETURN
END
答案 0 :(得分:2)
听起来你想要使用CROSS APPLY。
insert into UserEntryAccess
(EntryId, UserId)
select i.EntryId, f.userId
from inserted i
cross apply [dbo].[GetUserAccessIds](i.EntryId) f