将 table 中的单个值分配给 ORACLE PL/SQL 中声明的变量时出错

Getting an error when assigning single value from table to declared variable in ORACLE PL/SQL

我正在为 Oracle DB 10g/11g 编写过程,我需要为变量分配特定的日期值。代码如下。

DECLARE 
    date_from DATE := NULL;
DECLARE 
    d_count NUMBER := 0;
BEGIN
    SELECT COUNT(*) INTO d_count FROM TABLE_X;

    IF d_count = 0 THEN
        SELECT MIN(TRX_DATE) INTO date_from FROM TABLE_Y;
    ELSE
        SELECT MAX(TRX_DATE) INTO date_from FROM TABLE_X;
    END IF;
END;

当我 运行 这个时,我收到这个错误。

Error starting at line : 1 in command -
DECLARE 
    date_from DATE := NULL;
DECLARE 
    d_count NUMBER := 0;
BEGIN
    SELECT COUNT(*) INTO d_count FROM TABLE_X;

    IF d_count = 0 THEN
        SELECT MIN(TRX_DATE) INTO date_from FROM TABLE_Y;
    ELSE
        SELECT MAX(TRX_DATE) INTO date_from FROM TABLE_X;
    END IF;
END;
Error report -
ORA-06550: line 3, column 1:
PLS-00103: Encountered the symbol "DECLARE" when expecting one of the following:

    begin function pragma procedure subtype type <and identifier>
    <a double-quoted delimited-identifier> current cursor delete
    exist prior
The symbol "begin" was substituted for "DECLARE" to continue.
ORA-06550: line 13, column 4:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
    
    ( begin case declare and exception exit for goto if loop mod
    null pragma raise return select update while with
    <an identifier><a double-quoted
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usuallz a PL/SQL compilation error.
*Action:

我有 T-SQL 经验,但是对 OracleDB 中的 PL/SQL 非常陌生。 提前致谢。

您使用了extra declare。这应该没问题:

DECLARE 
    date_from DATE := NULL; 
    d_count NUMBER := 0;
BEGIN
    SELECT COUNT(*) INTO d_count FROM TABLE_X;

    IF d_count = 0 THEN
        SELECT MIN(TRX_DATE) INTO date_from FROM TABLE_Y;
    ELSE
        SELECT MAX(TRX_DATE) INTO date_from FROM TABLE_X;
    END IF;
END;

脚本的基本模板:

declare 
  -- Local variables here
  i integer;
begin
  --  statements here
end;

程序的基本模板:

procedure TEST(Name in out type, Name in out type, ...) is
begin
  
end TEST;

在你的情况下,只有一个 DECLARE 就足够了。

此外(虽然不是错误),

  • 声明的变量默认为NULL;您不必指定它(即 DATE_FROM
  • d_count用于接受count函数的结果;如果在 table_x 中没有找到任何内容,那么无论如何计数都将是 0,因此您也不必指定 d_count 的初始值

所以:

DECLARE
   date_from  DATE;
   d_count    NUMBER;
BEGIN
   SELECT COUNT (*) INTO d_count FROM TABLE_X;

   IF d_count = 0 THEN
      SELECT MIN(TRX_DATE) INTO date_from FROM TABLE_Y;
   ELSE
      SELECT MAX(TRX_DATE) INTO date_from FROM TABLE_X;
   END IF;
END;