SQL server 通过脚本创建数据库和表实例

创建的数据库关系图如下 

以下是创建数据库的脚本代码


--指向要操作的数据库
use master
go
--创建数据库
if exists(select * from sysdatabases where name='LibraryDBDemo')
--如果数据库里面已经有这个则执行下面删除此数据库
drop database LibraryDBDemo--注意这个数据库有没有重要数据删除就没有了
go
create database LibraryDBDemo
 on primary--主数据文件
 (
 name='LibraryDBDemo_Data',--数据库逻辑文件名(就是数据库内部名称,必须唯一)
 filename='d:\db\LibraryDBDemo_data.mdf',--数据库物理文件名(给操作系统使用)注意文件目录要存在
 size=6MB,--数据库初始大小(请务必根据实际项目数据来决定)
 filegrowth=6MB --当数据库文件以及存满数据时,数据自动增加量
 )
 log on--日志文件
 (
 name='LibraryDBDemo_log',
 filename='d:\db\LibraryDBDemo_log.ldf',
 size=5MB,
 filegrowth=5MB
 )
 go

 --创建数据表
 use LibraryDBDemo  --指向这个数据库
 go

 --创建图书分类表
 if exists(select * from sysobjects where name='Categories')--查询如果有这表则删除这个表
 drop table Categories
 go
 create table Categories
 (
 CategoryId int identity(1,1) primary key,--分类编号主键 以1开始 自动增长1
 CategoryName varchar(50) not null--分类名称,限长50 不允许为空
 )
 go

 --创建出版社图书分类表
 if exists(select * from sysobjects where name='Publisher')--查询如果有这表则删除这个表
 drop table Publishers
 go
 create table Publishers
 (
 PublisherId int identity(1,1) primary key,--分类编号主键 以1开始 自动增长1
 PublisherName varchar(50) --分类名称,限长50
 )
 go

 --创建图书信息表
 if exists(select * from sysobjects where name='Books')
 drop table Books
 go
 create table Books
 (
 BookId int identity(100000,1) primary key,--图片编号
 BarCode varchar(20) not null,--图片条码
 BookName varchar(100) not null,--图片名称
 Author varchar(50) not null,--图书作者
 publisherId int references Publishers(PublisherId),--出版社编号(外键 表Publishers(列PublisherId))
 PublisherDate datetime not null,--出版日期
 CategoryId int references Categories(CategoryId),--图片分类(外键 表Categories(列CategoryId) )
 RegTime dateTime default(getdate())--上架时间
 )
 go
以下是附加数据框架结构图