【问题标题】:INSERT SELECT and IGNORE_DUP_KEY, how can I retrieve discarded rows?INSERT SELECT 和 IGNORE_DUP_KEY,如何检索丢弃的行?
【发布时间】:2013-11-20 19:50:53
【问题描述】:

使用 MS-SQL,我有一个 INSERT ... SELECT 语句,它填充了一个具有唯一键 IGNORE_DUP_KEY = ON 的表。

有没有一种简单的方法可以让我得到因为重复而被丢弃的行? (最好在语句完成后)

【问题讨论】:

  • 你用什么sql? mysql? sql server 2012 ?
  • @LorenzMeyer:它需要与 MS-SQL 2005、2008 和 2012 兼容
  • @MartinSmith:我使用 IGNORE_DUP_KEY = OFF 来防止 INSERT SELECT 失败。
  • @MartinSmith:对不起,你是对的。已编辑。

标签: sql sql-server sql-server-2005 sql-server-2012


【解决方案1】:

OUTPUT clause 是这里的关键。

create table dbo.IDKsource ( 
    SNumber int not null, 
    SText varchar(100) not null  
) ;
go
insert into dbo.IDKsource 
values ( 1, 'aaaaa' ), ( 2, 'bbbbb' ), ( 1, 'cccccc' ), ( 3, 'dddddd' ) ;
go

create table dbo.IDKOntarget ( 
    SNumber int not null unique with ( ignore_dup_key = on ), 
    SText varchar(100) not null
) ;
go

-- The following lines must all be in one batch!
declare @RecordsWereInserted table (
    SNumber int not null , 
    SText varchar(100) not null
) ;

insert into dbo.IDKOntarget ( SNumber , SText )
output inserted.* into @RecordsWereInserted 
select SNumber , SText 
from dbo.IDKSource ;

select SNumber , SText 
from dbo.IDKsource 
except 
select SNumber , SText 
from @RecordsWereInserted ;

如果您希望将插入的数据保留超过一批(或者您的 SQL Server 版本不支持表变量),请将我的表变量 RecordsWereInserted 替换为实际表。

注意:我的第一种方法是直接使用带有 EXCEPT 的 INSERT 语句,但 SQL Server 不允许带有 EXCEPT、INTERSECT 或 UNION 的 DML 语句。

【讨论】:

  • +1 这很有趣,我没有意识到output inserted 还会包含由于IGNORE_DUP_KEY 而实际未插入的行
  • 没有,Martin,这就是我们必须使用 EXCEPT 查询的原因。
  • 啊,我知道我没有正确查看它。我以为您正在获取输出结果并对基表执行EXCEPT。
猜你喜欢
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-20
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
相关资源
最近更新 更多