在设计表时,一些列用于很简单且数据量很少的信息,比如各级角色名,几个部门id等等,如果不愿意多建个表,除了直接用一个varchar2字段来存储用","分割的字符串,有个更好的办法:用varray(可变长度数据类型)类型的字段。
create or replace type INTARRAY AS VARRAY (200) OF INTEGER
create table t1 ( id integer, name varchar2(64), allowed_deps intarray);
insert into t1 values(1,’aaaa’, intarray(0,1,2,3,4));
选择t1表allowed_deps字段含有1的记录:
Select * from t1 where 1 in (select * from table(allowed_deps));
选择allowed_deps字段含有1或者2的记录:
Select * from t1 where exists (select * from table(allowed_deps) where column_value=1 or column_value=2);
选择allowed_deps字段同时含有1、2、3的记录:
Select * from t1 where NOT exists ((select * from table(intarray(1,2,3))) minus (select * from table(allowed_deps)));
不可以单独修改varray 类型中的单个元素,但nested table类型的可以。
用jdbc访问:
ResultSet rs = 。。。;
Array arr = rs.getArray(1);
BigDecimal[] dids = (BigDecimal[])arr.getArray();
设置:
Integer[] ids=new Integer(){1,2,3};
Connection conn=getConnection();
//DatabaseError.throwUnsupportedFeatureSqlException(): Array arr = conn.createArrayOf("INTARRAY", ints); jdbc driver version11.2.0.1.0尚不支持
OracleConnection oconn = (OracleConnection)conn.unwrap(OracleConnection.class); //jboss4.2.3. 在tomcat6,需OracleConnection oconn = (OracleConnection)((DelegatingConnection) conn).getInnermostDelegate(); dataSource配置加accessToUnderlyingConnectionAllowed="true"后重启tomcat
Array arr = oconn.createARRAY("INTARRAY", ids);
pst.setArray(1, arr);