数据库数据表的一些操作脚本

SQLServer 数据库一些基本操作的脚本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use master
go

create database TestDB
on primary
(
name='TestDB_data',
filename='F:\DB\TestDB_log.mdf',--绝对路径
size=10MB,--数据库初始大小
filegrowth=5MB --数据文件增长量
--上面四个文件缺一不可
)
log on
(
name='TestDB_log',
filename='F:\DB\TestDB_log.ldf',
size=5MB,
filegrowth=2MB
)

go
▲ 创建数据库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use master
go

if exists(select * from sysdatabases where name = 'TestDB01')
drop database TestDB01 --删除就不能恢复了,一般测试阶段数据库内没有数据的时候用。

create database TestDB01
on primary
(
name='TestDB01_data',
filename='F:\DB\TestDB01_data.mdf',
size=5MB,
filegrowth=2MB
)
,
(
name='TestDB01_data1',
filename='F:\DB\TestDB01_data.ndf',
size=5MB,
filegrowth=2MB
)

log on
(
name='TestDB01_log',
filename='F:\DB\TestDB01_log.ldf',
size=2MB,
filegrowth=1MB
)
,
(
name='TestDB01_log1',
filename='F:\DB\TestDB01_log1.ldf',
size=2MB,
filegrowth=1MB
)
go
▲ 创建前判断,一起创建关联数据库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use TestDB
go

if exists(select * from sysobjects where name= 'Students')
drop table Students
go

create table Students
(
StudentId int identity(100000,1),--学号
StudentName varchar(20) not null,--姓名
Gender char(2) not null, --性别
Birthday datetime not null,--出生日期
StudentIdNo numeric(18,0) not null,--身份证号
Age int not null,--年龄。其实可以通过身份证号来动态获取
PhoneNumber varchar(50),--电话号码
StudentAddress varchar(500),--地址
ClassId int not null--班级外键
)
go

--创建班级表
if exists(select * from sysobjects where name='StudentClass')
drop table StudentClass
go
create table StudentClass
(
ClassId int primary key,--班级编号
ClassName varchar(20) not null--班级名称

)
go

--创建成绩表
if exists(select * from sysobjects where name='ScoreList')
drop table ScoreList
go
create table ScoreList
(
Id int identity(1,1) primary key,
StudentId int not null,--学号外键
CSharp int null,
SQLServer int null,
UpdateTime datetime not null,--更新时间
)
go

--创建管理员表
if exists(select * from sysobjects where name='Admins')
drop table Admins
go
create table Admins
(
LoginId int identity(1000,1) primary key,
LoginPwd varchar(20) not null,--登录密码
AdminName varchar(20) not null
)
go

--添加相关约束
--创建主键约束
use TestDB
go
if exists(select * from sysobjects where name='pk_StudentId')
alter table Students drop constraint pk_StudentId

alter table Students add constraint pk_StudentId primary key(StudentId)

--添加相关约束
--创建唯一约束
use TestDB
go
if exists(select * from sysobjects where name='uq_StudentsIdNo')
alter table Students drop constraint uq_StudentsIdNo
alter table Students add constraint uq_StudentsIdNo unique(StudentIdNo)
▲ 数据表的一些操作
感谢支持!