2012-02-15 94 views
8

我试图将SQL Server中列的数据类型从tinyint更改为smallint。如何修改具有默认值的列的数据类型

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

有没有简单的方法来做到这一点?

这不,因为默认约束的工作:

ALTER TABLE mytable 
Alter Column myColumn smallint NOT NULL default 1 

回答

19

您需要在多个步骤中执行此操作 - 首先:在列上放置默认约束,然后修改您的列。

你可以使用代码是这样的:

-- 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 
2

你能做到这一点的三个步骤

  • 用不同的名称添加新列,
  • 副本从旧列到新值
  • 下降旧列

重要的是名称相同,然后重复该过程以更改名称。

+0

是的可能是一个解决方案,但如果我有很多数据,它不会很好 – GregM 2012-02-15 19:47:50

0

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