57

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.

Robert
  • 1,567
  • 4
  • 14
  • 12

7 Answers7

110

You want the OUTPUT clause

UPDATE Items SET Clicks = Clicks + 1
OUTPUT INSERTED.Name
WHERE Id = @Id
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
24

Accesses table only once :

DECLARE @Name varchar(MAX);

UPDATE Items SET Clicks = Clicks + 1 , @Name = Name WHERE Id = @Id;
SELECT @Name;
Serg
  • 2,346
  • 3
  • 29
  • 38
Learning
  • 8,029
  • 3
  • 35
  • 46
4

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

Russ Cam
  • 124,184
  • 33
  • 204
  • 266
0

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:

declare @NextId int
set @NextId = (select Setting from Settings where key = 'NextId')

select @NextId + ROW_NUMBER() over (order by SomeColumnOfYourTable) from YourTable

update Settings set Setting = Setting + @@ROWCOUNT 
where key = 'NextId'
Kobbe
  • 809
  • 5
  • 16
0

Use a Stored procedure for this.

Rashack
  • 4,667
  • 2
  • 26
  • 35
0

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
  • 102,548
  • 21
  • 159
  • 201
0

I needed this in sqlite.

In sqlite you can do this by using the Returning clause.

UPDATE Items SET Clicks = Clicks + 1
WHERE Id = @Id
Returning Name

For more info see: https://www.sqlite.org/lang_returning.html

You can also return all fields like this:

UPDATE Items SET Clicks = Clicks + 1
WHERE Id = @Id
Returning *
raddevus
  • 8,142
  • 7
  • 66
  • 87