Is there a way to SELECT and UPDATE rows at the same time?

后端 未结 9 1550
醉话见心
醉话见心 2020-12-12 21:01

I\'d like to update a set of rows based on a simple criteria and get the list of PKs that were changed. I thought I could just do something like this but am worried about po

9条回答
  •  渐次进展
    2020-12-12 21:10

    Consider looking at the 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 
    

提交回复
热议问题