[英]Using SQL OUTPUT for INSERT into a table with Identity (or default values)
I am inserting records into a table (Payments) that require a sequence number. 我将记录插入到需要序列号的表(付款)中。 I get and increment this sequence number from another table (SequenceNumbers) using an UPDATE statement with a OUTPUT clause.
我使用带有OUTPUT子句的UPDATE语句从另一个表(SequenceNumbers)中获取并递增该序列号。
UPDATE [SequenceNumbers] SET SequenceNo = SequenceNo + 1
OUTPUT INSERTED.SequenceNo
WHERE EstateId = @EstateId
I was hoping to be able to combine the above UPDATE statement together with the Payments INSERT statement using OUTPUT INTO such as below 我希望能够将UPDATE语句与Payments INSERT语句结合使用OUTPUT INTO,如下所示
UPDATE [SequenceNumbers] SET Sequence = Sequence + 1
OUTPUT @EstateId AS EstateId,
INSERTED.SequenceNo AS SequenceNo
INTO Payments
WHERE EstateId = @EstateId
but when tested you have to supply all fields in the target table. 但是经过测试后,您必须提供目标表中的所有字段。 What I want to do is use the automatic Identity value for the Id field in the Payments table together with default values for any missing fields.
我想做的是将Payments表中Id字段的自动Identity值与所有缺失字段的默认值一起使用。
I then need to return the Id (Identity) value in the Payments table to the caller. 然后,我需要将Payments表中的Id(身份)值返回给调用方。
I wondering if this is possible or whether there is another alternative? 我想知道这是否可能,或者是否还有其他选择?
I have put simplified examples of the Payments and SequenceNumbers tables below for reference. 我在下面放置了Payments和SequenceNumbers表的简化示例,以供参考。
CREATE TABLE [Payments](
[EstateId] INT NOT NULL,
[Id] INT NOT NULL IDENTITY ,
[SequenceNo] INT NOT NULL DEFAULT 0,
.... other fields
PRIMARY KEY ([EstateId], [Id])
)
CREATE TABLE [SequenceNumbers] (
[EstateId] INT NOT NULL,
[SequenceNo] INT DEFAULT ((0)) NOT NULL,
PRIMARY KEY CLUSTERED ([EstateId] ASC)
)
You just need to specify which columns in Payments
to insert into: 您只需要指定要插入“
Payments
哪些列即可:
UPDATE [SequenceNumbers]
SET Sequence = Sequence + 1
OUTPUT Inserted.EstateId, Inserted.SequenceNo
INTO Payments(EstateId, SequenceNo) -- define what columns to insert into!
WHERE EstateId = @EstateId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.