要從日期提取年份,您可能會使用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
)做到這一點。在您的情況下,查詢可能會返回多條記錄,並處理您必須使用cursors和cursor 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
好極了,非常有幫助。謝謝尼古拉斯! – RobertF