您的位置:首页 > 职场人生

黑马程序员_手写数据表约束

2013-03-23 20:47 232 查看
-------
Windows Phone 7手机开发、.Net培训、期待与您交流! -------

前段时间学完sql,也知道了很多关于数据库的一些基本操作。如:手写代码建数据库、建表、表的约束等

下面我学习过程中自己做的笔记,通过手写代码来演示下建表、给表添加约束并给表中添加数据

--创建一个T_Person表

create table T_Person(

dId int,

dName nvarchar(10),

dAge int,

dGender nvarchar(1)

)

go

--给字段dId设置非空约束

alter table T_Person

alter column dId int not null

go

--给字段dId添加主键约束,在我们添加主键约束之前,必须先添加非空约束

alter table T_Person

add constraint PK_Person primary key(dId)

go

--给字段dName添加唯一约束

alter table T_Person

add constraint UQ_Person unique(dName)

go

--给字段dAge添加默认约束

alter table T_Person

add constraint DE_Person default(2) for dAge

go

--给字段dGender添加Check约束

alter table T_Person

add constraint CK_Person check(dGender='男')

go

--给创建的表中插入数据(一次插入多条数据)

--dId int,dName nvarchar(10),dAge int,dGender nvarchar(1)

insert into T_Person

select 1,'aom',11,'男' union all

select 2,'bom',12,'男' union all

select 3,'com',13,'男' union all

select 4,'dom',14,'男' union all

select 5,'eom',15,'男' union all

select 6,'fom',16,'男' union all

select 7,'gom',17,'男' union all

select 8,'hom',18,'男' union all

select 9,'iom',19,'男' union all

select 10,'jom',20,'男'

go

--将现有数据插入到一个新表中(新表不能存在)

select * into Person_temp from T_Person

go

select * from Person_temp --查询表中数据

delete from Person_temp --删除表中数据

truncate table Person_temp --初始化表

--将现有数据复制到一个已存在的表中

insert into Person_temp

select * from T_Person

-------
Windows Phone 7手机开发、.Net培训、期待与您交流! -------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: