2012-10-10 48 views

回答

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' 
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 
+0

只是問:它以某種方式不同(查詢部分和我們說,我們將使用 'USE DB_NAME' 切換到所需的DB)來自: SELECT「ALTER TABLE '+ TC.CONSTRAINT_SCHEMA +'。' + TC.TABLE_NAME +'DROP CONSTRAINT'+ TC.CONSTRAINT_NAME從INFORMATION_SCHEMA.TABLE_CONSTRAINTS查詢 作爲TC其中TC.CONSTRAINT_TYPE ='UNIQUE' – Bax