有没有办法可以从主表中删除表中的所有唯一键?
我的密钥名称是由ORM生成的,我不能保证他们的名字。
答案 0 :(得分:1)
这将删除所有唯一约束,它不会丢弃主键。主键仍然会强制实现唯一性。
declare @table_name nvarchar(50) = 'yourtable' -- table
declare @SchemaName nvarchar(50) = 'yourschema' -- dbo
declare @Catalog nvarchar(50) = 'yourdatabase' -- database
select * into #t from
(
select 'ALTER TABLE ' + TC.CONSTRAINT_CATALOG + '.' + TC.CONSTRAINT_SCHEMA + '.' + TC.TABLE_NAME + ' DROP CONSTRAINT ' + CCU.CONSTRAINT_NAME query
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS as TC
inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE as CCU
on TC.CONSTRAINT_CATALOG = CCU.CONSTRAINT_CATALOG
and TC.CONSTRAINT_SCHEMA = CCU.CONSTRAINT_SCHEMA
and TC.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME
where TC.CONSTRAINT_CATALOG = coalesce(@Catalog, db_name())
and TC.CONSTRAINT_SCHEMA = @SchemaName
and TC.TABLE_NAME = @table_name
and TC.CONSTRAINT_TYPE = 'UNIQUE'
) a
DECLARE @sqlstring as nvarchar(500)
DECLARE SqlCursor CURSOR FAST_FORWARD FOR
SELECT query FROM #t
OPEN SqlCursor
FETCH NEXT FROM SqlCursor
INTO @sqlstring
WHILE @@FETCH_STATUS = 0
BEGIN
exec(@sqlstring)
FETCH NEXT FROM SqlCursor
INTO @sqlstring
END
CLOSE SqlCursor
DEALLOCATE SqlCursor
DROP TABLE #t
答案 1 :(得分:1)
试试这个
select
distinct 'Alter table MyTable drop constraint '+o.name
from sys.objects o
join sys.columns c on o.parent_object_id = c.object_id AND o.type='UQ'
join sys.tables t on c.object_id = t.object_id
where t.name = 'MyTable'