我的程序没有返回预期的结果

时间:2010-09-16 07:11:08

标签: oracle plsql

这是我的代码:

create or replace    
procedure date_report (start_date  timestamp , end_date  timestamp  )
is
  cursor cursor_audit is
    select audit_id, audit_action, audit_user, audit_date
    from customer_audit
    where audit_date between start_date and end_date
    ;
  rec cursor_audit%rowtype;
begin
  open cursor_audit;
  fetch cursor_audit into rec;
  while cursor_audit%found
  loop
    dbms_output.put_line('User : '  || rec.audit_user
                    || ', ID :'     || rec.audit_id
                    || ', Action: ' || rec.audit_action
                    || ', Date : '  || rec.audit_date );
    fetch cursor_audit into rec;
  end loop;
  close cursor_audit;
end;

我想查询特定日期之间的所有行,但似乎没有报告任何内容。

3 个答案:

答案 0 :(得分:4)

不完全是你要求的,但值得一提的是:你可以写得更好,即更像惯用的PL / SQL:

创建或替换

procedure date_report (start_date  timestamp , end_date  timestamp  )
is
  cursor cursor_audit is select audit_id, audit_action, audit_user, audit_date
                         from customer_audit
                         where audit_date between start_date and end_date
                     ;
begin
  for rec in cursor_audit
  loop
    dbms_output.put_line('User : '||rec.audit_user ||', ID :' ||rec.audit_id||', Action: ' 
                         || rec.audit_action||', Date : ' ||rec.audit_date );
  end loop;
end;

甚至

procedure date_report (start_date  timestamp , end_date  timestamp  )
is
begin
  for rec in (select audit_id, audit_action, audit_user, audit_date
                from customer_audit
                where audit_date between start_date and end_date)
  loop
    dbms_output.put_line('User : '||rec.audit_user ||', ID :' ||rec.audit_id||', Action: ' 
                         || rec.audit_action||', Date : ' ||rec.audit_date );
  end loop;
end;

问题的一个可能原因是您选择了例如: 09-16-2010至09-16-2010,即09-16-2010 00:00:00至09-16-2010 00:00:00。要查找09-16-2010中的所有行,您必须明确地传递一个时间(或者只是在end_date中添加1,这在大多数情况下就足够了)

答案 1 :(得分:2)

查看是否已选中。

alt text

答案 2 :(得分:0)

首先,建议为变量和参数添加前缀,使它们不与列名冲突。

在您的示例中,如果“customer_audit”包含start_date和end_date列,则这些列将优先于PL / SQL变量或同名参数使用。

其次,原始标题包括“-parameter-always-null”。如果参数为null,则条件不为true,并且不返回任何行。

如果你想要满足这个要求,你需要编写一些逻辑代码:

> select audit_id, audit_action, audit_user, audit_date
> from customer_audit
> where (audit_date >= i_start_date or i_start_date is null)
> and   (audit_date <= i_end_date or i_end_date is null)