Oracle替换变量不适用于varchar2

时间:2017-05-01 13:37:52

标签: oracle plsql oracle11g

我只想使用替换变量来获取customer_name(varchar2),但是当我执行下面的子程序时,它会引发异常。

DECLARE
    v_cid     dummytest.customer_id%type := &customer_id;
    v_cname   dummytest.customer_name%type := &customer_name;
BEGIN
    INSERT INTO dummytest ( customer_id,customer_name ) VALUES ( v_cid,v_cname );

    COMMIT;
END;

错误

Error report -
ORA-06550: line 3, column 47:
PLS-00201: identifier 'HUHU' must be declared
ORA-06550: line 3, column 15:
PL/SQL: Item ignored
ORA-06550: line 5, column 72:
PLS-00320: the declaration of the type of this expression is incomplete or malformed
ORA-06550: line 5, column 72:
PL/SQL: ORA-00904: "V_CNAME": invalid identifier
ORA-06550: line 5, column 5:
PL/SQL: SQL Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

但是当我给出数字值并成功插入时。

2 个答案:

答案 0 :(得分:5)

首先发生替换,所以接下来......

v_cname   dummytest.customer_name%type := &customer_name;

... ...变为

v_cname   dummytest.customer_name%type := HUHU;

...由于缺少单引号而不是字符串,而是编译器无法确定源的标识符。

所以,如果你包括字符串(VARCHAR2)替换的引号,则以下......

v_cname   dummytest.customer_name%type := '&customer_name';

... ...变为

v_cname   dummytest.customer_name%type := 'HUHU';

...这是你要找的字符串。

它适用于数字,因为数字类型不需要引号。

答案 1 :(得分:1)

在解析和执行脚本之前,在您的SQL脚本中使用给定的输入替换替换变量;因此,你必须在字符串替换变量周围放置单引号,这样它们最终会成为字符串文字。

 v_cname   dummytest.customer_name%type := '&customer_name';