views:

58

answers:

3

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)
+2  A: 

[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 */
CJM
+1: Dunno what version of SQL Server, valid question about how many values can be expected to return.
OMG Ponies
A: 

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
AllenG
Does @@Identity only return the Identity of the last row INSERTed?http://msdn.microsoft.com/en-us/library/ms187342.aspx
CJM
[@@SCOPE_IDENTITY](http://msdn.microsoft.com/en-us/library/ms190315.aspx) is a better choice
OMG Ponies
This is an UPDATE query - AFAIK Scope_Identity() and @@Identity only work on INSERTS.
CJM
OMG Ponies (and everyone else) is correct. My brain farted and I went to @@Identity instead of @@SCOPE_Identity. Edit Forthcoming.
AllenG
+4  A: 

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
OMG Ponies
(+1) Never come across OUTPUT clause... been working in SQL2005/SQL2008 for long enough, but obviously still locked in SQL2000 thinking!
CJM
@CJM: I'm unfamiliar with the OUTPUT clause too - so far, I like Oracle's equivalent, the `RETURNING` clause a little more.
OMG Ponies