sql批量更新简单实例(图文)

发布时间:2021-01-21编辑:脚本学堂
sql批量更新简单实例,有需要的朋友可以参考下。

sql批量更新简单实例,有需要的朋友可以参考下。

先来看一个简单点的例子:
sql批量更新

以下是更深一些的有关sql批量更新的讲解。

sql批量更新表时,特别是update一个表的列时,需要依赖另外的表,这种依赖可以是where条件子句,也可以是update的field的值依赖另外的表

一般有两种做法:
1)、使用存储过程
2)、在程序代码里逐条循环执行

本文为大家提供一种效率更高的批量更新SQL的方法,一句SQL即可替代麻烦的循环过程,分为MS SQLServer、Oracle、DB2三个库的版本。
 

复制代码 代码示例:
--关键点:t4和t1是同一个table,primary key肯定也是同一个,
--并以它进行关联,这样在 select语句里即可引用到要update的表的fields
UPDATE Table1 AS t1
SET (Field1,Field2) = (SELECT Field21, Field22
                       FROM Table2 t2
                            INNER JOIN Table3 t3
                                 ON t3.Field31 = t2.Field23
                            INNER JOIN Table4 t4
                                 ON t3.Field32 = t4.Filed41
                       WHERE t2.Field24 >= ''
                                      AND t1.fId = t4.fId);
----------------------------MS SQLServer --------------------------------------
UPDATE t1
SET Field1 = Field21, Field2 = Field22
FROM Table2 t2
         INNER JOIN Table3 t3
              ON t3.Field31 = t2.Field23
         INNER JOIN Table4 t4
              ON t3.Field32 = t4.Filed41
WHERE ((t2.Field24 >= '')
                  AND t1.fId = t4.fId);
----------------------------Oracle --------------------------------------------
UPDATE Table1 t1
SET (Field1,Field2) = (SELECT Field21, Field22
                       FROM Table2 t2
                            INNER JOIN Table3 t3
                                 ON t3.Field31 = t2.Field23
                            INNER JOIN Table4 t4
                                 ON t3.Field32 = t4.Filed41
                       WHERE ((t2.Field24 >= '')
                                 AND t1.fId = t4.fId))
WHERE EXISTS (SELECT Field21, Field22
              FROM Table2 t2
                   INNER JOIN Table3 t3
                        ON t3.Field31 = t2.Field23
                   INNER JOIN Table4 t4
                        ON t3.Field32 = t4.Filed41
              WHERE ((t2.Field24 >= '')
                               AND t1.fId = t4.fId));
---------------------------------DB2 ------------------------------------------
UPDATE Table1 AS t1
SET (Field1,Field2) = (SELECT Field21, Field22
                       FROM Table2 t2
                            INNER JOIN Table3 t3
                                 ON t3.Field31 = t2.Field23
                            INNER JOIN Table4 t4
                                 ON t3.Field32 = t4.Filed41
                       WHERE ((t2.Field24 >= '')
                                         AND t1.fId = t4.fId))
WHERE EXISTS (SELECT Field21, Field22
              FROM Table2 t2
                   INNER JOIN Table3 t3
                        ON t3.Field31 = t2.Field23
                   INNER JOIN Table4 t4
                        ON t3.Field32 = t4.Filed41
              WHERE ((t2.Field24 >= '')
                                AND t1.fId = t4.fId));