【问题标题】:How to modify datatype of a column with a default value如何使用默认值修改列的数据类型
【发布时间】:2012-03-07 04:23:54
【问题描述】:

我正在尝试将 SQL Server 中列的数据类型从 tinyint 更改为 smallint。

但是我的列上有一个默认值,我不知道约束的名称。

有没有简单的方法?

由于默认约束,这不起作用:

ALTER TABLE mytable
Alter Column myColumn smallint NOT NULL default 1

【问题讨论】:

    标签: sql sql-server default-value alter


    【解决方案1】:

    您需要分几个步骤执行此操作 - 首先:删除列上的默认约束,然后修改您的列。

    你可以使用这样的代码:

    -- find out the name of your default constraint - 
    -- assuming this is the only default constraint on your table
    DECLARE @defaultconstraint sysname
    
    SELECT @defaultconstraint = NAME 
    FROM sys.default_constraints 
    WHERE parent_object_id = object_ID('dbo.mytable')
    
    -- declare a "DROP" statement to drop that default constraint
    DECLARE @DropStmt NVARCHAR(500)
    
    SET @DropStmt = 'ALTER TABLE dbo.mytable DROP CONSTRAINT ' + @defaultconstraint
    
    -- drop the constraint
    EXEC(@DropStmt)
    
    -- alternatively: if you *know* the name of the default constraint - you can do this
    -- more easily just by executing this single line of T-SQL code:
    
    -- ALTER TABLE dbo.mytable DROP CONSTRAINT (fill in name of constraint here)
    
    -- modify the column's datatype        
    ALTER TABLE dbo.mytable
    Alter Column myColumn smallint NOT NULL 
    
    -- re-apply a default constraint - hint: give it a sensible name!
    ALTER TABLE dbo.mytable
    ADD CONSTRAINT DF_mytable_myColumn DEFAULT 1 FOR MyColumn
    

    【讨论】:

    • 您可能应该将约束名称选择过滤为列名称,以防表有多个默认约束。 SELECT @defaultconstraint = d.NAME FROM sys.default_constraints AS d INNER JOIN sys.columns AS c ON d.parent_object_id = c.object_id AND d.parent_column_id = c.column_id WHERE d.parent_object_id = Object_id('dbo.mytable') AND c.NAME = 'myColumn '
    【解决方案2】:

    你可以分三步完成

    • 添加具有不同名称的新列,
    • 将旧列中的值复制到新列中
    • 删除旧列

    只要名字相同就可以了,然后重复这个过程把名字改回来。

    【讨论】:

    • 是的,可能是一个解决方案,但如果我有很多数据,那就不好了
    【解决方案3】:

    您可以使用 MS Management Studio 找到默认的约束名称。只需找到给定数据库的表文件夹并在约束下查看。如果有很多约束,您可以“将约束编写到显示相关列名称的查询窗口中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      • 2021-12-16
      • 1970-01-01
      相关资源
      最近更新 更多