sql 建库建表及约束

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:\stuDB_data.mdf',
size=3mb,
maxsize=10mb,
filegrowth=1mb
)
log on
(
name='stuDB_log',
filename='D:\stuDB_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

转载于:https://www.cnblogs.com/jasmine_xm/archive/2010/05/07/1729688.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值