我想根据一个简单的标准更新一组行,并获取已更改的PK列表。我以为我可以做这样的事情,但是担心并发问题:

SELECT Id FROM Table1 WHERE AlertDate IS NULL;
UPDATE Table1 SET AlertDate = getutcdate() WHERE AlertDate IS NULL;

如果将其包装在事务中,是否会发生任何并发问题?还是有更好的方法来做到这一点?

最佳答案

考虑查看OUTPUT clause:

USE AdventureWorks2012;
GO

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

关于sql - 有没有一种方法可以同时选择和更新行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/497464/

10-13 00:52