2024年4月19日发(作者:)
一、基础(建表、建约束、关系)
约束(Constraint)是Microsoft SQL Server 提供的自动保持数据库完整性的一种方法,定
义了可输入表或表的单个列中的数据的限制条件(有关数据完整性的介绍请参见第9 章)。
在SQL Server 中有5 种约束:主关键字约束(Primary Key Constraint)、外关键字约束
(Foreign Key Constraint)、惟一性约束(Unique Constraint)、检查约束(Check Constraint)
和缺省约束(Default Constraint)。
(最后几页介绍SQL基础约束)
1、说明:创建数据库
CREATE DATABASE database-name
2、说明:删除数据库
drop database dbname
3、说明:备份sql server
--- 创建备份数据的 device
USE master
EXEC sp_addumpdevice 'disk', 'testBack', 'c:mssql7backupMyNwind_'
--- 开始备份
BACKUP DATABASE pubs TO testBack
4、说明:创建新表
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)
--建表、建约束、关系
create table tableok
(
col1 int, col2_notnull int not null,
col3_default nchar(1) not null default('男'),
--默认男
col4_default datetime not null default(getdate()),
--默认得到系统时间
col5_check int not null check(col5_check>=18 and col5_check<=55), --添加约
束,数据值在18到55之间
col6_check nchar(9) not null check(col6_check like 'msd0902[0-9][^6-9]'),
--添加约束,数据值前7位必须是„msd0902‟,倒数第两位可以是0-9中任意一个数字,最
后一位不是6-9之间的数字。
cola_primary nchar(5) not null primary key,
--建立主键
colb_unique int unique,
--唯一约束
col7_Identity int not null identity(100,1),
--自增长,从100开始,每列值增加1个
col8_identity numeric(5,0) not null identity(1,1)
--自增长,从1开始,每列值增加1个,最大值是5位的整数
col9_guid uniqueidentifier not null default(newid())
--使用newid()函数,随机获取列值
)
--alter
--主外键/引用/关系 约束
alter table 从表名 [with check]--启用 with nocheck--禁用约束
add constraint FK_主表名_从表名
foreign key (从表中的字段名) references 主表名 (主表中的字段名)
发布评论