'IF EXISTS statement alternative in HANA
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)
Solution 1:[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
- For every record in
ZZZ_EXERCISE_5: check if it exists inZZZ_EXERCISE_3and if so, set theVALIDfield inZZZ_EXERCISE_5toY.
If the records exist inZZZ_EXERCISE_3but not inZZZ_EXERCISE_5, insert that record intoZZZ_EXERCISE_5.
If the records don't exist inZZZ_EXERCISE_3but inZZZ_EXERCISE_5, setVALIDtoN. - After that, you want to delete all records from
ZZZ_EXERCISE_3for which a matching record inZZZ_EXERCISE_5hasVALID=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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
