我有一个存储过程,我正在做类似下面的事情:
DECLARE @RemainingCount INT
DECLARE @DeletedUser Table(
UserID NVARCHAR(100))
DELETE esi
OUTPUT Deleted.UserID INTO @DeletedUser(UserID)
FROM dbo.TableA esi
WHERE esi.UserID = @UserID --@UserID is one of the parameters passed to the SP
AND esi.ColumB = @ColumnBValue --@ColumnBValue is another parameter to the SP
SELECT @RemainingCount = COUNT(*)
FROM TableA es
INNER JOIN @DeletedUser du ON es.UserID = du.UserID
IF @RemainingCount = 0
BEGIN
UPDATE at
SET at.TotalUsers = at.TotalUsers - 1
FROM TableB at
WHERE at.TotalUsers > 0
AND at.[key] = @SomeParam --@SomeParam is another parameter to the SP
END
这里不是为@DeletedUser
表中存在的UserIds的所有剩余计数调用最后一次更新,而是想循环遍历@DeletedUser
表并在下面对@DeletedUser
中的所有不同UserID执行操作。 {1}}表:
SELECT @RemainingCount = COUNT(*)
FROM TableA es
INNER JOIN @DeletedUser du ON es.UserID = du.UserID
IF @RemainingCount = 0
BEGIN
UPDATE at
SET at.TotalUsers = at.TotalUsers - 1
FROM TableB at
WHERE at.TotalUsers > 0
AND at.[key] = @SomeParam --@SomeParam is another parameter to the SP
END
所以基本上我想为@RemainingCount
表中的每个UserID
计算@DeletedUser
。我怎么能这样做?
答案 0 :(得分:0)
当您使用INNER JOIN
时,您的RemainingAmout
将为0。
您不需要遍历DeletedUser中的所有UserId。
据我了解,此查询应该有效
SELECT @RemainingCount = COUNT(DISTINCT de.UserId)
FROM @DeletedUser de
WHERE NOT EXISTS (SELECT 1 FROM TableA es WHERE es.UserId = de.UserId)
IF @RemainingCount > 0
BEGIN
UPDATE at
SET at.TotalUsers = at.TotalUsers - @RemainingCount
FROM TableB at
WHERE at.TotalUsers > 0
AND at.[key] = @SomeParam --@SomeParam is another parameter to the SP
END