【问题标题】:creating variables in PL/SQL在 PL/SQL 中创建变量
【发布时间】:2012-11-02 04:48:22
【问题描述】:

来自初学者的简单 PL/SQL 问题:在现有数据集中创建新变量的正确 PL/SQL 语法是什么?

我想从保险索赔数据集 (rpt_claim) 中的日期字段 (svcdat) 中提取年份。日期字段是数字字段,格式为 YYYYMMDD,例如 20120704 表示 2012 年 7 月 4 日。

我第一次创建“年份”变量时失败了:

declare
  year number(4);
begin
  select svcdat into year 
  from rpt_claim
  where year=floor(svcdat/10000);
end;

非常感谢任何帮助!

【问题讨论】:

    标签: oracle plsql


    【解决方案1】:

    要从日期中提取年份,您可能会使用extract 函数,但在此之前,当您将日期存储为数字时,您必须使用to_date 函数将它们转换为日期数据类型。这是一个例子(使用oracle 11g):

    -- For the sake of simplicity this table contains only one column.
    SQL> create table rpt_claim(
      2    date_col number(8)
      3  )
      4  /
    
    Table created
    
    SQL> insert into rpt_claim(date_col) values(20120704);
    
    1 row inserted
    
    SQL> commit;
    
    Commit complete
    
     SQL> declare
      2    l_year number(4);
      3  begin
      4    select extract(year from to_date(date_col, 'yyyymmdd'))
      5      into l_year
      6      from rpt_claim
      7    where rownum = 1;
      8    dbms_output.put_line(to_char(l_year));
      9  exception
     10    when no_data_found
     11    then dbms_output.put_line('No data has been selected');
     12  end;
     13  /
    
    2012                  --<-- result
    
    PL/SQL procedure successfully completed
    

    注意,在上面的示例中,查询返回 1(第一个选择)行,因为它被特别要求 (where rownum = 1) 这样做。在您的情况下,查询可能会返回多个记录,并且要处理您必须使用cursorscursor FOR loop(例如)来处理返回的数据或collections

    这里是一个使用集合的例子:

    -- add more records 
    SQL> insert into rpt_claim(date_col) 
      2    select 20120704 + level 
      3      from dual 
      4    connect by level < = 5;
    
    5 rows inserted
    
    
    SQL> commit;
    
    Commit complete
    
    SQL> select * from rpt_claim;
    
     DATE_COL
    ---------
     20120704
     20120705
     20120706
     20120707
     20120708
     20120709
    
     6 rows selected
    
    SQL> declare
      2    type t_years is table of number(4);
      3    l_year t_years;
      4  begin
      5    select extract(year from to_date(date_col, 'yyyymmdd'))
      6      bulk collect into l_year
      7      from rpt_claim;
      8  
      9    if l_year is not empty
     10    then
     11      for i in l_year.first..l_year.last
     12      loop
     13        dbms_output.put_line(to_char(l_year(i)));
     14      end loop;
     15    else
     16      dbms_output.put_line('No data has been selected');
     17    end if;
     18  end;
     19  /
    
    2012
    2012
    2012          --<-- our result
    2012
    2012
    2012
    
    PL/SQL procedure successfully completed
    

    【讨论】:

    • 太棒了,非常有帮助。谢谢尼古拉斯!
    猜你喜欢
    • 1970-01-01
    • 2017-07-21
    • 2017-05-02
    • 2012-03-24
    • 1970-01-01
    • 2016-02-17
    • 2012-10-11
    • 2022-08-17
    • 2016-02-18
    相关资源
    最近更新 更多