Thursday, March 27, 2008

Select between dates in Oracle SQL

SQL> with t as (select to_date('01/01/2007','dd/mm/yyyy') as update_date from dual union all
2 select to_date('01/01/2007','dd/mm/yyyy') from dual union all
3 select to_date('03/01/2007','dd/mm/yyyy') from dual union all
4 select to_date('03/01/2007','dd/mm/yyyy') from dual union all
5 select to_date('03/01/2007','dd/mm/yyyy') from dual union all
6 select to_date('04/01/2007','dd/mm/yyyy') from dual union all
7 select to_date('05/01/2007','dd/mm/yyyy') from dual union all
8 select to_date('07/01/2007','dd/mm/yyyy') from dual union all
9 select to_date('07/01/2007','dd/mm/yyyy') from dual)
10 -- end of test data
11 select to_char(x.UPDATE_DATE, 'YYYY-MM-DD') as update_date, DECODE(t.update_date, NULL, 0, count (*)) as count
12 from (select to_date('2007-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')+(rownum-1) as update_date
13 from dual
14 connect by rownum <= (to_date('2007-02-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS') -
15 to_date('2007-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS'))) x
16 LEFT OUTER JOIN t ON (x.update_date = t.update_date)
17 where x.UPDATE_DATE >= to_date('2007-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')
18 and x.UPDATE_DATE < color="navy">'2007-02-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')
19 group by to_char(x.UPDATE_DATE, 'YYYY-MM-DD'), t.update_date
20 order by 1
21 /

UPDATE_DAT COUNT
---------- ----------
2007-01-01 2
2007-01-02 0
2007-01-03 3
2007-01-04 1
2007-01-05 1

Tuesday, March 11, 2008

Oracle Triggers

CREATE OR REPLACE TRIGGER EBP.INSERT_EBP_TRADING_PARTNERS
BEFORE INSERT
ON EBP.EBP_TRADING_PARTNERS
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
DECLARE
tmpVar NUMBER;
v_fax_subject_line VARCHAR2(60);
BEGIN
tmpVar := 0;

SELECT SUBJECT_LINE INTO v_fax_subject_line FROM EBP_BILLERS WHERE BILLER_ID = :NEW.BILLER_ID;

IF :NEW.FAX_SUBJECT IS NULL THEN
:NEW.FAX_SUBJECT := v_fax_subject_line;
END IF;

EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line('Warning: The Biller_Id does not exist in EBP_BILLERS table.');

END ;
/

CONCAT Strings in Oracle v.s. MySQL

Oracle uses the CONCAT(string1, string2) function or the || operator. The Oracle CONCAT function can only take two strings so the above example would not be possible as there are three strings to be joined (FirstName, ' ' and LastName). To achieve this in Oracle we would need to use the || operator which is equivalent to the + string concatenation operator in SQL Server / Access.

-- Oracle
SELECT FirstName || ' ' || LastName As FullName FROM Customers

MySQL uses the CONCAT(string1, string2, string3...) function. The above example would appear as follows in MySQL

-- MySQL
SELECT CONCAT(FirstName, ' ', LastName) As FullName FROM Customers