如何在sql表中找到唯一的对值?

时间:2012-07-10 15:30:17

标签: sql tsql

  

可能重复:
  Finding duplicate values in a SQL table

我对T-Sql和Sql编程完全不熟悉,所以我希望有人可以引导我朝着正确的方向前进。这是我的问题..为了简单起见,我有一个只有2列的表,AppliedBandwidthSourceKey和AppliedBandwithSource我将分别称它们为A列和B列。

列A和B组成主键。当我尝试插入一个记录,其中列A的值已经存在时,我立即得到一个主键约束违规,如果列A不存在,但是列B,我得到唯一键约束违规。我的问题是如何检查表中是否已存在“值对”?如果不这样做,否则插入。

我已经看到使用tsql的合并以及如果不存在语句的类似问题的几种解决方案,但我无法理解这个概念。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:1)

你可以这样做:

IF NOT EXISTS (select * from yourtable where yourfield1 = 'field1' and yourfield2 = 'field2')
BEGIN
    INSERT INTO ...
END

如果找不到数据,只需将数据插入yourtable即可。

答案 1 :(得分:1)

你实际上不必先做这项工作。 。 。毕竟,这就是约束正在做的事情。

相反,了解try / catch块:

begin try
    insert into t(a, b) values('a', 'b')
end try
begin catch
    print 'Oops! There was a problem, maybe a constraint violation for example'
end catch;

此语句尝试插入。如果出现故障,则进入“捕获”部分,您可以做任何您想做的事情(包括忽略问题)。文档相当清楚(http://msdn.microsoft.com/en-us/library/ms175976.aspx)。

答案 2 :(得分:0)

使用count语句,其中(A和B)如果count返回0,则该对不存在。如果它返回的数字不是0(X),则条目对存在(X)次。

答案 3 :(得分:0)

在某些情况下,您可以使用左/右连接,加入PK:

insert into tableA (Id,AnotherId)
select b.Id, b.AnotherId
from tableB b
left join tableA a
    on b.Id = a.id
        and b.AnotherId = a.AnotherId
where a.Id is null

另一个左连接版本:

insert into tableA (Id,AnotherId)
select b.Id, b.AnotherId
from (select Id = 5, AnotherId = 5) b
left join tableA a
    on b.Id = a.id
        and b.AnotherId = a.AnotherId
where a.Id is null
and a.Id is null