关于proc SQL 中添加约束的几点心得
1、proc sql 中主要支持的约束
(1)主键约束(primary key);
(2)唯一性约束(unique);
(3)检查约束(check);
(4)非空约束(not null);
(5)外键约束(foreign key)。
tips:默认约束此处并不支持!!!
2、创建约束的两种情况及两种方法
1、建表时创建-列级约束
proc sql;
create table example1(
id num primary key,
name char(8) not null,
gender char(2) check(gender='男' or gender='女'),
age num not null,
works char(20) label='代表作' unique);
quit;
以上代码中,为各个字段分别创建了列举约束,而外键约束一般使用表级进行添加。
2、建表时创建-表级约束
proc sql;
create table example2(
id2 num,
name2 char(8),
gender2 char(2),
age2 num,
works2 char(20),
constraint fk foreign key(id2) references example1(id),
/*这里建立了外键约束,example2是从表,example2是主表,两表建立联系的
列(id,di2)类型应当一致或兼容,但名称可以不一样*/
constraint nt not null(name2),
constraint nt1 not null(age2),
constraint uq unique(works2));
quit;
3、修改表时创建约束-列级
proc sql;
alter table example2
add unique(works2);
quit;
4、修改表时创建约束-表级(一般用此方法创建外键约束)
proc sql;
alter table example2
add constraint fk_id2_example2 foreign key(id2) references
example1(id);
quit;
5、删除约束
prco sql;
alter table example2
drop constirant fk_id2_example2;
/*语法格式:drop constraint <约束名称>
quit;
总结:两种时机创建约束:建表时,改表时;两种方法创建约束:列级约束,表级约束。一般约束可以在建表时使用列级约束方式,外键约束建表时使用表级约束方式创建;改表时在关键字alter下使用add关键字,然后直接使用“表级约束”形式进行约束添加。
3、外键的特点
1、要求在从表(子表,“更小的表”)设置;
2、从表的外键列的类型和主表中的关联列类型一致或兼容;
3、主表的关联列必须是一个key(一般为主键或唯一键);
4、插入数据时应先插入主表,再插入从表;
5、删除数据时,先删从表,再删主表。



雷达卡




京公网安备 11010802022788号







