在使用數據庫工作中,經常會用建表並對一些字段設置默認值,在以後的插入數據不需要再增加值了。
在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
結果如下圖:
後記:好久沒有寫文章,先寫一個簡單的方法吧。