仅当表中尚不存在某个值时才插入 SQL?
仅当表中尚无该数字时,如何将数字插入表中?
我正在寻找特定的 SQL 代码,不太确定如何解决这个问题。尝试了几件事,没有任何效果。
编辑
表如下所示:
PK ID Value
1 4 500
2 9 3
因此,如果我尝试INSERT (ID, Value) VALUES (4,100)
,它不应该尝试这样做!
How to insert a number into the table, only if the table does not already have that number in it?
I am looking for specific SQL code, not really sure how to approach this. Tried several things, nothing's working.
EDIT
Table looks like this:
PK ID Value
1 4 500
2 9 3
So if I am trying to INSERT (ID, Value) VALUES (4,100)
it should not try to do it!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果
ID
应该是唯一的,则应该在表上定义唯一约束。如果您尝试插入已经存在的值,这将引发错误如果尝试插入重复的键,您可以捕获错误并执行您想要的任何操作 - 从忽略错误到记录和重新引发错误引发自定义异常的例外
您还可以对 INSERT 进行编码,以便插入 0 行(从数据模型的角度来看,您仍然希望存在唯一约束,因为它为优化器提供了更多信息并且可能使将来的查询更加高效)
或者您可以编写
MERGE
代码,以便将VALUE
列从 500 更新为 100,而不是插入新行。If
ID
is supposed to be unique, there should be a unique constraint defined on the table. That will throw an error if you try to insert a value that already existsYou can catch the error and do whatever you'd like if an attempt is made to insert a duplicate key-- anything from ignoring the error to logging and re-raising the exception to raising a custom exception
You can also code the
INSERT
so that it inserts 0 rows (you would still want the unique constraint in place both from a data model standpoint and because it gives the optimizer more information and may make future queries more efficient)Or you could code a
MERGE
instead so that you update theVALUE
column from 500 to 100 rather than inserting a new row.尝试 MERGE 语句:
Try MERGE statement:
当然,那个“1”将是你的数字或你的变量。
可以使用INSERT+SELECT来解决这个问题。
Of course, that '1' will be your number or your variable.
You can use INSERT + SELECT to solve this problem.