0

我想声明两个变量并在 teradata 中的 select 语句的 where 条件中使用 thoes 变量,但我得到了一个错误。

Create Procedure Demo()

Begin
Declare REnd Date;
Declare RStart Date;

Set REnd = (select max(CalendarDate) as REnd 
            from Table1 
            where CalendarDate = MonthEndDate
            and  Monthofyear in ('June', 'December')
            and CalendarDate < Current_date()
           );

Set RStart = (select max(CalendarDate) as RStart
            from Table1 
            where CalendarDate = (CalendarDate - Extract(Day From CalendarDate)+1)
            and  Monthofyear in ('January', 'July')
            and CalendarDate < REnd
           );

Call dbc.sysexecsql(('select * from table 2 where reviewdate between' ||REnd|| 'and' ||RStart|| ');');
End;
4

1 回答 1

0

不需要动态 SQL。

REPLACE PROCEDURE Demo()
DYNAMIC RESULT SETS 1 -- SP will return a result set
BEGIN 
   Declare REnd Date;
   Declare RStart Date;

   Set REnd = (select max(CalendarDate) as REnd 
               from Table1 
               where CalendarDate = MonthEndDate
               and  Monthofyear in ('June', 'December')
               and CalendarDate < Current_date()
              );

   Set RStart = (select max(CalendarDate) as RStart
               from Table1 
               where CalendarDate = (CalendarDate - Extract(Day From CalendarDate)+1)
               and  Monthofyear in ('January', 'July')
               and CalendarDate < REnd
              );

   -- Return result set
   BEGIN
      DECLARE cur2 CURSOR WITH RETURN ONLY FOR
       -- this is your query using parameters
         select * from table2 
         where reviewdate between :RStart and :REnd;

      OPEN cur2; -- don't close, otherwise no result set
   END;
END;

游标对于处理数据是邪恶的,但这不是真正的游标,它只是用于返回结果集的冗长的标准 SQL 语法:-)

于 2022-02-16T15:57:36.320 回答