Oracle:使用动态查询

时间:2016-12-02 16:03:56

标签: database oracle oracle11g dynamicquery

我正在尝试将NVARCHAR2类型的所有列更新为数据库中的一些随机字符串。我遍历了nvarchar2类型的数据库中的所有列,并为每个列执行了更新语句。

for i in (
    select 
        table_name,
        column_name 
    from 
        user_tab_columns
    where 
        data_type = 'NVARCHAR2'
    ) loop
execute immediate 
    'update ' || i.table_name || 'set ' || i.column_name ||
    ' = DBMS_RANDOM.STRING(''X'', length('|| i.column_name ||'))
    where ' || i.column_name || ' is not null';

我没有为nvarchar2类型的每一列运行update语句,而是希望使用单个update语句更新特定表的所有nvarchar列以提高效率(即每1个表一个更新语句)。为此,我尝试将表中的所有nvarchar列批量收集到临时存储中。但是,我坚持为此编写动态更新语句。你能帮帮我吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

请试试这个:

DECLARE
    CURSOR CUR IS
        SELECT
            TABLE_NAME, 
            LISTAGG(COLUMN_NAME||' = DBMS_RANDOM.STRING(''X'', length(NVL('||
            COLUMN_NAME ||',''A''))',', ')
            WITHIN GROUP (ORDER BY COLUMN_ID) COLUMN_NAME
        FROM DBA_TAB_COLUMNS 
        WHERE DATA_TYPE = 'NVARCHAR2'
        GROUP BY TABLE_NAME;
    TYPE TAB IS TABLE OF CUR%ROWTYPE INDEX BY PLS_INTEGER;
    T TAB;
    S VARCHAR2(4000);
BEGIN
    OPEN CUR;
    LOOP
        FETCH CUR BULK COLLECT INTO T LIMIT 1000;
        EXIT WHEN T.COUNT = 0;
        FOR i IN 1..T.COUNT LOOP
            S := 'UPDATE ' || T(i).TABLE_NAME || ' SET ' || T(i).COLUMN_NAME;
            EXECUTE IMMEDIATE S;
        END LOOP;
    END LOOP;
    COMMIT;
END;
/