当前位置: 代码网 > it编程>数据库>MsSqlserver > SQL中merge into用法详解

SQL中merge into用法详解

2025年04月12日 MsSqlserver 我要评论
从备份表中更新字段到正式表中,使用 update 批量更新大量的数据,会出现效率低下,有时候甚至卡死的情况,后面通过使用 merge into 代替 update 执行批量更新,会提升执行效率。mer

从备份表中更新字段到正式表中,使用 update 批量更新大量的数据,会出现效率低下,有时候甚至卡死的情况,后面通过使用 merge into 代替 update 执行批量更新,会提升执行效率。

merge into语法如下:

merge into table_name alias1 
using (table|view|sub_query) alias2
on (join condition) 
when matched then 
    update  
    set col1 = col1_val1, 
        col2 = col2_val2 
when not matched then 
    insert (column_list) values (column_values); 

其中,table_name 指的是更新的表,using()里边的指的是数据来源表/视图/子查询结果集,condition指的是连接条件,如果满足连接条件,set 字段1=值1,字段2=值2...

如果连接条件不满足,则停止更新进行插入。
下面我们来举例说明:

先创建被更新表merge_target,并往其中插入一条数据用来更新;

再创建更新表merge_source,用来向被更新表插入数据;

下面准备merge into脚本:

merge into merge_target target 
using (select b.name,b.age,b.target_id from merge_source b) source
on (target.id=source.target_id) 
when matched then 
    update 
    set target.name = source.name, 
        target.age = source.age 
when not matched then 
    insert(target.name,target.age) values (source.name,source.age); 

结果如下:

另:mysql不支持merge into 语法。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com