Chinaunix首页 | 论坛 | 博客
  • 博客访问: 752421
  • 博文数量: 128
  • 博客积分: 7079
  • 博客等级: 少将
  • 技术积分: 1326
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-16 08:53
文章分类

全部博文(128)

文章存档

2011年(3)

2010年(12)

2009年(9)

2008年(23)

2007年(61)

2006年(20)

我的朋友

分类: 数据库开发技术

2006-10-25 09:58:36

SQL -- 表的操作

1.表的创建
Create Table table_name
(
  column_name1 data_type [Null | Not Null] [Primary | Unique]
       [Foreign Key [(column_name)]]
       [References ref_table [(ref_column)]
  [column_name2 data_type ...]
)

各参数含义如下:
table_name 要创建的表的名称;
column_name1 第一个字段名称
data_type 指定字段的数据类型

(1)基本用法
如,在test数据库创建一个clients表,SQL语句如下:

Use test 
Create Table clients(
 cid int,
 cname char(8),
 address char(50)
)

提示:Use语句只要在第一次使用即可,后续的SQL语句都是作用在该数据库中,若要使用其它数据库,才需要再次执行Use语句
(2)段属性参数
常用的属性参数如下:
Null 和 Not Null 限制字段可以为Null(空),或者不能为Null
Primary Key 设置字段为主键
Unique 指定字段的惟一性

如,在test数据库中建立一个book表,指定bid为主键,而bname为非空
Create Table book(
 bid int Primary Key,
 bname char(8) Not Null,
 authorid char(10)
)

(3)与其他表建立关联
表的字段可以参考到其他表的字段,这就需要建立两个表建立关联:
Foreign Key References ref_table(ref_column)
参数如下:
ref_table 指定要关联的表
ref_column 指定要关联的字段名称

如,先删除之前创建的book表,创建新的book表,将authorid字段关联到authors表的authorid字段

Create Table authors(
 authorid int Not Null Primary Key,
 authorname char(20),
 address char(30)
)

Create Table book(
 bid int Not Null Primary Key,
 bname char(8) Not Null,
 authorid int Foreign Key References authors(authorid)
)

提示:在创建book表时,由于将authorid字段关联到authors表,因为authors表必须先存在

另外,还可以使用Select Into 语句创建一个新表,并用Select的结果填充到该表中。
如,创建student1表,包含表sno、sname、和class 3个字段和对应的记录

Select sno,sname,class Into student1 From student

2.表的修改

Alter Table table_name
 Add [column_name data_type]
     [Primary Key | Constraint]
     [Foreign Key (Column_name)
     References ref_table(ref_column)]
 Drop [Constraint] constraint_name | Column column_name

参数含义如下:
Add :增加字段
Drop:删除限制或者字段,Constraint表示删除限制;Column表示删除字段
例如,向test数据库中向book表增加一个"price"字段

Alter Table book Add price int

3.删除关联和表
Drop Table table_name

如,要删除book表,可执行下述语句:

Drop Table book

阅读(1482) | 评论(0) | 转发(0) |
0

上一篇:CListCtrl 使用技巧

下一篇:宴会笑话

给主人留下些什么吧!~~