2

有没有一种方法可以从表中删除除主键之外的所有唯一键?

我的键名是由 ORM 生成的,我不能保证它们的名字。

4

2 回答 2

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
于 2012-10-10T08:43:32.227 回答
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'
于 2012-10-10T08:59:59.153 回答