这个MERGE有什么不对

时间:2015-02-16 15:21:31

标签: sql teradata

这个合并声明有什么问题,我在匹配时有多个更新条件, 我在“匹配时”提供了moore join条件,但它不起作用

    MERGE INTO DATABASE1.TARGET AS KEY_SBSCR
    USING (
        SELECT
         SOURCE_KEY
        ,DOMAIN_NAME
        ,EDW_KEY
        ,CUSTOMER_ID
        ,START_DATE
        ,END_DATE
        ,PROCESS_ID
        ,UPDATE_PROCESS_ID
        ,NEG_UPD_FLAG
        ,FILEID
        ,CAST(ROW_NUMBER() OVER (ORDER BY SOURCE_KEY) +(SELECT COALESCE(MAX(EDW_KEY),'0') FROM DATABASE1.TARGET) AS INTEGER) as NEW_KEY
    FROM TARGET.TEST
    ) AS KEY_TEMP
    ON KEY_SBSCR.EDW_KEY=KEY_TEMP.EDW_KEY
    WHEN MATCHED AND KEY_SBSCR.END_DATE=CAST('99991231' AS DATE FORMAT 'YYYYMMDD') 
                THEN
                                    UPDATE SET  KEY_SBSCR.END_DATE=KEY_TEMP.END_DATE
                                                                ,KEY_SBSCR.UPDATE_PROCESS_ID=KEY_SBSCR.UPDATE_PROCESS_ID    
    WHEN MATCHED AND    KEY_SBSCR.CUSTOMER_ID IS NULL 
        THEN 
                            UPDATE SET  KEY_SBSCR.CUSTOMER_ID=KEY_TEMP.CUSTOMER_ID
                                                        ,KEY_SBSCR.UPDATE_PROCESS_ID=KEY_SBSCR.UPDATE_PROCESS_ID
    WHEN NOT MATCHED  BY KEY_SBSCR THEN
                                    INSERT (SOURCE_KEY,DOMAIN_NAME,EDW_KEY,CUSTOMER_ID,START_DATE,END_DATE,PROCESS_ID,UPDATE_PROCESS_ID,NEG_UPD_FLAG,FILEID)
                            VALUES (SOURCE_KEY,DOMAIN_NAME,NEW_KEY,CUSTOMER_ID,START_DATE,END_DATE,PROCESS_ID,UPDATE_PROCESS_ID,NEG_UPD_FLAG,FILEID)

感谢

1 个答案:

答案 0 :(得分:2)

您的查询看起来像SQL Server语法,但Teradata不支持多个WHEN MATCHED加上ANDed条件...

我不知道这种解决方法是否真的有效,但您可能会尝试将这两种情况合并为一种:

MERGE
....
ON KEY_SBSCR.EDW_KEY=KEY_TEMP.EDW_KEY
AND (KEY_SBSCR.END_DATE=CAST('99991231' AS DATE FORMAT 'YYYYMMDD')
     OR KEY_SBSCR.CUSTOMER_ID IS NULL )
WHEN MATCHED THEN 
UPDATE SET
         KEY_SBSCR.END_DATE=CASE WHEN KEY_SBSCR.END_DATE=CAST('99991231' AS DATE FORMAT 'YYYYMMDD'
                                 THEN KEY_TEMP.END_DATE 
                                 ELSE KEY_SBSCR.END_DATE 
                            end
       , KEY_SBSCR.CUSTOMER_ID=CASE WHEN KEY_SBSCR.CUSTOMER_ID IS NULL 
                                    THEN KEY_TEMP.CUSTOMER_ID 
                                    ELSE KEY_SBSCR.CUSTOMER_ID 
                               end
       ,KEY_SBSCR.UPDATE_PROCESS_ID=KEY_SBSCR.UPDATE_PROCESS_ID
WHEN NOT MATCHED THEN
INSERT ...

顺便说一下,您最好使用CAST('99991231' AS DATE FORMAT 'YYYYMMDD')

而不是DATE '9999-12-31'