sql建表语句约束.doc
文本预览下载声明
sql建表语句约束
篇一:SQL语句约束大全
一、基础(建表、建约束、关系)
约束(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 #39;disk#39;, #39;testBack#39;, #39;c:\mssql7backup\MyNwind_1.dat#39; --- 开始备份
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(#39;男#39;),
--默认男
col4_default datetime not null default(getdate()),
--默认得到系统时间
col5_checkintnot null check(col5_checkgt;=18 and col5_checklt;=55), --添加约束,数据值在18到55之间
col6_checknchar(9) not null check(col6_check like #39;msd0902[0-9][-9]#39;),
--添加约束,数据值前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 主表名 (主表中的字段名)
--其它非主外键约束
alter table wf
add constraint 约束名约束类型具体的约束说明
alter table wf--修改联合主键
add constraint Pk_cola_primary primary key(cola_primary,col1)
根据已有的表创建新表:
A:create table tab_new like tab_old (使用旧表创建新表)
B:create table tab_new as select col1,col2… from tab_old definition only
5、说明:删除新表
drop table tabname
6、说明:增加一个列
Alter table tabname add column col type
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加
7、说明:添加主键: Alter table
显示全部