PL / SQL DDL立即执行

时间:2012-02-18 02:13:14

标签: plsql

ACCEPT p_username PROMPT 'Enter Username : '
ACCEPT p_password PROMPT 'Enter New Password for Username : '
VARIABLE g_output VARCHAR2(4000)
DECLARE
   CURSOR NAME IS SELECT TABLE_NAME FROM DBA_TABLES 
      WHERE OWNER LIKE '%&p_username%';
   DDL_DROP VARCHAR2(200);
BEGIN
   FOR TNAME IN NAME
   LOOP
       BEGIN
          EXECUTE IMMEDIATE 'DROP TABLE' || ' ' || TNAME.TABLE_NAME;
         :g_output := :g_output || ' ' || TNAME.TABLE_NAME;
       END;
   END LOOP;
END;
/
PRINT g_output

您好,我是PL / SQL的新手,并尝试制作一个脚本来删除用户的表,并在删除表后最终更改密码。我在执行EXECUTE IMMEDIATE命令时遇到困难。如果我删除EXECUTE IMMEDIATE行,该脚本将起作用。我通过在循环中打印表名来测试它,我得到了正确的表#及其相应的名称。

感谢任何帮助,谢谢。

编辑代码以反映该建议但仍然无效。得到同样的错误。

ACCEPT p_username PROMPT 'Enter Username : '
ACCEPT p_password PROMPT 'Enter New Password for Username : '
VARIABLE g_output VARCHAR2(4000)
DECLARE
   NAME SYS_REFCURSOR;
   DDL_WORD VARCHAR2(200);
BEGIN
   OPEN NAME FOR SELECT TABLE_NAME FROM DBA_TABLES 
      WHERE OWNER LIKE '%&p_username%';
   LOOP
         FETCH NAME INTO DDL_WORD;
         EXIT WHEN NAME%NOTFOUND;
         EXECUTE IMMEDIATE 'DROP TABLE "' || DDL_WORD || '" CASCADE CONSTRAINTS';
         :g_output := :g_output || ' ' || DDL_WORD;
   END LOOP;
   CLOSE NAME;
END;
/
PRINT g_output

2 个答案:

答案 0 :(得分:1)

您可能需要在DROP语句中指定表的所有者:

ACCEPT p_username PROMPT 'Enter Username : '
ACCEPT p_password PROMPT 'Enter New Password for Username : '
VARIABLE g_output VARCHAR2(4000)
DECLARE
   CURSOR NAME IS SELECT OWNER, TABLE_NAME FROM DBA_TABLES 
      WHERE OWNER LIKE '%&p_username%';
   DDL_DROP VARCHAR2(200);
BEGIN
   FOR TNAME IN NAME
   LOOP
       BEGIN
          EXECUTE IMMEDIATE 'DROP TABLE' || ' ' || TNAME.OWNER || '.' || TNAME.TABLE_NAME;
         :g_output := :g_output || ' ' || TNAME.OWNER || '.' || TNAME.TABLE_NAME;
       END;
   END LOOP;
END;
/
PRINT g_output

答案 1 :(得分:0)

代码看起来很好。

您可以尝试使用()这样的

BEGIN

 EXECUTE IMMEDIATE (code_text);

END;

你可以尝试

 c SYS_REFCURSOR;
BEGIN
  OPEN c FOR 'SELECT * FROM table';
  CLOSE c;
END;