Should I use information_schema.referential_constraints or sys.foreign_keys to check a key's existence?
I've been checking the existence of foreign keys before deleting like so:
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_NAME ='FK_Table1_Table2')
ALTER TABLE dbo.Table1
DROP CONSTRAI开发者_高级运维NT FK_Table1_Table2
It then occurred to me that there's a sys.foreign_keys
table that holds this information as well, and now I'm not sure which is best.
My guess is that if i know that I'll only be deleting FKs then I should use sys.foreign_keys
, but if I don't know what type of constraint I'm dropping I should use the former method. Is this correct? Am I missing any important differences?
If you are using MS SQL server only, I suggest using views from sys schema, as you can get more information. sys schema is defined by MS SQL. You can get all kinds of info that is MS SQL specific and has no counterparts in other DBMS.
If you are concerned about portability, if you want to comply with other databases, use INFORMATION_SCHEMA, as this is cross-database ISO standard. Whichever database that claims to support this standard must return the data in the same way. Hence this approach has limitation.
精彩评论