我有下面的SQL过程,它从SQL DEveloper
运行时显示以下错误ERROR Message:
ORA-01422: exact fetch returns more than requested number of rows
PROCEDURE SP_ENABLE_CONST(P_ARCH_BATCH_ID VARCHAR) IS
TABLELIST VARCHAR2(100);
SQL_QUERY VARCHAR2(4000);
RESULT_COL INT;
RESULT_CONST_COL VARCHAR2(1000);
BEGIN
/*LOOP will return three tables designated in table_name */
FOR TEMP2_VAR_TEST IN (SELECT TABLE_NAME FROM SYS.ALL_TABLES WHERE TABLE_NAME LIKE 'TEST%')
/*each loop the table_name returned will be used in SQL_QUERY */
LOOP
SQL_QUERY := 'SELECT CONSTRAINT_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME = :1';
DBMS_OUTPUT.PUT_LINE(SQL_QUERY);
/*select statement will return more than one row containing table constraints*/
**ERROR on this part since RESULT_CONST_COL cannot contain more than one row
EXECUTE IMMEDIATE SQL_QUERY INTO RESULT_CONST_COL USING TEMP2_VAR_TEST.TABLE_NAME;
DBMS_OUTPUT.PUT_LINE('CONSTRAINT_NAME' || RESULT_CONST_COL);
END LOOP;
END SP_ENABLE_CONST;
END PK_ARCHIVE_PROCESS_TEST;
我知道错误是由result_const_col引起的,它是VARCHAR2类型但不知道用什么来存储execute immediate命令返回的多行。我已阅读有关游标并试图使用它但仍然出错。提前谢谢。
按照您的建议修改了我的代码,但仍然遇到错误。
TYPE RESULT_CONST_COL IS TABLE OF VARCHAR2(1000);
VAR_OF_RESULT_CONST RESULT_CONST_COL;
TBL_CONSTRAINTS VARCHAR2(100);
TABLELIST VARCHAR2(100);
SQL_QUERY VARCHAR2(4000);
RESULT_COL INT;
BEGIN
FOR TEMP2_VAR_TEST IN (SELECT TABLE_NAME FROM SYS.ALL_TABLES WHERE TABLE_NAME LIKE 'TEST%')
LOOP
SQL_QUERY := 'SELECT CONSTRAINT_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME = :1';
DBMS_OUTPUT.PUT_LINE(SQL_QUERY);
/*ERROR line 92*/
EXECUTE IMMEDIATE SQL_QUERY USING TEMP2_VAR_TEST.TABLE_NAME
RETURNING BULK COLLECT INTO VAR_OF_RESULT_CONST;
FOR I IN 1 .. VAR_OF_RESULT_CONST.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(VAR_OF_RESULT_CONST(i));
END LOOP;
END LOOP;
当我尝试运行上面的代码时遇到此错误
ORA-06547: RETURNING clause must be used with INSERT, UPDATE, or DELETE statements
**ORA-06512: at "HSNIAPP.PK_ARCHIVE_PROCESS_TEST", line 92**
ORA-06512: at line 6
SELECT CONSTRAINT_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME = :1
答案 0 :(得分:2)
您必须将RESULT_CONST_COL
声明为集合:
RESULT_CONST_COL IS TABLE OF VARCHAR2(1000);
然后使用BULK COLLECT INTO
返回多行:
EXECUTE IMMEDIATE SQL_QUERY BULK COLLECT INTO RESULT_CONST_COL
USING TEMP2_VAR_TEST.TABLE_NAME;
然后遍历集合中的返回结果以处理所有值:
FOR i IN 1 .. RESULT_CONST_COL.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(RESULT_CONST_COL(i));
EXECUTE IMMEDIATE 'ALTER TABLE '|| TEMP2_VAR_TEST ||
' DISABLE CONSTRAINT ' || RESULT_CONST_COL(i);
END LOOP;