简体   繁体   中英

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?

         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 :

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]

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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