有一张表X,X表中只有一个字段A,且A上设了主键,用一条sql语句实现插入,插入前先判断X中是否已经存在该插入的记录了,如果存在就不插入,如果不存在就插入!记得是用1条sql语句实现!!

解决方案 »

  1.   

    if (select count(*) from table where a='a')=0 insert into a(...) values(...)
      

  2.   

    insert into X select @A where  not exist (select 1 from X where A=@A)
      

  3.   

    if not exists(select 1 from tb where A='X') insert into tb select 'X'
      

  4.   


    declare @x table(a int primary key)
    insert into @x select 1
    select * from @x
    --insert into @x select 1
    --Cannot insert duplicate key in object 'dbo.@x'.已经设置主键了,重复数据插入不了,sql server自动判断。
      

  5.   

    异常处理一下,客户肯定是看不到的。正常的处理就是先判断是否存在,存在提示客户已存在。一条语句有点搞不定。if not exists(select 1 from tb where A='X') 
    insert into tb select 'X'
    --select '插入成功'
    else
    select '已存在'
      

  6.   

    已经搞定了,谢谢ssp2009,不过你那个exist少了一个s,呵呵!!