IF EXISTS statement alternative in HANA

[亡魂溺海] 提交于 2020-01-07 03:11:30

问题


I want looked for "if exists", but sap hana sql was not understand for "if exists". whether i was created sql-command wrong.

If 'Y' for the record exists in table from ZZZ_Exercise_3, else 'N' for the record not exists in table from ZZZ_Exercise_3. If old record for 'N' then this record delete should.

 CREATE COLUMN TABLE ers.ZZZ_EXERCISE_5(
    ID INT NOT NULL PRIMARY KEY generated by default as IDENTITY,
    Orig_ID INT,
    COMPANY nvarchar(251),
    VALID char(1)
);

COMMIT;

IF EXISTS(
    INSERT INTO ZZZ_EXERCISE_5(Orig_ID, COMPANY, VALID)
    SELECT ID, COMPANY, 'Y' FROM ZZZ_EXERCISE_3
)
ELSE(
    INSERT INTO ZZZ_EXERCISE_5(Orig_ID, COMPANY, VALID)
    SELECT ID, COMPANY, 'N' FROM ZZZ_EXERCISE_3
)

COMMIT;

UPDATE ZZZ_EXERCISE_3
SET COMPANY = (SELECT COMPANY FROM ERS.ZZZ_EXERCISE_5)
WHERE NOT EXISTS (SELECT COMPANY FROM ZZZ_EXERCISE_5 WHERE ZZZ_EXERCISE_5.VALID = 'N')

COMMIT;

DELETE FROM ZZZ_EXERCISE_3
WHERE ERS.ZZZ_EXERCISE_5.VALID = 'N'

SELECT * FROM ZZZ_EXERCISE_3
WHERE NOT EXISTS (SELECT COMPANY FROM ZZZ_EXERCISE_5 WHERE ZZZ_EXERCISE_5.ID = ZZZ_EXERCISE_3.ID)

回答1:


Not sure which SQL dialect would accept your statement, but IF-THEN-ELSE is typically part of the procedural extension like PL/SQL, T-SQL or SQLScript in SAP HANA.

If you explain more about what you want to achieve (instead of just posting some non-standard syntax that does not work), there are likely options to do it in SAP HANA.


If 'Y' for the record exists in table from ZZZ_Exercise_3, else 'N' for the record not exists in table from ZZZ_Exercise_3. If old record for 'N' then this record delete should.

Based on the revised description, my understanding is that you want

  1. For every record in ZZZ_EXERCISE_5: check if it exists in ZZZ_EXERCISE_3 and if so, set the VALID field in ZZZ_EXERCISE_5 to Y.
    If the records exist in ZZZ_EXERCISE_3 but not in ZZZ_EXERCISE_5, insert that record into ZZZ_EXERCISE_5.
    If the records don't exist in ZZZ_EXERCISE_3 but in ZZZ_EXERCISE_5, set VALID to N.
  2. After that, you want to delete all records from ZZZ_EXERCISE_3 for which a matching record in ZZZ_EXERCISE_5 has VALID = N

For step 1, you want to look into the

Step 2 is the easier one, so let's start with that:

   DELETE FROM ZZZ_EXERCISE_3 
   WHERE ID IN (SELECT DISTINCT ID 
                FROM ZZZ_EXERCISE_5 
                WHERE VALID ='N');

Step 1 is a bit more complicated as it shall combine UPDATEs and INSERTS. For this, SAP HANA provides the MERGE command (also called REPLACE). MERGE|REPLACE DOCU

With SAP HANA 2, there also a new command MERGE INTO that is closer to the commonly used MERGE command in other DBMS. MERGE INTO DOCU.



来源:https://stackoverflow.com/questions/43111389/if-exists-statement-alternative-in-hana

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!