2

需要从源表中删除所有行,然后
仅当目标表中尚不存在已删除的行时,才将已删除的行插入目标表。
是否可以使用单个 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' 插入 #Target on call to ";with cteTable.."

SQL 小提琴演示

4

2 回答 2

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  
于 2013-08-06T05:56:15.653 回答
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;
于 2013-08-06T06:14:08.820 回答