在SQL中的临时表中的每个不同行上的操作

时间:2017-04-10 04:43:25

标签: sql-server stored-procedures

我有一个存储过程,我正在做类似下面的事情:

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。我怎么能这样做?

1 个答案:

答案 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