tags:

views:

57

answers:

2

How to get updated row's PK_ID

UPDATE 
    [M_RATINGS] 
SET 
    [RATING] = @rating 
WHERE 
    [POST_ID] = @postId AND 
    [USER_ID] = @userId; 
+4  A: 

Use OUTPUT clause http://msdn.microsoft.com/en-us/library/ms177564.aspx

DECLARE @MyTableVar table(
ID int NOT NULL
); 

UPDATE 
   [M_RATINGS] 
SET   
   [RATING] = @rating 
OUTPUT INSERTED.YourPK_ID INTO @MyTableVar
WHERE 
   [POST_ID] = @postId AND 
   [USER_ID] = @userId; 

SELECT * from @MyTableVar;

Michael Pakhantsov
Like this?UPDATE [M_RATINGS] SET [RATING] = @rating OUTPUT [PK_ID]WHERE [POST_ID] = @postId AND [USER_ID] = @userId;
Venom
@Venom, I added example.
Michael Pakhantsov
@Michael But it is showing..Incorrect syntax near 'OUTPUT'.
Venom
@Venom, removed ';'
Michael Pakhantsov
@Michael Still not working :(
Venom
@Venom, what is version of your DBMS?
Michael Pakhantsov
@Michael Sql server 2008
Venom
@Venom, when you said 'non working', what so you mean? Syntax error or something else?
Michael Pakhantsov
@Michael Ya, Syntax error "Incorrect syntax near 'Output'."
Venom
@Venom, I really hope that you changed YourPK_ID to your real column name which used as primary key in table M_RATINGS.
Michael Pakhantsov
A: 

Hello All, I may be missing something, but this is not working in my place. While executing this query it gives me a error message like "Incorrect syntax near 'OUTPUT'". Please help me out. Thanks in advance.

Amit
Are you on SQL 2000 or running it against a db in SQL2K compatibility mode? (It is SQL2005+)
Martin Smith
I think we have a SQL 2000 server but i am working in the SQL Server Management Studio. I am not sure but i think it is the client side interface for the SQL Server. Now i think the way you suggest is working in the SQL 2005 and above... So what for the SQL 2000
Amit