SQL server中对字段设置默认值的方法

在使用数据库工作中,经常会用建表并对一些字段设置默认值,在以后的插入数据不需要再增加值了。

在SQL server中有三种方法可以设置默认值:

1、在建表时设置默认值:

create table test_table1(
id int,
name varchar(10),
stamp datetime DEFAULT (getdate()))--建表的时候就设置默认值
select * from test_table1
insert into test_table1 (id, name) values (1, '张三')
select * from test_table1

结果如下图:

SQL server中对字段设置默认值的方法_第1张图片

2、对已有的字段设置默认值:

create table test_table2(
id int,
name varchar(10),
stamp datetime)
select * from test_table2
--增加约束
ALTER TABLE test_table2 ADD  CONSTRAINT test_table2_stamp  DEFAULT (getdate()) FOR stamp
insert into test_table2 (id, name) values (2, '李四')
select * from test_table2

结果如下图:

SQL server中对字段设置默认值的方法_第2张图片

3、增加字段并设置默认值:

create table test_table3(
id int,
name varchar(10))
select * from test_table3
ALTER TABLE test_table3 ADD stamp datetime DEFAULT getdate()
insert into test_table3 (id, name) values (3, '王五')
select * from test_table3

结果如下图:

SQL server中对字段设置默认值的方法_第3张图片

后记:好久没有写文章,先写一个简单的方法吧。

你可能感兴趣的:(SQL,server)