Sql 在存储过程中,如何循环表a,然后更新表B
在存储过程中,我需要循环下表:Sql 在存储过程中,如何循环表a,然后更新表B,sql,sql-server,sql-server-2008,tsql,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.
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)
如果有更好的方法来实现这一点,那么我愿意接受建议。基本上,第一个查询根据内部联接进行筛选,以确定哪些记录需要更新。然后,这些过滤的记录将循环并使用新的角色ID进行更新。您可以使用CTE进行更新:
因此,只需在CTE中键入wrap查询,然后对CTE返回的表执行更新。RoleId值将传播到实际表UsersInRoles的记录 使用join更新:
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)
答案是,你需要在看待数据的方式上进行范式转换。循环效率非常低。你必须改变你的思维方式,从思考你需要做什么变成一行,而是思考你需要做什么变成一列。
;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
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)