首页 > 代码库 > 数据定义语言DDL - 建库建表

数据定义语言DDL - 建库建表

数据库文件构成:主文件(MDF)、次要文件(NDF)、日志文件(LDF)

其中主文件和日志文件是必须的,次要文件可以有多个(存放在不同分区以提高速度),也可以没有

创建数据库文件主要用到5个属性:

name、filename、size、maxsize、filegrowth

use mastergoif exists (select * from sysdatabases where name=db)drop database dbgocreate database dbon primary(    name = db_mdf,    filename = c:\temp\db.mdf,    size = 10,    maxsize = 100,    filegrowth = 5),(    name = db_ndf,    filename = c:\temp\db.ndf,    size = 10,    maxsize = 100,    filegrowth = 5)log on(    name = db_ldf,    filename = c:\temp\db.ldf,    size = 10,    maxsize = 100,    filegrowth = 5)go

常见数据类型

字符:char、varchar、nvarchar
数值:int、decimal
时间:date、datetime
布尔:bit
图片:image
文本:xml
 
创建表的SQL语句
use dbgoif exists (select * from sysobjects where name=score)drop database scoregoif exists (select * from sysobjects where name=corse)drop database corsegoif exists (select * from sysobjects where name=grade)drop database gradegoif exists (select * from sysobjects where name=student)drop database studentgocreate table student(    id int primary key identity(1,1),    name nvarchar(50) not null,    gender bit default true,    joindate date default getdate())gocreate table grade(    id int primary key identity(1,1),    name nvarchar(50) not null unique,    state bit default true)gocreate table corse(    id int primary key identity(1,1),    name nvarchar(50) not null unique,    state bit default true,    gradeid int not null,    constraint fk_corse_gradeid foreign key (gradeid) references grade(id))alter table corse nocheck constraint fk_corse_gradeidgocreate table score(    studentid int foreign key references student(id) on delete cascade,    corseid int foreign key references corse(id) on delete cascade,    examtime datetime default getdate(),    value decimal(4,1) check(value between 0 and 100),    constraint pk_score primary key clustered (studentid,corseid))go

数据库完整性主要包括:

实体完整性
域完整性
引用完整性
自定义完整性
 
数据库约束主要包括:
主键:primary key [clustered]
外键:foreign key references [on delete cascade | nocheck constraint]
唯一:unique
非空:not null
检查:check
默认:default
 

数据定义语言DDL - 建库建表