用一条sql语句实现插入判断

szto2003 2011-01-16 07:06:38
有一张表X,X表中只有一个字段A,且A上设了主键,

用一条sql语句实现插入,插入前先判断X中是否已经存在该插入的记录了,如果存在就不插入,如果不存在就插入!

记得是用1条sql语句实现!!
...全文
380 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
szto2003 2011-01-16
  • 打赏
  • 举报
回复
已经搞定了,谢谢ssp2009,不过你那个exist少了一个s,呵呵!!
叶子 2011-01-16
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 szto2003 的回复:]
如果插入重复值,程序会提示错误啊,那客户肯定认为程序不稳定的
[/Quote]
异常处理一下,客户肯定是看不到的。

正常的处理就是先判断是否存在,存在提示客户已存在。

一条语句有点搞不定。

if not exists(select 1 from tb where A='X')
insert into tb select 'X'
--select '插入成功'
else
select '已存在'


szto2003 2011-01-16
  • 打赏
  • 举报
回复
如果插入重复值,程序会提示错误啊,那客户肯定认为程序不稳定的
叶子 2011-01-16
  • 打赏
  • 举报
回复

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自动判断。

-晴天 2011-01-16
  • 打赏
  • 举报
回复
if not exists(select 1 from tb where A='X') insert into tb select 'X'
快溜 2011-01-16
  • 打赏
  • 举报
回复 1
insert into X select @A where  not exist (select 1 from X where A=@A)
饮水需思源 2011-01-16
  • 打赏
  • 举报
回复
if (select count(*) from table where a='a')=0 insert into a(...) values(...)

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧