使用循环更新多个表中的列

时间:2016-04-13 14:33:41

标签: sql oracle loops plsql auto-update

我的Oracle数据库的每个表中都有几个QA列,我希望每天使用插入/更新对象的用户名更新。我能够在表格中手动更新列,如下所示:

UPDATE TEST.TABLE1 TB
SET TB.ADDED_BY2 = 
(
select IA.FULL_NAME
from ISM.APP_USER IA
where IA.NAME = UPPER(TB.ADDED_BY)
),
TB.CHANGED_BY2 = 
(
select IA.FULL_NAME
from ISM.APP_USER IA
where IA.NAME = UPPER(TB.CHANGED_BY)
)
where TO_CHAR(CREATION_DATUM, 'YYYY-MM-DD') = TO_CHAR(SYSDATE) AND ADDED_BY2 IS NULL;

但要更新25个表中的同一列是一项繁琐(无聊)的工作。问题是:无论如何使用LOOP(或任何其他方法)更新25个表中的列?

我的最终目标是做以下事情:

FOR I IN SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME IN ('TEST.TABLE1', 'TEST.TABLE2')

LOOP

UPDATE I.TABLE_NAME TB
SET TB.ADDED_BY2 = 
(
select IA.FULL_NAME
from ISM.APP_USER IA
where IA.NAME = UPPER(TB.ADDED_BY)
),
TB.CHANGED_BY2 = 
(
select IA.FULL_NAME
from ISM.APP_USER IA
where IA.NAME = UPPER(TB.CHANGED_BY)
)
where TO_CHAR(CREATION_DATUM, 'YYYY-MM-DD') = TO_CHAR(SYSDATE) AND ADDED_BY2 IS NULL;

END LOOP;

1 个答案:

答案 0 :(得分:0)

您需要使用动态SQL:

FOR I IN SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME IN ('TEST.TABLE1', 'TEST.TABLE2')

LOOP
 execute immediate
  'UPDATE ' || I.TABLE_NAME || ' TB
   SET TB.ADDED_BY2 = 
   (
     select IA.FULL_NAME
     from ISM.APP_USER IA
     where IA.NAME = UPPER(TB.ADDED_BY)
   ),
   TB.CHANGED_BY2 = 
   (
     select IA.FULL_NAME
     from ISM.APP_USER IA
     where IA.NAME = UPPER(TB.CHANGED_BY)
   )
   where TO_CHAR(CREATION_DATUM, ''YYYY-MM-DD'') = TO_CHAR(SYSDATE)
     AND ADDED_BY2 IS NULL';

END LOOP;

这样,您可以根据不同的表名动态构建SQL语句并执行它;