簡體   English   中英

返回UPDATE TOP 1修改的記錄

[英]Return the record modified by UPDATE TOP 1

我有一個C#應用程序,並希望在不進行第二次查詢的情況下返回由TSQL UPDATE TOP 1更新的記錄。 這可能嗎?

您可以使用output子句。

update top (1) T
set Col = 'x'
output inserted.*
from YourTable as T

您可以使用OUTPUT ,例如:

DECLARE @tmp TABLE (Id int not null)
UPDATE TOP (1) [YourTable]
SET [YourColumn] = newValue
OUTPUT inserted.Id INTO @tmp

SELECT * FROM @tmp

(添加更多列以適應)

請注意, INTO一般情況下是必要的,以避免觸發器的問題; 否則通常會看到:

如果語句包含沒有INTO子句的OUTPUT子句,則DML語句的目標表'YourTable'不能具有任何已啟用的觸發器。

是。 這是可能的 。

DECLARE @MyTableVar table(
EmpID int NOT NULL,
OldVacationHours int,
NewVacationHours int,
ModifiedDate datetime);
UPDATE TOP (10) HumanResources.Employee
SET VacationHours = VacationHours * 1.25,
ModifiedDate = GETDATE() 
OUTPUT inserted.BusinessEntityID,
   deleted.VacationHours,
   inserted.VacationHours,
   inserted.ModifiedDate
INTO @MyTableVar;
--Display the result set of the table variable.
SELECT EmpID, OldVacationHours, NewVacationHours, ModifiedDate
FROM @MyTableVar;
GO 
--Display the result set of the table.
SELECT TOP (10) BusinessEntityID, VacationHours, ModifiedDate
FROM HumanResources.Employee;
GO

參考: http//msdn.microsoft.com/en-us/library/ms177523.aspx#CaptureResults

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM