网站首页 > 数据库教程 > 面试准备之SQL 2——数据库的实现(T-SQL建库建表)

面试准备之SQL 2——数据库的实现(T-SQL建库建表)

  • 作者:互联网
  • 时间:2010-05-05 16:23:25

1. 数据库文件包括:

主数据文件:*.mdf

次要数据文件:*.ndf

日志文件:*.ldf ( l 是 L 的小写)

 

2.使用T-SQL创建数据库

 

代码
use master
go
-----------创建数据库------------

if exists (select * from sysdatabases where name='stuDB')
drop database stuDB
create database stuDB
on primary
(
name='stuDB_data',
filename='D:st***_data.mdf',
size=3mb,
maxsize=10mb,
filegrowth=1mb
)
log on
(
name='stuDB_log',
filename='D:st***_data.ldf',
size=1mb,
filegrowth=1mb
)

 

 

3.使用T-SQL 创建数据库表

 

代码
-----------创建数据库表------------
use stuDB
go
if exists (select * from sysobjects where name='stuInfo')
drop table stuInfo
create table stuInfo
(
    stuName varchar(20) not null,
    stuNo char(6) not null,
    stuAge int not null,
    stuID numeric(18,0),--身份证
    stuSeat smallint identity(1,1),
    stuAddress text
)
go

if exists (select * from sysobjects where name='stuMarks')
drop table stuMarks
create table stuMarks
(
    ExmaNo char(7) not null, --考号
    stuNo char(6) not null,--学号
    writtenExam int  not null,--笔试成绩
    LabExam int not null--机试成绩
)
go
 

 

4. 添加约束

 

代码
--------------添加约束-----------------

alter table stuinfo --修改stuinfo表
add constraint PK_stuNo primary key (stuNo)--添加主键 PK_stuNo是自定义的主键名 也可以省略

alter table stuinfo
add constraint UQ_stuID unique (stuID) --添加唯一约束

alter table stuinfo
add constraint DF_stuAddress default ('地址不详') for stuAddress--添加默认  不填默认’地址不详‘

alter table stuinfo
add constraint CK_stuAge check(stuAge between 18 and 60) --添加检查约束 18-60岁

alter table stuMarks
add constraint FK_stuNo foreign key(stuNo) references stuInfo(stuNo)
go
 

 

5.删除约束

 

-------------删除约束--------------
alter table stuinfo
drop constraint 约束名 --如:FK_stuNo  CK_stuAge DF_stuAddress UQ_stuID PK_stuNo