views:

2388

answers:

6

I need to update a row in a table, and get a column value from it. I can do this with

UPDATE Items SET Clicks = Clicks + 1 WHERE Id = @Id;
SELECT Name FROM Items WHERE Id = @Id

This generates 2 plans/accesses to the table. Is possibile in T-SQL to modify the UPDATE statement in order to update and return the Name column with 1 plan/access only?

I'm using C#, ADO.NET ExecuteScalar() or ExecuteReader() methods.

A: 

Use a Stored procedure for this.

Rashack
A: 

Create a stored procedure that takes the @id as a parameter and does both of those things. You then use a DbDataAdapter to call the stored procedure.

BFree
+4  A: 

Accesses table only once :

UPDATE Items SET Clicks = Clicks + 1 , @Name = Name WHERE Id = @Id;
select @name;
Learning
Marc's approach is much better because my query inherently assumes that there is one name for one Id which might/not be true.
Learning
+9  A: 

You want the OUTPUT clause

UPDATE Items SET Clicks = Clicks + 1
OUTPUT INSERTED.Name
WHERE Id = @Id
Marc Gravell
Neat, learned something new today. Thanks!
Joel Coehoorn
I guess this only works for SQL-2005
Jhonny D. Cano -Leftware-
And above, yes. With SQL Server 2000, see Learning's response
Marc Gravell
IIRC, the OUTPUT clause was introduced as part of SQL Server 2005 Service Broker - http://msdn.microsoft.com/en-us/library/ms345108.aspx
Russ Cam
Thanks, how can I retrieve the output parameter from ExecuteNonQuery?
Robert
The question cited ExecuteReader ;-p For ExecuteNonQuery, and assuming there is only 1 row, then maybe the approach Learning mentions.
Marc Gravell
ok. thanks a lot
Robert
Marc: This may be over a year later, but I needed to thank you anyway... This is the first I've heard of the OUTPUT clause, and it's *exactly* what I needed! Thanks a lot!
JMTyler
@JMTyler - you're welcome.
Marc Gravell
+2  A: 

If you're using SQL Server 2005 onwards, the OUTPUT clause is ideal for this

Russ Cam
A: 

Is there any way to achive this for Access database?

I want to update a record and then get the value.

Thanks...