EXECUTE IMMEDIATE语句几乎可以用在任何由 BEGIN 和 END 包围的 SQL 块中,例如存储过程或匿名复合语句。
CREATE PROCEDURE create_table_from_file( IN fileDir VARCHAR( 1024 ),
IN fileName VARCHAR( 128 ),
IN tabSchema VARCHAR( 128 ),
IN tabName VARCHAR( 128 )
)
BEGIN
DECLARE fh UTL_FILE.FILE_TYPE;
DECLARE sqlStmt VARCHAR( 32672 );
DECLARE currentLine VARCHAR( 32672 );
DECLARE SQLCODE INTEGER DEFAULT 0;
DECLARE SQLSTATE CHAR(5) DEFAULT '00000';
DECLARE SQLSTATE1 CHAR(5) DEFAULT '00000';
DECLARE CONTINUE HANDLER FOR SQLSTATE 'ORANF' SET SQLSTATE1 = SQLSTATE;
SET sqlStmt = 'CREATE TABLE '
|| CASE WHEN ( NULLIF( tabSchema, '' ) IS NOT NULL )
THEN RTRIM( tabSchema ) || '.'
ELSE '' END || tabName;
CALL UTL_DIR.CREATE_OR_REPLACE_DIRECTORY( 'createTablePath', fileDir );
SET fh = UTL_FILE.FOPEN( 'createTablePath', fileName, 'r' );
loop1: LOOP
CALL UTL_FILE.GET_LINE( fh, currentLine );
IF SQLSTATE1 = 'ORANF' THEN -- NO DATA FOUND
LEAVE loop1;
END IF;
SET sqlStmt = sqlStmt || ' ' || currentLine ;
END LOOP;
EXECUTE IMMEDIATE sqlStmt;
END
@