在存储过程中,我需要循环下表:
SELECT *
FROM dbo.UsersInRoles
INNER JOIN Application_Users ON UsersInRoles.AppUserID = Application_Users.AppUserID
WHERE (UsersInRoles.ApplicationId = @ApplicationId)
AND (UsersInRoles.RoleId = @CurrentRoleId)
AND (Application_Users.LastLogin < @StartDate)
对于循环的每条记录,我需要执行此更新:
UPDATE UsersInRoles
SET UsersInRoles.RoleId = @DenyRoleId
WHERE (UsersInRoles.ApplicationId = @ApplicationId)
AND (UsersInRoles.RoleId = @CurrentRoleId)
如果有更好的方法来执行此操作,那么我愿意接受建议。基本上,第一个查询根据INNER JOIN
执行过滤,以确定需要更新哪些记录。然后使用新的RoleID
循环并更新这些过滤的记录。
答案 0 :(得分:1)
使用加入更新:
UPDATE UIR
SET UIR.RoleId = @DenyRoleId
FROM UsersInRoles UIR
INNER JOIN Application_Users ON UIR.AppUserID = Application_Users.AppUserID
WHERE (UIR.ApplicationId = @ApplicationId)
AND (UIR.RoleId = @CurrentRoleId)
AND (Application_Users.LastLogin < @StartDate)
答案 1 :(得分:0)
您可以使用count
执行CTE
:
UPDATE
因此,您只需在;WITH ToUpdate AS (
SELECT uir.RoleId
FROM dbo.UsersInRoles AS uir
INNER JOIN Application_Users AS au
ON uir.AppUserID = au.AppUserID
WHERE (uir.ApplicationId = @ApplicationId) AND
(uir.RoleId = @CurrentRoleId) AND
(au.LastLogin < @StartDate)
)
UPDATE ToUpdate
SET RoleId = @DenyRoleId
中键入查询,然后在CTE
返回的表上执行UPDATE
。 CTE
值将传播到实际表RoleId
的记录中。