执行存储在过程中FOR循环中的变量中的查询时出错

时间:2017-10-30 20:30:38

标签: oracle plsql

在运行此准备好的声明时

DECLARE

BEGIN
-- Get the list of dependent tables and store it in a variable.
FOR cons IN (SELECT A.TABLE_NAME 
    FROM ALL_CONSTRAINTS A, ALL_CONSTRAINTS B
    WHERE A.CONSTRAINT_TYPE = 'xxx'
    AND A.R_CONSTRAINT_NAME = B.CONSTRAINT_NAME
    AND A.R_OWNER  = B.OWNER
    AND B.TABLE_NAME = 'MY_TABLE'
    AND B.OWNER = 'DBA')

LOOP
    SET @querytext = CONCAT('SELECT * FROM ',cons.TABLE_NAME);

        PREPARE stamquery FROM @querytext;

        EXECUTE stamquery;

        DEALLOCATE PREPARE stamquery;

END LOOP;
END;

我收到错误说明:

Encountered the symbol "STAMQUERY" when expecting one of the following:

   := . ( @ % ;

我是新手,但看起来这是根据我在互联网上的研究来做到这一点。

请让我知道我做错了什么..

1 个答案:

答案 0 :(得分:1)

您用于PL / SQL的语法不正确。它应该是这样的。

DECLARE
  querytext   VARCHAR2(1000); --declare the variable to store query.
  v_tab_count NUMBER;
BEGIN
  -- Get the list of dependent tables and store it in a variable.
  FOR cons IN
  (
    SELECT
      A.TABLE_NAME
    FROM
      ALL_CONSTRAINTS A,
      ALL_CONSTRAINTS B
    WHERE
      A.CONSTRAINT_TYPE     = 'xxx'
    AND A.R_CONSTRAINT_NAME = B.CONSTRAINT_NAME
    AND A.R_OWNER           = B.OWNER
    AND B.TABLE_NAME        = 'MY_TABLE'
    AND B.OWNER             = 'DBA'
  )
  LOOP
    querytext := CONCAT('SELECT COUNT(*) FROM ',cons.TABLE_NAME);
    EXECUTE IMMEDIATE querytext INTO v_tab_count ; --dynamicall execute the
    -- select statement.
    DBMS_OUTPUT.PUT_LINE( 'TABLE ' ||cons.TABLE_NAME||' COUNT '||v_tab_count);
    -- Display the table name and its count of rows.
  END LOOP;
END;