简体   繁体   中英

Update a column in table A with reference to the newest record in table B, in SQL Server

I need to periodically insert new data into two tables:

Table mstr_project , where every time I insert one project record (1 row). I have a identity column Project_ID , so each time a new project record is inserted, a project ID is automatically generated.

Table tbl_ProjectData , where every time I insert 200 rows of new data for the new project I added to table mstr_project .

My question is - how do I update the ProjectID column in tbl_ProjectData every time, so that its new records take on the newly generated Project_ID in table mstr_project ? This means every time, the 200 new records in table tbl_ProjectData will all take on the same ProjectID that is generated in table mstr_project .

Just use Scope_Identity :

DECLARE @ProjectID int;
INSERT dbo.mstr_project (Name) VALUES ('My New Project');
SET @ProjectID = Scope_Identity();

INSERT dbo.tbl_ProjectData (ProjectID, Value)
SELECT @ProjectID, Value
FROM #ProjectDataValues;

You can also capture the inserted value using the OUTPUT clause (SQL Server 2005 and up):

CREATE TABLE #NewProjectIDs (
   ProjectID int NOT NULL PRIMARY KEY CLUSTERED
);

INSERT dbo.mstr_project (Name)
OUTPUT ProjectID INTO #NewProjectIDs
SELECT 'My New Project';

INSERT dbo.tbl_ProjectData (ProjectID, Value)
SELECT N.ProjectID, V.Value
FROM
   #NewProjectIDs
   CROSS JOIN #ProjectDataValues V;

For the second code snippet, pay attention to how many rows you insert to your project table--if you insert multiple at once, you'll have to do something different to choose the correct project for each row that goes into the ProjectData table.

Note: Please stop naming your tables with "tbl_" as a prefix. You'll spare someone from murderous dreams about you some day.

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