问题
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
- For every record in
ZZZ_EXERCISE_5
: check if it exists inZZZ_EXERCISE_3
and if so, set theVALID
field inZZZ_EXERCISE_5
toY
.
If the records exist inZZZ_EXERCISE_3
but not inZZZ_EXERCISE_5
, insert that record intoZZZ_EXERCISE_5
.
If the records don't exist inZZZ_EXERCISE_3
but inZZZ_EXERCISE_5
, setVALID
toN
. - After that, you want to delete all records from
ZZZ_EXERCISE_3
for which a matching record inZZZ_EXERCISE_5
hasVALID
=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