gpt4 book ai didi

sql - 如何修改具有默认值的列的数据类型

转载 作者:行者123 更新时间:2023-12-02 09:02:10 25 4
gpt4 key购买 nike

我正在尝试将 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

关于sql - 如何修改具有默认值的列的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9299966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com