SQLserver中对字段定义默认值的形式

原创
小哥 3年前 (2022-11-02) 阅读数 46 #大杂烩

在使用数据库工作时,经常用来构建表格和设置某些字段的缺省值,在以后插入数据时不需要增加价值。

在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

结果如下:

后记:我很久没有写过一篇文章了。让我们先编写一个简单的方法。

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门