执行 `EXECUTE IMMEDIATE ` Oracle 语句获取错误

executing `EXECUTE IMMEDIATE ` Oracle Statement Getting Error

我是 Oracle 新手。当我执行以下语句时

BEGIN
 EXECUTE IMMEDIATE  'SELECT * FROM DUAL;';
END;
 /

我遇到错误

Error starting at line : 2 in command - BEGIN EXECUTE IMMEDIATE 'SELECT * FROM DUAL;'; END;

Error report - ORA-00911: invalid character ORA-06512: at line 2 00911. 00000 - "invalid character" *Cause: identifiers may not start with any ASCII character other than letters and numbers. $#_ are also allowed after the first character. Identifiers enclosed by doublequotes may contain any character other than a doublequote. Alternative quotes (q'#...#') cannot use spaces, tabs, or carriage returns as delimiters. For all other contexts, consult the SQL Language Reference Manual. *Action:

只需删除“;”来自动态 string.Try 这个:

BEGIN 
   EXECUTE IMMEDIATE 'SELECT * FROM DUAL'; 
END; 

问题是 'SELECT * FROM DUAL;' 中的 ; 字符。

来自documentation

execute_immediate_statement ::=
EXECUTE_IMMEDIATE dynamic_string
 { 
    INTO { define_variable [, define_variable ...] | record_name } 
  | BULK COLLECT INTO { collection_name [, collection_name ...] | :host_array_name } 
 }
   [ USING [ IN | OUT | IN OUT ] bind_argument
   [, [ IN | OUT | IN OUT ] bind_argument] ... ] [ returning_clause ] ;

... 其中 dynamic_string 是(强调我的):

A string literal, variable, or expression that represents a single SQL statement or a PL/SQL block. It must be of type CHAR or VARCHAR2, not NCHAR or NVARCHAR2.

因为它不会接受多个语句,除非您将它们包含在一个 PL/SQL 块中,因此不需要 ; 分隔符。


Using the EXECUTE IMMEDIATE Statement in PL/SQL 有更好的解释:

When constructing a single SQL statement in a dynamic string, do not include a semicolon (;) at the end inside the quotation mark. When constructing a PL/SQL anonymous block, include the semicolon at the end of each PL/SQL statement and at the end of the anonymous block; there will be a semicolon immediately before the end of the string literal, and another following the closing single quotation mark.

您可以通过从动态查询中删除 ; 来修复错误。

BEGIN
 EXECUTE IMMEDIATE  'SELECT * FROM DUAL';
END;
 /

此查询不会 return 任何结果;

select EXECUTE IMMEDIATE 中没有 into 子句的语句将被忽略。

Declare
    v_variable number;--some variable
BEGIN
     EXECUTE IMMEDIATE  'SELECT clmn FROM tbl' into v_variable;
END;
/