我正在将新记录插入到Person表中,如果已经有一个具有相同SSN的记录,我想将这个旧记录备份到另一个表(让我们称之为PersonsBackup)并使用我的新值更新该行。 Person表中有一个标识列作为我的主键,它必须是相同的。
源表结构:
Name | Addr | SSN
人员表结构:
PrimaryKeyID | Name | Addr | SSN
PersonBackup表结构:
BackupKeyID | Name | Addr | SSN | OriginalPrimaryKeyID
其中OriginalPrimaryKeyID =已备份记录的PrimaryKeyID。如何才能做到这一点?我正在考虑使用游标来检查SSN是否匹配,然后相应地插入该记录,但我被告知使用这样的游标是非常低效的。谢谢你的帮助!
答案 0 :(得分:2)
您可以这样做,使用MERGE组合插入/更新
INSERT INTO PersonBackup
SELECT P.Name, P.Addr, P.SSN, P.PrimaryKeyID
FROM Person P
INNER JOIN source s ON P.SSD = s.SSD
MERGE Person AS target
USING (SELECT Name, Addr, SSN FROM SOURCE) AS source (NAME, Addr, SSN)
ON (target.SSN = source.SSN)
WHEN MATCHED THEN
UPDATE SET name = source.name, Addr = source.Addr
WHEN NOT MATCHED THEN
INSERT(Name, Addr, SSN)
VALUES(source.name, source.addr, source.SSN)
答案 1 :(得分:0)
这是一些让你开始的伪代码:
所以有些提示:
答案 2 :(得分:0)
假设BackupKeyID
表中的PersonBackup
是身份,您可以尝试使用update
子句后跟output
语句,后跟insert
不存在的记录在目标表中:
update p
set p.Name = s.Name, p.Addr = s.Addr
output deleted.Name, deleted.Addr,
deleted.SSN, deleted.PrimaryKeyID into PersonBackup
from Source s
join Person p on p.SSN = s.SSN;
insert into Person (Name, Addr, SSN)
select s.Name, s.Addr, s.SSN
from Source s
where not exists (select 1 from Person where SSN = s.SSN);
或在单个语句中使用insert into ... from (merge ... output)
构造:
insert into PersonBackup
select Name, Addr, SSN, PrimaryKeyID
from
(
merge Person p
using (select Name, Addr, SSN from Source) s
on p.SSN = s.SSN
when matched then
update set p.Name = s.Name, p.Addr = s.Addr
when not matched then
insert (Name, Addr, SSN) values (s.Name, s.Addr, s.SSN)
output $action, deleted.Name, deleted.Addr, deleted.SSN, deleted.PrimaryKeyID)
as U(Action, Name, Addr, SSN, PrimaryKeyID)
where U.Action = 'UPDATE';
答案 3 :(得分:0)
DECLARE @TEMP TABLE (SSN VARCHAR(100),Name VARCHAR(MAX),Addr VARCHAR(MAX) ),
@SSN VARCHAR(100),
@Name VARCHAR(MAX),
@ADDR VARCHAR(MAX)
//INSERT YOUR VALUES INTO THIS TEMP VARIABLE FIRST.
SET @SSN = (SELECT SSN FROM @TEMP)
SET @Name = (SELECT NAME FROM @TEMP)
SET @Addr = (SELECT ADDR FROM @TEMP)
IF EXISTS (SELECT 1 FROM Person_table WHERE SSN = @SSN)
BEGIN
//BACKUP FIRST
INSERT INTO PersonBackup_table
SELECT * FROM Person_table WHERE SSN = @SSN
//UPDATE NEXT
UPDATE A
SET A.NAME = @NAME,
A.ADDR = @ADDR
FROM Person_table A
WHERE A.SSN = @SSN
END
ELSE
BEGIN
INSERT INTO Person_table VALUES @Name,@Addr,@SSN
END