Gre*_*egM 11 sql sql-server default-value alter
我正在尝试将SQL Server中列的数据类型从tinyint更改为smallint.
但是我的列上有一个默认值,我不知道约束的名称.
有一个简单的方法吗?
由于默认约束,这不起作用:
ALTER TABLE mytable
Alter Column myColumn smallint NOT NULL default 1
Run Code Online (Sandbox Code Playgroud)
mar*_*c_s 23
您需要分几步完成此操作 - 首先:删除列上的默认约束,然后修改列.
你可以使用这样的代码:
-- 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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
32805 次 |
最近记录: |