Reputation: 7520
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)
Upvotes: 0
Views: 15710
Reputation: 8190
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
Upvotes: 0
Reputation: 12016
[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 */
Upvotes: 2
Reputation: 332571
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
Upvotes: 4