要从日期中提取年份,您可能会使用提取函数,但在此之前,当您将日期存储为数字时,您必须使用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
) 这样做。在您的情况下,查询可能会返回一条以上的记录,并且要处理您必须使用游标和游标 FOR 循环(例如)来处理返回的数据或集合。
下面是一个使用集合的例子:
-- 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