sql server查询返回一个值

时间:2010-07-30 19:08:11

标签: sql sql-server tsql

下面是我的查询,它正在更新User表中的记录,我希望查询返回已更新的UserId,我该怎么做?

         UPDATE USER
            SET GroupID = @New_GroupID
           FROM USER 
LEFT OUTER JOIN DOCUMENTS ON User.UserID = Documents.UserID
          WHERE (Documents.UNC = @UNC) 
            AND (User.GroupID = @Old_GroupID)

3 个答案:

答案 0 :(得分:4)

对于SQL Server 2005+,您可以使用OUTPUT clause

UPDATE USER
   SET GroupID = @New_GroupID
OUTPUT INSERTED.id AS ID
     FROM USER u
LEFT JOIN DOCUMENTS d ON d.userid = u.userid
    WHERE d.UNC = @UNC 
      AND u.GroupID = @Old_GroupID

答案 1 :(得分:2)

[Scratch previous answer - 我读INSERT而不是UPDATE]

您的查询是否始终只更新一行?

Declare @ID int

SELECT @ID=User.UserID
FROM User 
LEFT OUTER JOIN Documents ON User.UserID = Documents.UserID
WHERE     (Documents.UNC = @UNC) AND (User.GroupID = @Old_GroupID)

UPDATE User
Set GroupID = @New_GroupID
Where UserID = @ID

If @@RowCount = 1
 Return @ID
Else
 Return -1  /* problem - multiple rows updated */

答案 2 :(得分:0)

如果UserId是您的标识列,请在当前更新语句后添加Select @@Scope_Identity

如果没有,您只需要稍加修改:

Update User
Set GroupID = @New_GroupID
FROM  User LEFT OUTER JOIN
      Documents ON User.UserId = Documents.UserID
WHERE Documents.UNC = @UNC AND User.GroupID = @Old_GroupID

Select UserId from User where [YourIdentityColumn] = @@Scope_Identity