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!
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):
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: