在插入之前检查主键值是否比使用 try-catch 更快? [英] Is checking for primary key value before insert faster than using try-catch?

查看:51
本文介绍了在插入之前检查主键值是否比使用 try-catch 更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有一个包含两个字段的主键列(memberid、messageid)的表,并且我有一个存储过程,可以在该表中插入一个新行.

Basically I have a table with two-field primary key column (memberid, messageid) and I have a stored proc that inserts a new row into that table.

现在我检查是否存在带有 PK 的行,如果不存在则插入,但是我已经遇到了在检查之后和实际插入之前由不同进程插入该行的情况,所以我正在考虑另一种方式.

Right now I check if a row with the PK exists and insert if not, but I have already ran into situation when the row was inserted by a different process at the time right after the check and before the actual insert, so I'm thinking of an alternative way.

出于性能原因,我不想使用事务,所以我想将 INSERT 包含在 try-catch 中并完全跳过检查.如果该行已经存在,插入将失败,但会被catch"静音,这是可以的.

I DO NOT want to use transactions for performance reasons, so I was thinking of enclosing the INSERT into try-catch and skipping the check altogether. If the line already exists insert will fail but will be silenced by "catch" which is ok.

我的问题是 - 抛出错误并捕获它是一项昂贵的操作吗?

My question is - is throwing an error and catching it an expensive operation?

推荐答案

如果您不希望失败经常发生,那么可以通过异常进行处理.

If you don't expect failures to happen too often then it is ok to handle it via exceptions.

每次都进行检查会降低数据库性能,这也会影响应用程序性能...

Doing the check everytime will reduce db perfomance which could affect application perfomance as well...

这篇关于在插入之前检查主键值是否比使用 try-catch 更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆