SQL: Update a row and returning a column value wit

2019-01-06 12:35发布

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.

6条回答
不美不萌又怎样
2楼-- · 2019-01-06 13:15

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-01-06 13:18

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

查看更多
干净又极端
4楼-- · 2019-01-06 13:26

Accesses table only once :

UPDATE Items SET Clicks = Clicks + 1 , @Name = Name WHERE Id = @Id;
select @name;
查看更多
别忘想泡老子
5楼-- · 2019-01-06 13:30

You want the OUTPUT clause

UPDATE Items SET Clicks = Clicks + 1
OUTPUT INSERTED.Name
WHERE Id = @Id
查看更多
手持菜刀,她持情操
6楼-- · 2019-01-06 13:33

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'
查看更多
甜甜的少女心
7楼-- · 2019-01-06 13:35

Use a Stored procedure for this.

查看更多
登录 后发表回答