How to check if constraint exists before adding

Forum related to Firebird

Moderators: gto, cipto_kh, EgonHugeist

Post Reply
kerino
Junior Boarder
Junior Boarder
Posts: 27
Joined: 26.06.2008, 10:04

How to check if constraint exists before adding

Post by kerino »

Hi, I'm using Zeos and Firebird.
I create a table with a constraint e.g.
'ALTER TABLE Table1 ADD CONSTRAINT FK_TEST1 FOREIGN KEY (Field1) REFERENCES Table2(Field2)'

When I run the program again, the constraint already exists so I get an error. How can I change the statement to avoid the error please? (I'm rather new to all this)

Many thanks
Kerin
User avatar
mdaems
Zeos Project Manager
Zeos Project Manager
Posts: 2766
Joined: 20.09.2005, 15:28
Location: Brussels, Belgium
Contact:

Post by mdaems »

You can do a Query against the system tables to check if the constraint exists.
Alternatively, you could use TZSQLMetaData Component to get the constraints that are present in the database. You'll have to check how a foreign key constraint shows up there as I don't know that myself, however. Set Metadatatype property to mdImportedKeys , mdExportedKeys or mdCrossReference. One of these might reveal the existing constraint names so you could check.

Mark
Image
kerino
Junior Boarder
Junior Boarder
Posts: 27
Joined: 26.06.2008, 10:04

Post by kerino »

Thanks Mark,
I am currently querying the RDB$REF_CONSTRAINTS table for the RDB$CONSTRAINT_NAME tosee if it exists.
I just thought there might be a more elegant way to do it in one SQL statement (using IF EXISTS or something).
Anyway, what I have seems to work, although it's not ideal.
I haven't used the TZSQLMetaData component, so I'll have a look at it.

Thanks again.
Post Reply