将记录新插入的ID插入子记录SQL Server OUTPUT子句

时间:2015-08-07 18:38:38

标签: sql-server

我有一个ProjectStaging表,我希望根据StagingID字段的不匹配将记录插入到我的Project表中。 Project表有自己的自动递增ProjectID。这部分如果罚款(使用NOT EXISTS)。

接下来,我想为每个插入的项目创建三个ProjectLineItems,其中新插入的ProjectID以及Status字段中的默认设置1,2和3。我正在使用OUTPUT提取ProjectID,将id保存到TempTable并稍后将其存储在变量@NewProjectID中以插入3个行项目。但我得到一个错误,说ProjectID为null。那为什么会这样?我的OUTPUT ID是否没有进入TempTable?

---这是SQL

DECLARE @NewProjectID int
DECLARE @TempTable TABLE(id int) 

INSERT INTO Project
    (
    StagingID,
    Field1,
    Field2
    )
    OUTPUT INSERTED.ProjectID INTO @TempTable(id)
    SELECT
    StagingID,
    Field1,
    Field2
    FROM ProjectStaging
WHERE NOT EXISTS (
    SELECT * FROM ProjectStaging WHERE Project.StagingID = ProjectStaging.StagingID)

    SELECT @NewProjectID = id FROM @TempTable 

    INSERT INTO ProjectLineItems(ProjectID, Status) VALUES(@NewProjectID, 1)
    INSERT INTO ProjectLineItems(ProjectID, Status) VALUES(@NewProjectID, 2)
    INSERT INTO ProjectLineItems(ProjectID, Status) VALUES(@NewProjectID, 3)

2 个答案:

答案 0 :(得分:0)

您是否尝试过:而不是插入内的OUTPUT: SELECT @NewProjectID = (SELECT IDENT_CURRENT('ProjectStaging'))

这会将@NewProjectID设置为ProjectID

的最后插入标识值的值

为什么这对你不起作用?

所以你的新代码将是:

DECLARE @NewProjectID int

INSERT INTO Project
    (
    StagingID,
    Field1,
    Field2
    )
    SELECT
    StagingID,
    Field1,
    Field2
    FROM ProjectStaging
WHERE NOT EXISTS (
    SELECT * FROM ProjectStaging WHERE Project.StagingID = ProjectStaging.StagingID)

    SELECT @NewProjectID = (SELECT IDENT_CURRENT('ProjectStaging'))

    INSERT INTO ProjectLineItems(ProjectID, Status) VALUES(@NewProjectID, 1)
    INSERT INTO ProjectLineItems(ProjectID, Status) VALUES(@NewProjectID, 2)
    INSERT INTO ProjectLineItems(ProjectID, Status) VALUES(@NewProjectID, 3)

答案 1 :(得分:0)

我认为你遗漏了一些东西......你想插入Project中的东西,但是在Project中不存在吗?

然后你希望你的陈述看起来像这样:

INSERT INTO Project
    (
    StagingID,
    Field1,
    Field2
    )
    OUTPUT INSERTED.ProjectID INTO @TempTable(id)
    SELECT
    StagingID,
    Field1,
    Field2
    FROM ProjectStaging
WHERE NOT EXISTS (
    SELECT * 
    FROM ProjectStaging Stage
    JOIN Project Proj ON Stage.StagingID = Proj.StagingID)

你的表也可以有多行,如果有的话

 SELECT @NewProjectID = id FROM @TempTable 

会出错

要使用该表,请执行以下操作:

INSERT INTO ProjectLineItems(ProjectID, Status)
  SELECT ID, ROW_NUMBER() OVER (ORDER BY ID)
  FROM @TempTable