这在SQL Server 2008中不起作用:

ALTER TABLE Employee ALTER COLUMN CityBorn SET DEFAULT 'SANDNES'

错误是:

关键字“SET”附近的语法错误。

我做错了什么?


当前回答

ALTER TABLE tblUser
 ADD CONSTRAINT DF_User_CreatedON DEFAULT GETDATE() FOR CreatedOn

其他回答

刚刚发现3个简单的步骤来改变已经存在的列,之前是空的

update   orders
set BasicHours=0 where BasicHours is null

alter table orders 
add default(0) for BasicHours

alter table orders 
alter  column CleanBasicHours decimal(7,2) not null 

正确的做法如下:

执行如下命令: Sp_help[表名] 复制约束的名称。 删除默认约束: ALTER TABLE[表名]DROP[约束名] 运行如下命令: 修改表[表名]为[列名]添加默认值[默认值]

试试下面的命令;

ALTER TABLE Person11
ADD CONSTRAINT col_1_def
DEFAULT 'This is not NULL' FOR Address
ALTER TABLE [dbo].[Employee] ADD  DEFAULT ('N') FOR [CityBorn]

第一次掉落约束

https://stackoverflow.com/a/49393045/2547164

DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N'__ColumnName__'
                        AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)

第二步创建默认值

ALTER TABLE [table name] ADD DEFAULT [default value] FOR [column name]