码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-01-29 19:22:47      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:

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

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

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

name、filename、size、maxsize、filegrowth

use master
go

if exists (select * from sysdatabases where name=db)
drop database db
go

create database db
on 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 db
go

if exists (select * from sysobjects where name=score)
drop database score
go

if exists (select * from sysobjects where name=corse)
drop database corse
go

if exists (select * from sysobjects where name=grade)
drop database grade
go

if exists (select * from sysobjects where name=student)
drop database student
go

create table student
(
    id int primary key identity(1,1),
    name nvarchar(50) not null,
    gender bit default true,
    joindate date default getdate()
)
go

create table grade
(
    id int primary key identity(1,1),
    name nvarchar(50) not null unique,
    state bit default true
)
go

create 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_gradeid
go

create 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 - 建库建表

标签:

原文地址:http://www.cnblogs.com/rammderek/p/4260529.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!