数据库、数据表的创建SP2

时间:2023-03-09 04:32:58
数据库、数据表的创建SP2
 

本人前一个版本的数据库、数据表的创建由于不是很详细,于是通过细心的修订,已经修复了很多Bug,希望这篇文章能够给大家一些帮助

 --代表注释,相当于C#里的//
--切换到master数据库,目的是查询所要创建的数据库存不存在
use master
go
--打开高级选项
exec sp_configure 'show advanced options',1
go
RECONFIGURE
go
--将xp_cmdshell设置为true
exec sp_configure 'xp_cmdshell',1
go
RECONFIGURE
go
--利用xp_cmdshell创建文件路径,防止出现路径不存在的错误
exec xp_cmdshell 'mkdir E:\C#学习\项目实例\超市会员信息管理系统'
go
------------------------------------------------------
--判断数据库是不否存在,存在的话就删除
if exists(select * from sysdatabases where name='SuperMark')
drop database SuperMark
go
--创建数据库SuperMark
create database SuperMark
on primary --创建主数据文件SuperMark_data.mdf
( name='SuperMark_data',--文件的名字
size=3mb, --文件的初始大小
maxsize=1024mb, --文件的最大大小
filegrowth=3mb, --文件的自动增长
filename='E:\C#学习\项目实例\超市会员信息管理系统\SuperMark_data.mdf' --文件的路径 )
log on --创建数据库的配置文件,它一般不指定maxsize
(
name='SuperMark_log',
size=3mb,
filegrowth=3mb,
filename='E:\C#学习\项目实例\超市会员信息管理系统\SuperMark_log.ldf'
)
go
--切换到SuperMark数据库,这步很有必要,不切换的话,下面创建的数据表就不是这个数据库的了
use SuperMark
--判断States表是否存在,存在就删除
if exists(select * from sysobjects where name='States')
drop table States
go
--创建表States
create table States
(
--添加字段
--字段名 数据类型 约束(主键,标识符,check,非空等)
Id int primary key identity(1,1),
StatesName varchar(20) not null,
) -----------------
if exists(select * from sysobjects where name='UsersInfo')
drop table UsersInfo
go
create table UsersInfo
(
Id int primary key identity(1,1),
CustomerId varchar(20) not null,
CustomerPassword varchar(20) not null,
CustomerType varchar(10) not null,
Score int not null,
statusId int not null
)
--------------------------------------------
--alter table 表名 语句用于在已有的表中添加、修改或删除列。
alter table UsersInfo --(alter table UsersInfo with nocheck 这样在执行时不检查原有数据)
--添加约束 add constraint 约束名 约束类型 具体操作
--外键约束add constraint FK_teacher_subjectId foreign key(subjectid) references subject(id)on delete no action
--主键约束add constraint PK_id primary key(id)
--唯一键约束add constraint UQ_name unique(name)
--Check约束add constraint CK_Age check(age>0 and age<=100)
--默认值add constraint DF_Birthday default('1999-9-9') for birthday
add constraint FK_UsersInfo_statusId foreign key(statusid) references states(id) on delete no action -----------------------------------------
--为表States插入3条数据
insert into States values('合法账户')
insert into States values('非法账户')
insert into States values('被禁账户')
-----------------------------------------
--为表UsersInfo插入3条数据
insert into UsersInfo values('leichaowen','leichaowenmima','钻石卡',69999,1)
insert into UsersInfo values('zhouyanqun','zhouyanqunmima','铂金卡',59999,1)
insert into UsersInfo values('leiqun','leiqunmima','金卡',49999,1)