xielong

Oracle的创建表和创建约束的Sql语法

1、创建表的语句

 ---1、创建模拟的数据表 ---
  --1.1.创建学生表Student
  create table Student(
         StuId NUMBER NOT NULL,     --学生ID
         StuName VARCHAR2(10) NOT NULL, --名称
         Gender VARCHAR2(10)NOT NULL,  -- 性别
         Age NUMBER(2) NOT NULL,    -- 年龄     
         JoinDate DATE NULL,       --入学时间
         ClassId NUMBER NOT NULL,   --班级ID
         Address VARCHAR2(50) NULL   --家庭住址           
  ); 
  --1.2、创建班级表StuClass 
  create table StuClass(
       classId NUMBER not null,     -- 班级ID
       ClassName varchar2(20) not null,  --班级名称
       Notes varchar2(50) null default\'班级信息\',  --备注,默认班级信息
  ); 

2、创建约束的语句

  ----2、创建数据表的约束---
  --2.1)创建主键约束--
  alter table Student add constraint PK_Student_StuId primary key(StuId);
  alter table StuClass add constraint PK_StuClass_ClassId primary key(ClassId);
--2.2) 创建检查约束-- alter table Student add constraint CK_Student_Gender check(gender=\'\' or gender=\'\'); alter table Student add constraint CK_Student_Age check(Age>=0 and Age<=100);
--2.3)创建唯一约束-- alter table Student add constraint UQ_Student_StuName unique(StuName);
--2.4)创建默认约束-- --alter table Student add constraint DF_Student_Address default(\'地址不详\'); alter table Student Modify Address varchar(50) default \'地址不详\'; alter table Student Modify JoinDate Date default sysdate;
--2.5)创建外键约束-- alter table Student add constraint FK_Student_StuCLass_ClassId foreign key(ClassId) references StuClass(ClassId);

注意:创建表还是约束,与SQL Server基本相同,注意:在Oracle中default是一个值,而SQL Server中default是一个约束,

因此Oracle的default设置可以在建表的时候创建或者通过Modify函数创建

3、添加模拟的数据

  --3、添加模拟的数据--
  --3.1)添加班级信息
  insert into StuClass(ClassId,Classname) values(1,\'一班\');
  insert into StuClass(ClassId,Classname) values(2,\'二班\');
  insert into StuClass(ClassId,Classname) values(3,\'三班\');
   --3.2)添加学生信息
  insert into Student(StuId,Stuname,Gender,Age,ClassId)
  values(1,\'关羽\',\'\',17,1);
  insert into Student(StuId,Stuname,Gender,Age,ClassId)
  values(2,\'张飞\',\'\',16,2);
   insert into Student(StuId,Stuname,Gender,Age,ClassId)
  values(3,\'刘备\',\'\',18,3);

4、查询模拟数据

select * from Student;
select * from StuClass;

4.1)查询学生表信息

4.2)查询班级表信息

5、验证数据表约束

5.1)验证Student表的StuName是否唯一(唯一约束)

--插入相同名称--
insert into Student(StuId,Stuname,Gender,Age,ClassId)
  values(5,\'关羽\',\'\',18,1);

结果是

5.2)验证Student表Gender的检查约束

  --添加性别为未知的数据--
  insert into Student(StuId,Stuname,Gender,Age,ClassId)
  values(4,\'曹操\',\'未知\',18,1);

结果是

其它就不一样验证了

分类:

技术点:

相关文章: