在 SQL Server 2005 上插入/更新而不使用存储过程
我正在尝试执行经典的插入/更新场景,其中我需要更新数据库中的现有行或插入它们(如果它们不存在)。
我发现了关于该主题的上一个问题,但它涉及使用存储过程,我没有使用它。 我只想使用普通的 SQL SELECT、INSERT 和 UPDATE 语句,除非有更好的可用语句(MERGE 语句在 SQL Server 2005 中不可用)。
我想我的总体想法是这样的:
If the row is found
update
else
insert
至于检查行是否存在,在调用 UPDATE 或 INSERT 之前执行 SELECT 语句的成本有多大? 或者最好尝试执行 UPDATE,检查受影响的行数,然后在受影响的行数为 0 时执行 INSERT?
I'm trying to do the classic Insert/Update scenario where I need to update existing rows in a database or insert them if they are not there.
I've found a previous question on the subject, but it deals with stored procedures, which I'm not using. I'd like to just use plain SQL SELECT, INSERT and UPDATE statements, unless there's something better available (the MERGE statement isn't available in SQL Server 2005).
I guess my general idea is this:
If the row is found
update
else
insert
As for checking for a row's existence, how expensive is it to do a SELECT statement before calling an UPDATE or an INSERT? Or is it better to just try an UPDATE, check for the number of rows affected, and then do an INSERT if the rows affected is 0?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最有效的方法是执行
UPDATE
,然后执行INSERT
(如果@@rowcount
为零),如前面的答案中所述。The most efficient way is to do the
UPDATE
, then do anINSERT
if@@rowcount
is zero, as explained in this previous answer.(首先 - 如果没有充分的理由,我不会尝试避免存储过程。在大多数情况下,这会带来很好的好处。)
您可以这样做:
如果您正在插入,这可能会运行得更快/更新大量行。
(First of all - I would not try to avoid stored procedures, if there is no strong reason. The give a good benefit in most cases.)
You could do it this way:
This will probably run faster, if you are inserting/updating large amounts of rows.
完全理解您的帖子标题为“SQL Server 2005”,但只是想在您升级到 SQL 2008 时抛出一些值得期待的内容。Microsoft 添加了一个新的 MERGE 语句,该语句将使您能够编写一个 DML 语句它同时进行更新和插入。 它太酷了。 我还没有比较性能和 I/O,但如果您的工具箱中有另一个工具,那就太好了。
Completely understand that your post was titled "SQL Server 2005" but just wanted to throw out something to look forward to if/when you upgrade to SQL 2008. Microsoft has added a new MERGE statement which will give you the ability to code one DML statement that does both the update and insert. It's pretty cool. I've yet to compare performance and I/Os but it's just great to have another tool in your toolbox.
如果您总是要去:
* 计算行数
* 根据结果插入/更新
为什么不改为:
* 删除行
* 插入行
结果相同且更整洁。
据我所知,当您更新一行时 - SQLServer 无论如何都会执行删除/插入(如果存在)
If you are always going to:
* Count the rows
* Insert / Update based on the result
Why not instead:
* Delete row
* Insert row
Same result and neater.
As far as I know when you Update a row - SQLServer does a Delete / Insert anyway (where it exists)