代码改变世界

主、外键约束

2013-04-19 18:03  段少洁  阅读(129)  评论(0编辑  收藏  举报

--创建数据库----------

use master go

if exists(select * from Sysdatabases where name='学生数据库')

 drop database 学生数据库

create database 学生数据库

on primary(

 name=学生数据库,

 filename='d:\data\学生数据库.mdf',

 size=5,

 maxsize=300

)

log on(

 name=学生数据库_log,

 filename='d:\data\学生数据库_log.ldf',

 size=5,

 maxsize=300

)

----创建表------------

use 学生数据库 go

if exists(select * from Sysobjects where name='学生表')

 drop table 学生表

create table 学生表 (

 学号 char(6) primary key,

 姓名 char(30) not null,

 性别 char(4) check(性别 in('男','女')),

 年龄 char(6) not null,

 民族 char(4) default('汉') not null,

 身份证号 char(20) unique,

 宿舍号 char(6) foreign key references 宿舍表(宿舍号)

)

use 学生数据库 go

if exists(select * from Sysobjects where name='宿舍表')

 drop table 宿舍表

create table 宿舍表 (

 宿舍号 char(6) primary key,

 宿舍电话 char(20) not null

)

-----修改表--------

insert into 宿舍表 values('101','00123456')

insert into 宿舍表 values('102','00134678')

update 宿舍表 set 宿舍电话='1234567' where 宿舍号='101'

delete from 宿舍表 where 宿舍号='102'

insert into 学生表 values ('01','duanshaojie','女','20','','12454567','101')

----先删学生表,再删宿舍表---------

delete from 学生表 where 宿舍号='101'

delete from 宿舍表 where 宿舍号='101'