SQL Server 2000 (SP4)笔记整理(二):数据库表

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 pengjj 的 blog

--==========================================================--
--  作者:彭建军
--  日期:2005-06-22
--  页面:page2
--  概要:数据库表的创建、修改、删除以及默认值、check、identity
--  说明:以下示例均在[查询分析器]下进行,可配合图形界面进行测试
--==========================================================--

use master
go

--检查是否存在测试表,若存在,则删除之
if exists (select name from sysobjects where xtype = 'u' and name = 'mytesttable1')
    drop table mytesttable1
go

create table mytesttable1
(
    编号        int primary key not null identity(1,1),
    姓名        char(8),
    别名        varchar(8),
    性别        char(2) default ('男'),
    年龄        int check(年龄>0 and 年龄<100),
)on [primary]
go

--插入数据:

/*
下面的语句将不能执行,因为 [编号] 列为系统自动自增列。

insert into mytesttable1(编号,姓名,别名,性别,年龄)
    values (1,'彭建军','彭建军','男',25)
go

在当 identity_insert 设置为 off 时,不能向表 'mytesttable1' 中的标识列插入显式值。

*/

--正确的语句,方法一
insert into mytesttable1(姓名,别名,性别,年龄)
    values ('彭建军','彭建军','男',25)
go
--方法二:
insert into mytesttable1(姓名,别名,性别,年龄)
    select '老转','老转','男',30 union all
    select '钱妮','妮子','女',28
go

--查询数据(注意编号的自增性)

select * from mytesttable1
go

/*

结果集

编号          姓名       别名       性别   年龄         
----------- -------- -------- ---- -----------
1           彭建军      彭建军      男    25
2           老转        老转        男    30
3           钱妮        妮子        女    28

*/

--验证 默认值,不插入[性别]的值,则系统取默认值
insert into mytesttable1(姓名,别名,年龄)
    select '潘颖','梨窝浅笑',25
go

--查询
select * from mytesttable1 where 姓名 = '潘颖'
go

/*

结果集
编号          姓名       别名       性别   年龄         
----------- -------- -------- ---- -----------
4           潘颖       梨窝浅笑     男    25

*/

--验证 check,插入[年龄]的值超过100,则系统报错
insert into mytesttable1(姓名,别名,性别,年龄)
    select '蛋蛋','蛋蛋','女',120
go

/*

结果集

insert 语句与 column check 约束 'ck__mytesttable1__年龄__30b91d22' 冲突。该冲突发生于数据库 'master',表 'mytesttable1', column '年龄'。
语句已终止。

*/

--修改表

--增加列
alter table mytesttable1
add 备注    varchar(50)
go

--修改列定义
alter table mytesttable1
alter column 备注 varchar(100)
go

--清空表的数据

--方法一(删除的数据将记入日志)
delete from mytesttable1
go

--如果是删除特定的行,则类似于 delete from mytesttable1 where 编号 = 1

--方法二(删除的数据不记入日志,执行效率高)
truncate table mytesttable1
go

--删除表(谨慎使用!)
drop table mytesttable1
go

本文关键:SQL Server 2000 (SP4)笔记整理(二):数据库表
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top