我想实现在插入的数据时,先检查该数据是否已在数据库中已经存在,如果存在就不行执行,反之则执行insert语句?
原本以为很简单,做起来却不知道如何下手了。:(

解决方案 »

  1.   

    Create Trigger In_sert 
    on Table1
    for insert
    as
    if exists (select 1 from Table1 a,Inserted b where a.checksum(*)=b.checksum(*))
    rollback
    end
      

  2.   

    create table a( id int)
    insert a
    select 1
    union all
    select 2
    union all
    select 3
    create proc cx 
    @i int --待插入数据
    as
      begin transaction 
    if exists(select id from a where id=@i)
    begin 
      rollback transaction 
      begin transaction 
    end
      else begin
      insert a(id)
      select @i
    end  
      commit transaction exec cx @i=1
    exec cx @i=4
    select * from adrop table a
    drop proc cxid          
    ----------- 
    1
    2
    3(所影响的行数为 3 行)id          
    ----------- 
    1
    2
    3
    4(所影响的行数为 4 行)
      

  3.   

    declare @a int
    declare @b varchar(20)
    select @a = count(*) from tablename 
    where columnname = @b
    if(@a > 0)
    begin 
    insert into ...
    end