2012-02-15 62 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中的默認的約束名。只需找到給定數據庫的表格文件夾並查看約束條件。如果有很多約束條件,你可以「將約束腳本寫入一個查詢窗口,其中顯示相關的列名稱。