请教条件insert语句(if insert into或者insert into where)

siu5 2014-12-23 10:01:03
用Java写了个系统,为了不让java在插入有唯一约束的表时候报错,我想在insert语句中加入判断。
但自己写了好多次,还在网上找了一下,也测试过,都报错。
我的语句是这样的:
表的结构是:id int, empSn smaillint, remark nvarchar(500)
sql语句:
insert into tn values (null, 7, '测试数据')
where not exists (select id from tn where empSn=7)
或者:
if not exists (select id from tn where empSn=7)
insert into tn values (null, 7, '测试数据')
结果总是报这个错:
Error Code : 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where not EXISTS (select id from tn where empSn=7)' at line 2
或者:
Error Code : 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if not exists (select id from tn where empSn=7)
insert into' at line 1

请问我应该怎样修改?谢谢!
...全文
1137 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
wacld 2014-12-25
  • 打赏
  • 举报
回复
MYSQL确实有这些方法,也都可以用,但是在MYSQL的存储过程、函数里面才行。 楼主的需求用可以MYSQL存储过程来实现,先判断,再插入。
ACMAIN_CHM 2014-12-24
  • 打赏
  • 举报
回复
引用 2 楼 siu5 的回复:
咦?奇怪了,那么为何能在百度找到这些错误的教人的方法的?
你可以仔细阅读一下完整的文章,如果不是断章取义,则应该是SQL Server 中的例子,而不是 MYSQL
siu5 2014-12-24
  • 打赏
  • 举报
回复
看语句就像是SqlServer的,但又确实写着是解决MySQL的问题的。 而且,在开发工具里面,输入“if”或者“exists”,就会变成蓝色,说明是能产生作用的关键字来的啊!那么怎么用呢?
siu5 2014-12-23
  • 打赏
  • 举报
回复
而且MySQL是有if和exists语句的啊???那么这两个语句怎么用呢?不会没用的吧?
siu5 2014-12-23
  • 打赏
  • 举报
回复
咦?奇怪了,那么为何能在百度找到这些错误的教人的方法的?
ACMAIN_CHM 2014-12-23
  • 打赏
  • 举报
回复
MYSQL不支持这些语句。 建议还是在JAVA中直接捕捉异常,然后处理。

56,677

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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