在存储过程中,如何循环表A然后更新表B

时间:2017-10-10 13:11:18

标签: sql sql-server sql-server-2008 tsql

在存储过程中,我需要循环下表:

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循环并更新这些过滤的记录。

2 个答案:

答案 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返回的表上执行UPDATECTE值将传播到实际表RoleId的记录中。