--加唯一性索引。
alter table tbname add constraint uniquename unique (colname)

解决方案 »

  1.   

    IF NOT EXISTS(SELECT * FROM INSERTED GROUP BY COL1 HAVING COUNT(X)>1)
    BEGIN
      执行语句
    END
      

  2.   

     if not exists(select 1 from tb where a=@a and b=@b and c=@c)
       insert ...
      

  3.   

    if not exists(select * from A  inner join inserted i on A.x=i.x)
      insert
      

  4.   

    忘了说了,那个表已经是有记录的,要提供给前台应用程序,所以表可能不方便重新设计,
    我说的插入重复是这个意思
    表A
    id  x
    1   n1
    2   n2
    3   n3我插入的记录是这样的
    id    x
    100   n2
    101   n4
    102   n5
    103   n5
    包括两个相同的n2,要同时插入到表A,这时候我希望系统有提示 要插入的n2在A中有重复记录,待插入的n5也是重复的不知道这样sql能不能实现
      

  5.   

    --2种方法
    --1
    --在字段X上加unique 约束
    --2
    --在触发器中加入以下判断
    if exist(select * from inserted group by x having count(*)>1)
    print '已经插入重复记录'
    else
    .......
      

  6.   

    if exist(select * from inserted group by x having count(*)>1)
    begin
        select '原来的a表已经有数据'+ X from inserted where [id] in (select [id]from a )
     end 
     else....
      

  7.   


    --你想终止的话就
    if exist(select * from inserted group by x having count(*)>1)
    begin
        select '原来的a表已经有数据'+ X from inserted where [id] in (select [id]from a )
    rollback
     end 
     else....
    --如果你不想终止的话就直接
    if exist(select * from inserted group by x having count(*)>1)
    begin
        select '原来的a表已经有数据'+ X from inserted where [id] in (select [id]from a )
    rollback
     end 
     else....
      

  8.   

    同时插入多条,是哪种方式?insert tb values()
    insert tb values()
    还是
    insert tb select ....
    --后者的话,要用游标判断。
      

  9.   

    写法还是看应用场景。如果是在应用程序代码中或是在存储过程中,insert之前判断一下就行了,先判断待插入的记录集不允许重复,再判断插入的集不能已经存在;如果真的无法通过程序的方式判断,估计就只能在SQL中用语句过滤一下先再insert,不过就不能像代码中那样把几种错误都详细地报出来了
      

  10.   

    是在前台程序做的批量增加,我看了记录是用INSERT INTO ... VALUES ....这样做的
      

  11.   

    insert into table1 select column1,column2,...... from table2 where column1 not in (select column1 from table1)table1是你要插入数据的表,column1是你要防止重复的字段,最后不要用in,该代码还可以划简。
    这种写法必须table1中有一些数据了,否则会无法插入数据,这点还要改进。
      

  12.   

    楼上兄弟,我说insert into ...values...是应用程序插入的方式,这个我没办法修改,定下来就是用这样的方式插入进去的,现在只能从存储过程或者触发器的角度看能不能改一下了