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.
7条答案
按热度按时间z0qdvdin1#
You want the OUTPUT clause
l3zydbqr2#
Accesses table only once :
41ik7eoe3#
If you're using SQL Server 2005 onwards, the OUTPUT clause is ideal for this
disbfnqx4#
Use a Stored procedure for this.
ars1skjm5#
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.
dy2hfwbg6#
I could not manage to update and return one row inside a select statement. I.e you can not use the selected value from the other answers.
In my case, I wanted to use the selected value in a query. The solution I came up with was:
2q5ifsrm7#
I needed this in sqlite.
In sqlite you can do this by using the Returning clause.
For more info see: https://www.sqlite.org/lang_returning.html
You can also return all fields like this: