更新表并插入缺少的记录

时间:2018-06-12 14:51:02

标签: sql sql-server sql-server-2016

我有一个带有外键列的表,其中包含一些NULL记录。我可以选择缺少列的记录,例如:

SELECT * FROM Outgoing WHERE Receipt_Id IS NULL

现在,对于每个记录,我想在表Receipts中插入新记录,获取插入的记录Id并将其设置为Receipt_Id的值在这个记录中。

查询中是否可以这样做?

2 个答案:

答案 0 :(得分:0)

看来你正在寻找inserted

INSERT INTO Receipts (col1, col2....)
OUTPUT INSERTED.*
INTO @CreatedIds -- TEMP TABLE WHICH HOLDS RECENTLY INERTED DATA INCLUDING Receipt_Id (pk)
SELECT col1, col2.... 
FROM Outgoing 
WHERE Receipt_Id IS NULL

至,查看最近插入的记录

SELECT c.*
FROM @CreatedIds c -- Note this is a table variable that you need to manual create.

答案 1 :(得分:0)

更新:由于您只将Receipt表用作序列表。您应该遵循使用序列的更新方法

更新答案:

您需要做的就是创建一个序列说收据而不是一列的表。然后使用序列号更新Outgoing表。

   --create table Outgoing ( id int Primary Key IDENTITY(1,1),data nvarchar(100), record_id int);
--insert into Outgoing values ('john',NULL),('jane',NULL),('jean',NULL);

create sequence dbo.receipts as int start with 1 increment by 1;

update Outgoing
set record_id= NEXT VALUE FOR dbo.receipts
where record_id is null

select * from Outgoing

See working demo

下面的旧答案

如果两个表中都有ID列,您可以根据此列将Receipt_Id更新回Outgoing

所以你的步骤是: 1.插入记录

DECLARE @LastRID bigint 
SELECT @LastRID= MAX(Id) FROM Receipts
INSERT INTO Receipts(<col list>)
SELECT <col list> FROM Outgoing WHERE Receipt_Id IS NULL

使用CHECKSUM函数

根据从传出到收据插入的所有列的唯一性更新记录
update O
set O.Receipt_Id=R.Id
From Outgoing  O
Join Receipts R 
on CHECKSUM(o.<col list>)=CHECKSUM(R.<col list>)
and R.Id>@LastRID