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

在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

结果如下图:

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

结果如下图:

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

结果如下图:

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

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐