解析SQL Server 2008中的新语句:MERGE

来源:互联网 发布:摄乎大国之间的摄 编辑:程序博客网 时间:2024/05/21 13:56
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
 

SQL Server 2008将包含用于合并两个行集(rowset)数据的新句法。根据一个源数据表对另一个数据表进行确定性的插入、更新和删除这样复杂的操作,运用新的MERGE语句,开发者用一条命令就可以完成。

 

对两个表进行信息同步时,有三步操作要进行。首先要处理任何需要插入目标数据表的新行。其次是处理需要更新的已存在的行。最后要删除不再使用的旧行。这个过程中需要维护大量重复的逻辑,并可能导致微妙的错误。

Bob Beauchemin讨论了MERGE语句,这个语句将上述的多个操作步骤合并成单一语句。他给出了如下的例子:

以下是引用的片断:

 

MERGE [target] tusing [source] s on t.id = s.idwhen matched then update t.name = s.name, t.age = s.age -- use "rowset1"when not matched then insert values(id,name,age) -- use "rowset2"when source not matched then delete; -- use "rowset3"

如你所见,具体操作是根据后面的联合(join)的解析结果来确定的。在这个例子中,如果目标和源数据表有匹配的行,就实行更新操作。如果没有,就实行插入或者删除操作来使目标数据表和源数据表保持一致。

 

这个新句法的一个美妙之处是它在处理更新时的确定性。在使用标准的UPDATE句法和联合时,可能有超过一个源行跟目标行匹配。在这种情况下,无法预料更新操作会采用哪个源行的数据。

 

而当使用MERGE句法时,如果存在多处匹配,它会抛出一个错误。这就提醒了开发者,要达到预想的目标,当前的联合条件还不够明确。

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击