简体   繁体   中英

How can i make an insert of a SCOPE_IDENTITY() into update in SQL SERVER

I want to insert an id that i created into an update of each row:

    UPDATE TABLE1
    SET NAME=(INSERT INTO TABLE2(EVT01,EVT02) values(0,0)
    SELECT @id=SCOPE_IDENTITY() )
    FROM TABLE1
    INNER JOIN  TABLE2 ON ......

How can i make that in SQL Server?
Thanks.

Declare @NewId  Int

INSERT INTO TABLE2(EVT01,EVT02) values(0,0)

Select  @NewId = @@Identity

UPDATE  t1
SET     t1.NAME = t2.Name
FROM    TABLE1 As t1
        Join TABLE2 As t2 On t1.somecolumn = t2.Id
Where   t2.Id = @NewId

Edit:-

----- Table SourceTable

Insert Into TABLE2(EVT01,EVT02)
Select   Col1
        ,Col2
From    SrouceTable

Update  t1
Set     t1.Name = t2.Id
From    TABLE1 As t1
        Join TABLE2 As t2 On t1.Somecolumn = t2.Id
        Join SourceTable As st On t2.EVT01 = Col1   ----Assumed there would be unique matching column

You can create an Insert Trigger on Table2 to Update Table1 using Inserted table:

CREATE TRIGGER [dbo].[YourTriggerName]
   ON  [dbo].[Table2]
   AFTER  INSERT 
AS 
BEGIN
      UPDATE t1
      SET NAME= t2.IdColName
      FROM Table1 t1
         INNER JOIN  Inserted t2 ON ......

END

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