如何使用默认值修改列的数据类型



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

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

有简单的方法吗?

这不起作用,因为默认约束:

ALTER TABLE mytable
Alter Column myColumn smallint NOT NULL default 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

您可以将其作为三步流程

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

重要的是名称相同,然后重复此过程将名称改回。

您可以使用MS Management Studio找到默认的约束名称。只需找到给定DB的tables文件夹,然后在Constraints下查找即可。如果有许多约束,您可以"编写约束到显示相关列名的查询窗口的脚本。

最新更新