I have created a few constraints on my table with a script without specifying the constraint name. As a result, I ended up having constraints like FK__DOC_OBGS___kntr___54E63309
for example.
Is it possible to drop that constraints without specifying the exact constraint name ?
For example, something like this (which doesn't work)
ALTER TABLE DOC_OBGS_10 DROP CONSTRAINT LIKE 'FK__DOC_OBGS___kntr%'
The problem is that we have a lot of databases with this table and I need to remove all the constraints from the tables, but apparently the name is different for each table.
First, inspect the name given to the FK by the RDBMS, it has the same prefix and body but differs only in suffix hash. Second, select names of these constraints. Third, exec alter command that drops them.
The syntax for disabling a check constraint in SQL Server (Transact-SQL) is: ALTER TABLE table_name NOCHECK CONSTRAINT constraint_name; table_name. The name of the table that you wish to disable the check constraint.
DDL commands in SQL do not cooperate with like operator.
However, you may use information_schema views and easily build SQL for drop constraint commands, like this:
SELECT 'ALTER TABLE DOC_OBGS_10 DROP CONSTRAINT ' + CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_NAME LIKE 'FK__DOC_OBGS___kntr%'
DECLARE @sql1 NVARCHAR(MAX);
SELECT @sql1 = c
FROM
(
SELECT 'ALTER TABLE DOC_INVS_1 DROP CONSTRAINT ' + CONSTRAINT_NAME + '; '
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'DOC_INVS_1'
and CONSTRAINT_NAME LIKE 'FK__DOC_INVS___kntr%'
) T(c);
EXEC(@sql1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With