Pergunta

I get an Integrity constraint violation by a delete sql statement. This happens because the id of a table is used in another table as Primary Key. However I want to delete them anyway, by using CASCADE.

But what's the correct syntax for hsqldb?

enter image description here

Foi útil?

Solução

The DELETE statement does not support a "cascade" keyword (which is clearly documented in the manual)

You need to setup the foreign key constraint to cascade deletes:

create table playlist
(
   id integer primary key not null, 
   ... other columns ...
);

create table playlistmovies
(
   id integer primary key not null,
   playlist_id integer not null,
   ... other columns
);

alter table playlistmovies
   add constraint fk_plm_playlist
   foreign key (playlist_id) references playlist(id)
   on delete cascade;

Then when you delete a playlist, all rows referencing that playlist are also deleted.

Outras dicas

while creating child table You Add 'On delete cascade' in foreign key constraint as below.

ALTER TABLE ADD [CONSTRAINT ] FOREIGN KEY () REFERENCES () ON DELETE CASCADE;

Adds a foreign key constraint to the table, using the same constraint syntax as when the foreign key is specified in a table definition.

After that you delete your parent record it will deelte child record also.

In the current version of HSQLDB (I'm using 2.5.0) the ON DELETE CASCADE modifier can be specified on the column definition statement, it does not need to be added using ALTER TABLE. This allows for concise, more readable SQL.

For example, this works:

CREATE TABLE IF NOT EXISTS TestRecord
(
    -- Primary key column
    id        INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,

    -- Example fields
    sValue    VARCHAR(100),
    iValue    INTEGER,
);


CREATE TABLE IF NOT EXISTS TestRecordJoin
(
    -- Foreign key column, specifying cascade delete behavior.
    kRecord INTEGER     NOT NULL FOREIGN KEY REFERENCES TestRecord ON DELETE CASCADE,

    -- Example fields
    sValue2 VARCHAR(64) NOT NULL,
    iValue2 INTEGER     NOT NULL
);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top