Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL remove autonamed constraints

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.

like image 365
Dimitar Tsonev Avatar asked Jan 19 '13 10:01

Dimitar Tsonev


People also ask

How do you drop unnamed constraints?

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.

How do I remove a check constraint in SQL?

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.


2 Answers

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%'
like image 159
pkmiec Avatar answered Sep 22 '22 11:09

pkmiec


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);
like image 33
Dimitar Tsonev Avatar answered Sep 22 '22 11:09

Dimitar Tsonev