首页 > 学院 > 开发设计 > 正文

数据库SQL语言语法总结1---表操作

2019-11-08 20:53:14
字体:
来源:转载
供稿:网友

一:创建表结构

create table <表名> (<列名><数据类型>[列级完整性约束条件][,<列名><数据类型>[列级完整性约束条件]]….[,<表级完整性约束条件>])

其中约束条件包括not null —–非空unique—–唯一(当一个表的其中一个属性被设置为unique时,插入两个此属性相同的记录时,第二个插入操作会被拒绝,以此来保证此属性列在各记录上的分量上唯一),PRimary key——–将一个属性列设置为主码primary key等同于 not null + unique

下面结合几个例子帮助各位看官深入理解一下创建过程: 例1:创建一个customer表,包含customer _name(存储字长为20个char长度),customer _street(存储字长为30个char长度),customer _city(存储字长为30个char长度)这三个属性列, 其中customer _name为非空,customer _street必须是唯一的,且规定customer _name是这个表的主码 create table customer( customer_name char(20) not null customer_street char(30) unique customer_city char(30), primary key (customer _name));

例2:创建一个branch表,包括branch_name(存储字长为15个char长度且为非空),branch _city(存储字长为30个char长度), assets(小数)三个属性列,其中branch _name是主码 create table branch( branch_name char(15) not null, branch_city char(30), assets decimal, primary key(branch _name), check(assets >=0);) 最后一行语句是检查约束语句,检查assets>=0。当对数据库执行插入操作时,如assets这一列输入的值<0则会被数据库报错以此来保证assets>=0

例3:创建一个account表,其中包括account_number(存储字长为10个char长度且非空且为主码),branch _name(存储字长为15个char长度且为外码,此属性列在branch表中为主码),balance(存储为int且>=0)三个属性列 create table account( account_number char(10) not null, branch_name char(15), balance int, primary key(account_number), foreign key(branch_name), reference branch(branch_name), check(balance>=0));

例4:创建一个deposit表,包括customer_name(存储字长为20个char长度且非空且为外码,参照于customer表中的customer _name属性列),account _number(存储字长为10个char长度且非空且为外码,参照于account表中的account _number属性列)这两个属性列,其中customer _name和account _number共同作为deposit表的主码 create table deposit( customer_name char(20) not null, account_number char(10) not null, primary key(customer_name,account _number), foreign key(customer_name) reference customer (customer _name), foreign key(account _number) reference account(account _number));

二:更新表结构

alter table <表名> [add <新列名><数据类型>[列级完整性约束条件]] [drop <列名><完整性约束条件>] [modify <列名><数据类型>];

举例: 如数据库中觉得Sage使用int来存储太浪费了,需要把存储字长改小一点:alter table Student modify Sage,small int 如需要删除Sname这一属性:alter table Student drop Sname 如需要增加Scome Date 这一属性:alter table Student add Scome Date

三:整表删除

drop table <表名> 如:删除Student表 :drop table Studnent


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表