Search code examples
sqldatabasesql-server-2005unique-constraintnon-clustered-index

How to drop a unique constraint from table column?


I have a table 'users' with 'login' column defined as:

[login] VARCHAR(50) UNIQUE NOT NULL

Now I want to remove this unique constraint/index using SQL script. I found its name UQ_users_7D78A4E7 in my local database but I suppose it has a different name on another database.

What is the best way to drop this unique constraint? Or at least any...

Thanks.


Solution

  • SKINDER, your code does not use column name. Correct script is:

    declare @table_name nvarchar(256)  
    declare @col_name nvarchar(256)  
    declare @Command  nvarchar(1000)  
    
    set @table_name = N'users'
    set @col_name = N'login'
    
    select @Command = 'ALTER TABLE ' + @table_name + ' drop constraint ' + d.name
        from sys.tables t 
        join sys.indexes d on d.object_id = t.object_id  and d.type=2 and d.is_unique=1
        join sys.index_columns ic on d.index_id=ic.index_id and ic.object_id=t.object_id
        join sys.columns c on ic.column_id = c.column_id  and c.object_id=t.object_id
        where t.name = @table_name and c.name=@col_name
    
    print @Command
    
    --execute (@Command)