Reputation:
I have tables "Item" and "Category", where "Item" contains a foreign key constraint that references "Category" (i.e. every item has the name of a category element in its category-column). This constraint is called "CONSTRAINT_74E".
When the data is changed by the user, I need to overwrite the entire database. For this I use the TRUNCATE command. I tried to disable the constraint to truncate CATEGORY:
command = "truncate table ITEM;";
s.execute(command); //throws no exception
command = "alter table ITEM disable constraint CONSTRAINT_74E;\n" +
"truncate table CATEGORY;\n" +
"alter table ITEM enable constraint CONSTRAINT_74E;";
s.execute(command);
This yields the following exception:
org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "ALTER TABLE ITEM DISABLE[*] CONSTRAINT CONSTRAINT_74E; TRUNCATE TABLE CATEGORY; ALTER TABLE ITEM ENABLE CONSTRAINT CONSTRAINT_74E;"; expected "., ADD, SET, RENAME, DROP, ALTER";
SQL statement: alter table ITEM disable constraint CONSTRAINT_74E; truncate table CATEGORY; alter table ITEM enable constraint CONSTRAINT_74E; [42001-200]
What exactly do I need to do to make this work? I don't see how I would need to add SET/RENAME/etc. after DISABLE.
Upvotes: 0
Views: 1285
Reputation: 88747
Of course you can't remove data that's being used as a foreign key as that would break referential integrity. You could try to remove the foreign key but adding it again would break if the keys are not the same - and if they are, why are you truncating in the first place?
Depending on your requirements you have a few options here:
Update: since you're only asking for the syntax (at least for now), have a look at the H2 commands documentation.
There you'll see that disabling foreign key checks, aka referential integrity, would be done using this command:
ALTER TABLE ITEM SET REFERENTIAL_INTEGRITY FALSE
It seems as if disabling other constraints is not supported so you might have to drop and add them again.
Btw:
I don't see how I would need to add SET/RENAME/etc. after DISABLE.
Note that ...expected "., ADD, SET, RENAME, DROP, ALTER";
doesn't mean the statement parser expects the mentioned commands after DISABLE but instead of rename, i.e. DISABLE is not supported at this possition (if at all).
Upvotes: 0