Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

sql - Output Inserted.Id AND another field

I have the following query:

DECLARE @OutProduct TABLE 
(
    ProductID INT,
    BulkProductId INT
)

INSERT INTO dbo.Products 
        ( EanCode , 
          ChangedDateTime , 
          ChangedById , 
          Deleted  
        ) 
OUTPUT INSERTED.ID, BulkProducts.Id INTO @OutProduct (ProductID, BulkProductId)
SELECT  EanCode , 
        GETDATE(), 
        GETDATE(),
        0 
FROM dbo.BulkProducts 
WHERE ProductId is NULL

Assuming Products.Id & BulkProducts.Id are auto-incrementing identity columns:

What I'm trying to achieve:

@OutProduct temp table contains tuples made up of the just-inserted Products.Id and the Id of the row in BulkProducts.

What I've stumbled upon: BulkProducts.Id cannot be used in the OUTPUT INSERTED.ID, BulkProducts.Id INTO statement, as it's not valid syntax.

How can I solve this?

EDIT: I'm using SQL Server 2012.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You might want to explore MERGE:

MERGE INTO dbo.Products
USING dbo.BulkProducts AS src
    ON 1 = 0 -- Never match
WHEN NOT MATCHED THEN
    INSERT(EanCode, ChangedDateTime, ChangedById, Deleted)
    VALUES(src.EanCode, GETDATE(), GETDATE(), 0)
OUTPUT
    inserted.Id,
    src.Id
INTO @OutProduct;

Reference:

Dr. OUTPUT or: How I Learned to Stop Worrying and Love the MERGE by Adam Machanic


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...