这在SQL Server 2008中不起作用:

ALTER TABLE Employee ALTER COLUMN CityBorn SET DEFAULT 'SANDNES'

错误是:

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

我做错了什么?


当前回答

如果一个限制已经存在,它的默认名称是:

-- Drop existing default constraint on Employee.CityBorn
DECLARE @default_name varchar(256);
SELECT @default_name = [name] FROM sys.default_constraints WHERE parent_object_id=OBJECT_ID('Employee') AND COL_NAME(parent_object_id, parent_column_id)='CityBorn';
EXEC('ALTER TABLE Employee DROP CONSTRAINT ' + @default_name);

-- Add default constraint on Employee.CityBorn
ALTER TABLE Employee ADD CONSTRAINT df_employee_1 DEFAULT 'SANDNES' FOR CityBorn;

其他回答

就像Yuck的答案,检查允许脚本运行多次而没有错误。(与使用information_schema.columns相比,代码/自定义字符串更少)

IF object_id('DF_SomeName', 'D') IS NULL BEGIN
    Print 'Creating Constraint DF_SomeName'
   ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;
END

您可以使用以下语法,有关详细信息,请参阅此问题和答案:将具有默认值的列添加到SQL Server中的现有表中

语法:

ALTER TABLE {TABLENAME} 
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} 
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
WITH VALUES

例子:

ALTER TABLE SomeTable
ADD SomeCol Bit NULL --Or NOT NULL.
CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is 
autogenerated.
DEFAULT (0)--Optional Default-Constraint.
WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.

另一种方法:

右键单击表并单击“设计”,然后单击要设置默认值的列。

然后在页面底部添加一个默认值或绑定:例如字符串为'1'或int为1。

不能使用alter列,而是使用add列

ALTER TABLE Employee 
ADD DEFAULT('SANDNES') 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]

刚刚发现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