如何在表之间翻转Oracle同义词

时间:2018-12-31 22:11:49

标签: sql oracle stored-procedures synonym

我有下面两个表。

A_DETAILS

B_DETAILS

我在上面的表格中创建了以下两个SYNONYM

A_DETAILS指向-> L_DETAILS

B_DETAILS指向-> R_DETAILS

我想在某个时间点翻转同义词

A_DETAILS指向-> R_DETAILS

B_DETAILS指向-> L_DETAILS

我尝试了下面的代码,但它同时创建了一个表的同义词并从另一个表中删除。

BEGIN

   FOR reg IN 
(SELECT SYNONYM_NAME, TABLE_NAME, OWNER
            FROM ALL_SYNONYMS
           WHERE OWNER IN ('MY_SCHEMA') AND SUBSTR (TABLE_NAME, 1, 2) = 'A_')
   LOOP
      v_Statement := 'CREATE OR REPLACE SYNONYM '|| reg.owner|| '.'|| reg.SYNONYM_NAME|| ' FOR '|| reg.owner|| '.'|| 'B_'|| SUBSTR (reg.TABLE_NAME, 3);

      EXECUTE IMMEDIATE v_Statement;
   END LOOP;
      FOR reg
      IN (SELECT SYNONYM_NAME, TABLE_NAME, OWNER
            FROM ALL_SYNONYMS
           WHERE OWNER IN ('MY_SCHEMA') AND SUBSTR (TABLE_NAME, 1, 2) = 'B_')
   LOOP
      v_Statement :='CREATE OR REPLACE SYNONYM '|| reg.owner|| '.'|| reg.SYNONYM_NAME|| ' FOR '|| reg.owner|| '.'|| 'A_'|| SUBSTR (reg.TABLE_NAME, 3);

      EXECUTE IMMEDIATE v_Statement;
   END LOOP;
   END;

1 个答案:

答案 0 :(得分:3)

以一个循环而不是两个循环进行。到第二个循环时,第一个同义词已更新为指向B_,因此第二个循环将两个同义词更新为指向A _。

BEGIN
  FOR reg IN (
    SELECT SYNONYM_NAME, TABLE_NAME, OWNER
         , case SUBSTR (TABLE_NAME, 1, 2)
             when 'A_' then 'B_'
             when 'B_' then 'A_'
           end || SUBSTR (TABLE_NAME, 3) NEW_TABLE
      FROM ALL_SYNONYMS
     WHERE OWNER IN ('MY_SCHEMA') AND SUBSTR (TABLE_NAME, 1, 2) in ('A_','B_'))
  LOOP
    v_Statement := 'CREATE OR REPLACE SYNONYM '|| reg.owner|| '.'|| reg.SYNONYM_NAME
                || ' FOR '|| reg.owner|| '.'|| reg.NEW_TABLE;

    EXECUTE IMMEDIATE v_Statement;
  END LOOP;
END;