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

后端 未结 9 1508
醉话见心
醉话见心 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:13

    Many years later...

    The accepted answer of using the OUTPUT clause is good. I had to dig up the actual syntax, so here it is:

    DECLARE @UpdatedIDs table (ID int)
    UPDATE 
        Table1 
    SET 
        AlertDate = getutcdate() 
    OUTPUT
        inserted.Id
    INTO
        @UpdatedIDs
    WHERE 
        AlertDate IS NULL;
    

    ADDED SEP 14, 2015:

    "Can I use a scalar variable instead of a table variable?" one may ask... Sorry, but no you can't. You'll have to SELECT @SomeID = ID from @UpdatedIDs if you need a single ID.

提交回复
热议问题