替换Oracle表中的NULL值

brtdzjyr  于 2023-04-20  发布在  Oracle
关注(0)|答案(1)|浏览(196)

我有这张table

COL 1   | COL 2   | COL 3   | COL 4
entry1  | NULL    | NULL    | NULL
NULL    | NULL    | entry1  | entry1  
entry2  | entry1  | entry1  | NULL

输出应为

COL_1   | COL_2   | COL_3   | COL_4
entry1  | EMPTY   | EMPTY   | EMPTY
EMPTY   | EMPTY   | entry1  | entry1  
entry2  | entry1  | entry1  | EMPTY

我想用一个给定的字符串替换所有的列。在这个例子中,字符串是'EMPTY'。
我知道有像'COALESCE(COL_1,'EMPTY_STRING)AS COL_1 '这样的函数...但我不想对每一列都做COALESCE。有没有一种方法可以替换整个表中的每个NULL值?
谢谢。

piah890a

piah890a1#

一个简单的PL/SQL代码的例子,它做了你解释的事情。它假设表中的所有列都是VARCHAR2,因为你不能把'EMPTY'放入NUMBERDATE数据类型的列中。如果你在那个表中有不同数据类型的列,在游标的WHERE子句中过滤它们。
样品表:

SQL> CREATE TABLE test
  2  (
  3     col1   VARCHAR2 (10),
  4     col2   VARCHAR2 (10)
  5  );

Table created.

SQL> INSERT INTO test
  2     SELECT 'entry1', NULL FROM DUAL
  3     UNION ALL
  4     SELECT NULL, NULL FROM DUAL
  5     UNION ALL
  6     SELECT 'entry2', 'entry1' FROM DUAL;

3 rows created.

SQL> SELECT * FROM test;

COL1       COL2
---------- ----------
entry1

entry2     entry1

过程使用动态SQL更新NULL值,并使用字符串'EMPTY':

SQL> DECLARE
  2     l_str  VARCHAR2 (200);
  3  BEGIN
  4     FOR cur_r IN (SELECT column_name
  5                     FROM user_tab_columns
  6                    WHERE table_name = 'TEST')
  7     LOOP
  8        l_str :=
  9              'update test set '
 10           || cur_r.column_name
 11           || q'[ = 'EMPTY' where ]'
 12           || cur_r.column_name
 13           || ' is null';
 14
 15        EXECUTE IMMEDIATE l_str;
 16     END LOOP;
 17  END;
 18  /

PL/SQL procedure successfully completed.

结果:

SQL> SELECT * FROM test;

COL1       COL2
---------- ----------
entry1     EMPTY
EMPTY      EMPTY
entry2     entry1

SQL>

如果要将匿名代码移动到过程中,则:

SQL> rollback;

Rollback complete.

SQL> SELECT * FROM test;

COL1       COL2
---------- ----------
entry1

entry2     entry1

程序:

SQL> CREATE OR REPLACE PROCEDURE p_empty (par_table_name IN VARCHAR2)
  2  IS
  3     l_str  VARCHAR2 (200);
  4  BEGIN
  5     FOR cur_r IN (SELECT column_name
  6                     FROM user_tab_columns
  7                    WHERE table_name = DBMS_ASSERT.sql_object_name (par_table_name))
  8     LOOP
  9        l_str :=
 10              'update '
 11           || par_table_name
 12           || ' set '
 13           || cur_r.column_name
 14           || q'[ = 'EMPTY' where ]'
 15           || cur_r.column_name
 16           || ' is null';
 17
 18  dbms_output.put_line(l_str);
 19        EXECUTE IMMEDIATE l_str;
 20     END LOOP;
 21  END;
 22  /

Procedure created.

测试:

SQL> BEGIN
  2     p_empty ('TEST');
  3  END;
  4  /

PL/SQL procedure successfully completed.

SQL>
SQL> SELECT * FROM test;

COL1       COL2
---------- ----------
entry1     EMPTY
EMPTY      EMPTY
entry2     entry1

SQL>

相关问题