PL-SQL将查询结果存储到变量中

时间:2012-10-09 18:45:33

标签: plsql

美好的一天,

我有一个PL-SQL查询如下。我正在尝试执行查询并将结果存储到变量中。到目前为止,我有这个查询有效:

    SELECT DECODE(COUNT(*), 0, 'N', 'Y') REC_EXISTS
    FROM
         (SELECT 
                COUNT(*) AS TOTAL_COUNT
           FROM DEV.BASEOBJECT INNER JOIN
                DEV.ANIMAL ON DEV.BASEOBJECT.ID = DEV.ANIMAL.BASEOBJECT_ID
       GROUP BY DEV.BASEOBJECT.ID, 
                DEV.BASEOBJECT.FIRST_NAME, 
                DEV.BASEOBJECT.LAST_NAME, 
                DEV.BASEOBJECT.CITY,
                DEV.BASEOBJECT.STATE,
                DEV.BASEOBJECT.ZIP,
                DEV.ANIMAL.ID,
                DEV.ANIMAL.NAME,
                DEV.ANIMAL.BREED, 
                DEV.ANIMAL.DATE_OF_BIRTH, 
                DEV.ANIMAL.GENDER,
                DEV.ANIMAL.SPECIES
         HAVING (COUNT(*) > 1));

但是当我尝试使用此查询将结果保存到变量中时:

DECLARE
    v_name  VARCHAR2(2);
BEGIN
    SELECT DECODE(COUNT(*), 0, 'N', 'Y') REC_EXISTS
        INTO v_name
    FROM
         (SELECT 
                COUNT(*) AS TOTAL_COUNT
           FROM DEV.BASEOBJECT INNER JOIN
                DEV.ANIMAL ON DEV.BASEOBJECT.ID = DEV.ANIMAL.BASEOBJECT_ID
       GROUP BY DEV.BASEOBJECT.ID, 
                DEV.BASEOBJECT.FIRST_NAME, 
                DEV.BASEOBJECT.LAST_NAME, 
                DEV.BASEOBJECT.CITY,
                DEV.BASEOBJECT.STATE,
                DEV.BASEOBJECT.ZIP,
                DEV.ANIMAL.ID,
                DEV.ANIMAL.NAME,
                DEV.ANIMAL.BREED, 
                DEV.ANIMAL.DATE_OF_BIRTH, 
                DEV.ANIMAL.GENDER,
                DEV.ANIMAL.SPECIES
         HAVING (COUNT(*) > 1));
END

我收到错误:

ERROR
ORA-06550: line 1, column 8:
PLS-00103: Encountered the symbol "" when expecting one of the following:

   begin function package pragma procedure subtype type use
   <an identifier> <a double-quoted delimited-identifier> form
   current cursor
The symbol "" was ignored.    

最终,这将是一个存储过程,但我还没准备好那部分,因为我想验证我到目前为止所做的工作。

TIA,

COSON

1 个答案:

答案 0 :(得分:0)

你是怎么运行的?你用的是什么工具?我认为问题是您的工具/ IDE正在尝试将其编译为函数/过程。此代码看起来正常,如果您将其作为SQL * Plus中的脚本运行,则可能会毫无问题地运行。如果您将其作为脚本运行,则应在查询后添加dbmbs_output.put_line(v_name)以查看结果。