SQL remove autonamed constraints

喜欢而已 提交于 2019-12-08 15:36:53

问题


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.


回答1:


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%'



回答2:


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);



回答3:


I faced a similar issue after using the Access to SQL Server upsizing tool. In my case I needed to loop all of the tables for matching constraints, which can be done like this:

DECLARE @sql1 NVARCHAR(MAX);

-- Concatenate all the drop statements in the inner loop into a single SQL string
SELECT @sql1 = STUFF((SELECT '; ' + a.t FROM 
(
    -- find all the constraints we're interested in and create a list of 
    -- SQL statements to drop them
    SELECT 'ALTER TABLE [' + p.name + '] DROP CONSTRAINT [' + o.name + ']' as t
    FROM sys.objects o
    left join sys.objects p on o.parent_object_id = p.object_id 
    WHERE o.name LIKE '%disallow_zero_length' 
) a
FOR XML PATH('')), 1, 2, '')

print @sql1

-- Execute the bit concatenated drop statement
EXEC(@sql1);

You can avoid the STUFF method in later versions of SQL Server, see this answer for more on that.



来源:https://stackoverflow.com/questions/14413486/sql-remove-autonamed-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!