SQL Server 2005 drop column with constraints

后端 未结 13 917
一向
一向 2020-12-07 23:54

I have a column with a \"DEFAULT\" constraint. I\'d like to create a script that drops that column.

The problem is that it returns this error:

Msg 50         


        
相关标签:
13条回答
  • 2020-12-08 00:30

    I believe explicitly dropping the constraints prior to dropping the column is a "cleaner" solution. This way, you don't drop constraints you may not be aware of. If the drop still fails, you know there are additional constraints remaining. I like being in control of exactly what is happening to my database.

    Plus, scripting the drops explicitly guarantees the script and hopefully the results to be repeatable in exactly the way you intend.

    0 讨论(0)
  • 2020-12-08 00:34

    What do you mean randomly generated? You can look up the constraints on the specific column in management studio or via the sys.tables view and find what the name(s) are.

    Then, you can change your script to drop the constraints prior to dropping the column. What type of constraint is this? If it is a foreign key constraint, make sure that doing this won't hurt the data integrity within you database.

    0 讨论(0)
  • 2020-12-08 00:35

    You can get the constraint names by querying the information_schema system views.

    select CONSTRAINT_NAME from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE TABLE_NAME = '<tablename>' AND COLUMN_NAME = 'IsClosed'
    
    0 讨论(0)
  • 2020-12-08 00:41

    Looking up the name of the contraint or using MSSQL design view is not always an option. I currently want to make a script for deleting a column with a contraint on it. Using the name is not an option since the name is generated and I want to use the script in different environments Dev/Sys/Prod/etc. Using the name is then not possible because the contraint names will differ per environment. I will probably have to look into the systems tabel but I agree there should be an easier option available.

    0 讨论(0)
  • 2020-12-08 00:41

    Just Generate Scripts for the table. There you can find the name of all constraints.

    0 讨论(0)
  • 2020-12-08 00:42

    Here is a script that will delete the column along with its default constraint. Replace MYTABLENAME and MYCOLUMNNAME appropriately.

    declare @constraint_name sysname, @sql nvarchar(max)
    
    select @constraint_name = name 
    from sys.default_constraints 
    where parent_object_id = object_id('MYTABLENAME')
    AND type = 'D'
    AND parent_column_id = (
        select column_id 
        from sys.columns 
        where object_id = object_id('MYTABLENAME')
        and name = 'MYCOLUMNNAME'
        )
    
    set @sql = N'alter table MYTABLENAME drop constraint ' + @constraint_name
    exec sp_executesql @sql
    
    alter table MYTABLENAME drop column MYCOLUMNNAME
    
    go
    
    0 讨论(0)
提交回复
热议问题