Wednesday, March 29, 2017

Netezza: MERGE SQL statement

Netezza NPS release 7.2.1 comes with new MERGE SQL statement. Here are some usage examples.

-----------------------------------------------
-----  Using heap table ----
-----------------------------------------------
MERGE INTO my_target_table a
     USING my_source_table b
ON   a.UID   =  b.UID
WHEN MATCHED  AND a.DATAFIELD <> b.DATAFIELD THEN
       UPDATE SET a.DATAFIELD = b.DATAFIELD, a.UPDATED = CURRENT_TIMESTAMP
WHEN NOT MATCHED  THEN
       INSERT VALUES (b.UID,B.DATAFIELD,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)
;
-----------------------------------------------
-----  Using TET (transient external table) ---
-----------------------------------------------
MERGE INTO my_target_table A
     USING (SELECT * FROM external '/tmp/data.csv'
                                  ( UID       INT4
                                  , DATAFIELD CHARACTER VARYING(64))
                     using (Delim ',' SkipRows 0 MaxErrors 300 Logdir '/tmp'  )) B
ON   a.UID   =  b.UID
WHEN MATCHED  AND a.DATAFIELD <> b.DATAFIELD THEN
       UPDATE SET a.DATAFIELD = b.DATAFIELD ,a.UPDATED = CURRENT_TIMESTAMP
WHEN NOT MATCHED  THEN
       INSERT VALUES (b.UID,B.DATAFIELD,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)
;
-----------------------------------------------
-----  Using intermediate TEMP table ---
-----------------------------------------------
create temp table TEMP_source_table
as select * from external '/tmp/data.csv' (UID INT4, DATAFIELD CHARACTER VARYING(64)) 
   using (Delim ',' SkipRows 0 MaxErrors 300 Logdir '/tmp')
;
MERGE INTO my_target_table   A
     USING TEMP_source_table B
ON   a.UID   =  b.UID
WHEN MATCHED AND a.DATAFIELD <> b.DATAFIELD THEN
       UPDATE SET   a.DATAFIELD = b.DATAFIELD,a.UPDATED = CURRENT_TIMESTAMP
WHEN NOT MATCHED  THEN
       INSERT VALUES (b.UID,B.DATAFIELD,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)
;
-----------------------------------------------

Notice, Aginity Workbench 4.8.0 report only INSERTED records statistics, but UPDATED.  The nzsql reports both UPDATED and INSERTED records affected. 


REFER


2 comments:

  1. Hi, Can you help me to convert ITEM_ID ~~ LIKE_ESCAPE('%-%'::"VARCHAR", '\'::"VARCHAR") into Oracle code

    ReplyDelete
  2. The expression ITEM_ID ~~ LIKE_ESCAPE('%-%'::"VARCHAR", '\'::"VARCHAR") into Oracle code checks of a hypen character is part of the string. This is an Oracle alternatives to test the same condition:

    select str
    ,case when regexp_like(str,chr(45)) then 'Yes' else 'No' end as Exists_Solution1
    ,case when regexp_instr(str,chr(45)) > 0 then 'Yes' else 'No' end as Exists_Solution2
    ,case when instr(str,chr(45)) > 0 then 'Yes' else 'No' end as Exists_Solution3
    from (
    select 'adsfads' as str from dual union all
    select '-asdfdsa' as str from dual union all
    select 'adsfaa-ds' as str from dual
    )
    ;

    ReplyDelete