SQL 2008 R2:尝试使 T-SQL MERGE 语句在存储过程中工作
我已经查看了 SQL 合并语句的各种示例..所有这些看起来都很棒,尽管由于某种原因我似乎无法从合并测试中获得正确/预期的结果。
快速概述: 我有一个简单的表,其中包含一些设计数据..阅读有关 MERGE 的内容似乎指出了一种更有效的方法来执行'upsert'(即:插入或更新取决于记录是否存在或不)。
所以 SQL 2008 代码是这样的(抱歉,如果它不完全完整,因为我正在处理它!):
这将在一个存储过程中,所以 @values 显然是传递的参数..< /em>
merge designs as ds
using ( select designname, designcode from designs) as dsi
on (@passedDesignName = dsi.designname and @passedDesignCode = dsi.designcode)
when matched then
update set ds.designname = @passedDesignName, ds.designcode = @passedDesignCode
when not matched then
insert (designname, designcode)
values (@passedDesignName, @passedDesignCode)
这个问题似乎出在我正在测试的 7 条记录中,所有这些记录似乎都已更新,显然我只能看到一条与更新匹配的记录..奇怪的是,如果我通过一些新的记录数据(设计名称和设计代码),我似乎得到了重复的插入。从我上次的测试来看,似乎有 7 个新插入,我猜这不仅仅是侥幸。
希望我已经正确解释了这一点。攻击新事物的一部分大部分情况下上下文都是正确的吗?
预先感谢您的任何反馈。
PS:抱歉,合并语句末尾有一个分号!完成解析检查/语法。
I have looked at various example of the SQL Merge statement.. all of which look excellent, albeit for some reason I cannot seem to get the correct/expected results from my Merge test.
Quick overview:
I have a simple table with some design data in it.. and reading about MERGE seems to point to a more efficient way of doing an 'upsert' (i.e: an Insert or Update depending if the record exists or not).
So the SQL 2008 code goes something like this (sorry if it is not fully complete, as I am working on it!):
This will be in a stored procedure, so the @values are obviously the passed params..
merge designs as ds
using ( select designname, designcode from designs) as dsi
on (@passedDesignName = dsi.designname and @passedDesignCode = dsi.designcode)
when matched then
update set ds.designname = @passedDesignName, ds.designcode = @passedDesignCode
when not matched then
insert (designname, designcode)
values (@passedDesignName, @passedDesignCode)
The issue seems to be out of the 7 records I am testing with, ALL of them seem to be updated, when clearly I can only see one record that matches the update.. and the strange thing is if I pass some NEW data (designname and designcode), I seem to get a repeating insert.. from my last test it seemed 7 new inserts which I am guessing isn't just a fluke..
Hope I have explained this correctly.. part of attacking something new is mostly getting the context correct right?
Thanks in advance for any feedback.
P.S: Sorry, there is a semi-colon at the end of the merge statement! to complete the parse checking/syntax.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用
designs
作为目标表和源表:这相当于:
相反,尝试将变量作为源表传递:
You're using
designs
as both the target and the source table:This is equivalent to:
Instead, try to pass the variables as the source table: