简体   繁体   中英

Update table column with primary key after insert (in one statement)

Using an update statement, how can i directly set a column value to the primary key of an insert statement? I need this as one statement.

I know the following is wrong, but it helps get my idea through:

update AppNationalities
set CountrySelectionID = (
                            select [INSERTED.pkID] from
                            (
                                insert into CountrySelections
                                output INSERTED.pkID
                                values(CountryID, 'test', 0)
                            )
                        )

Put the values into a temporary table:

declare @ids table (pkID int);

insert into CountrySelections
    output INSERTED.pkID into @ids
    values (CountryID, 'test', 0);

update AppNationalities
    set CountrySelectionID = i.id
    from @ids i;

I don't think the output clause is allowed in the FROM clause of an UPDATE or DELETE statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM