Wednesday, August 26, 2009

Reverse function in Oracle

The following shows how to use the reverse function to reverse a string or number in Oracle.
SQL> select reverse('string') from dual;
REVERS
------
gnirts

However you may not have the function installed and can use the following procedure:
SQL>
SQL> create or replace procedure reverse(x in varchar2) as
2 a char(1);
3 i number;
4 begin
5 for i in 1..length(x) loop
6 select substr(x,length(x)-i+1,1) into c from dual;
7 dbms_output.put(a);
8 end loop;
9 dbms_output.put_line(' ');
10 end;
11 /


Procedure created.

SQL> set serverout on
SQL> exec reverse('Oracle')
elcarO

SQL> exec reverse('string')
gnirts
PL/SQL procedure successfully completed.

Thursday, August 6, 2009

Get last 2 financial years quarters

The 'solution' below is to retrieve the start and end dates of annual quarters of the last 2 years, using the @end_date as your input parameter.

You can replace the '--- YOUR QUERY USING the @qtr_start and @qtr_end parameters' with your query, with the @qtr_start and @qtr_end as your search criteria.


DECLARE
@qtr_start DATETIME,
@qtr_end DATETIME,
@end_date DATETIME

-- your date parameter
SET @end_date = '2009-06-30'

-- initialise dates
SET @qtr_start = DATEADD(YYYY, -2, DATEADD(D,1, @end_date))
SET @qtr_end = DATEADD(DD, -1,DATEADD(M,3,@qtr_start))


WHILE @qtr_end <= @end_date
BEGIN
SELECT 'Quarter: '+convert(VARCHAR, @qtr_start, 3)+'-'+convert(VARCHAR, @qtr_end, 3),
@qtr_start,
@qtr_end

--- YOUR QUERY USING the @qtr_start and @qtr_end parameters

-- get rest of the quarters until end date
SET @qtr_start = DATEADD(DD, 1,@qtr_end)
SET @qtr_end = DATEADD(DD, -1,DATEADD(M,3,@qtr_start))
END