需要从源表中删除所有行,然后将删除的行插入目标表
仅在目标表中尚未存在已删除的行时
是否可以使用单个sql发布?
代码是我到目前为止尝试的代码(尽管有错误)。 谢谢!
create table #Target (column01 varchar(100)
,employee_number varchar(10)
)
Insert into #Target (column01, employee_number)
values ('2','222')
create table #Srs (column01 varchar(100)
,employee_number varchar(10)
)
Insert into #Srs (column01, employee_number)
values ('1','111')
,('2','222')
,('3','333')
,('4','444')
;with cteTable as (Select column01, employee_number from #Srs)
insert into #Target (column01, employee_number)
select * from (Delete from cteTable output deleted.column01, deleted.employee_number) t
where not exists (select 1
from #Target t1
where t1.employee_number = t.employee_number)
2,'222'不应该在调用“; with cteTable ..”时插入#Target。
答案 0 :(得分:3)
可组合DML非常有限。
如果您通过
更改#Target
的定义,则可以执行此操作
CREATE TABLE #Target
(
column01 VARCHAR(100),
employee_number VARCHAR(10) PRIMARY KEY WITH (IGNORE_DUP_KEY=ON)
)
INSERT INTO #Target
(column01,
employee_number)
VALUES ('2',
'222')
CREATE TABLE #Srs
(
column01 VARCHAR(100),
employee_number VARCHAR(10)
)
INSERT INTO #Srs
(column01,
employee_number)
VALUES ('1', '111'),
('2', '222'),
('3', '333'),
('4', '444');
WITH cteTable
AS (SELECT column01,
employee_number
FROM #Srs)
INSERT INTO #Target
(column01,
employee_number)
SELECT * from (Delete from cteTable output deleted.column01, deleted.employee_number) t
答案 1 :(得分:2)
它必须只是一个声明吗?如果没有,你可以使用它。
begin transaction;
insert into Target(column01, employee_number)
select column01, employee_number
from Srs with (updlock, holdlock)
except
select column01, employee_number
from Target;
delete from Srs;
commit transaction;