RobertF
RobertF

Reputation: 904

creating variables in PL/SQL

Simple PL/SQL question from a beginner: What is the proper PL/SQL syntax for creating a new variable in an existing dataset?

I'd like to extract the year from a date field (svcdat) in an insurance claims dataset (rpt_claim). The date field is numerical and follows the format YYYYMMDD, for example 20120704 for July 4, 2012.

My first pass at creating a "year" variable was unsuccessful:

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

Any help is much appreciated!

Upvotes: 2

Views: 1069

Answers (1)

Nick Krasnov
Nick Krasnov

Reputation: 27251

To extract year from a date you probably will use extract function, but before that, as you store your dates as numbers, you have to convert them to date datatype using to_date function. Here is an example(oracle 11g is used):

-- 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

Note, in the example above the query returns 1 (first selected) row, because it was specifically asked (where rownum = 1) to do that. In your case will probably more than one record be returned by the query and to handle that you have to use cursors and cursor FOR loop(for example) to process returned data or collections.

Here is an example of using 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

Upvotes: 1

Related Questions