简体   繁体   English

sql server查询返回值

[英]sql server query to return a value

Below is my query which is updating a record in the User table , I want the query to return the UserId which was updated, How can I do this? 以下是我的查询,该查询正在更新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)

For SQL Server 2005+, you can use the OUTPUT clause : 对于SQL Server 2005+,可以使用OUTPUT子句

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

[Scratch previous answer - I read INSERT rather than UPDATE] [抓取先前的答案-我读的是INSERT,而不是UPDATE]

Is your query always going to update a single row only? 您的查询是否总是只更新一行?

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 */

If UserId is your Identity colum, add Select @@Scope_Identity after your the current update statement. 如果UserId是您的Identity列,请在当前更新语句之后添加Select @@Scope_Identity

If not, you only need a little modification: 如果没有,您只需要做一点修改:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM