改写条件中的or,原始sql如下,改sql会传入一个参数,select t1.* from t1, t2
where t1.id = t2.fid
and (t1.name = ? or t1.fname = ?)想改成,如果有t1.fname 等于传入进来的参数,则使用 t1.fname = ? 做为条件,不使用t1.name = ?做为条件。
如果没有t1.fname 等于传入进来的参数,那么就使用t1.name = ?做为条件。
这个sql该如何改写呢?id name fname
1 n1 n5
2 n2 n1
3 n3 n6
4 n4 n7例如输入的是n1,则查询出来的结果是 id = 2的记录(原来sql会把id=1 和 id = 2的记录都查询出来)。
如果输入的是 n3,则查询出来的是id = 3的记录。
where t1.id = t2.fid
and (t1.name = ? or t1.fname = ?)想改成,如果有t1.fname 等于传入进来的参数,则使用 t1.fname = ? 做为条件,不使用t1.name = ?做为条件。
如果没有t1.fname 等于传入进来的参数,那么就使用t1.name = ?做为条件。
这个sql该如何改写呢?id name fname
1 n1 n5
2 n2 n1
3 n3 n6
4 n4 n7例如输入的是n1,则查询出来的结果是 id = 2的记录(原来sql会把id=1 和 id = 2的记录都查询出来)。
如果输入的是 n3,则查询出来的是id = 3的记录。
str_sql = "select t1.* from t1, t2 where t1.id = t2.fid and ";
if (str_name!=null)
str_sql = str_sql + "t1.name = '"+str_name+"'";
else if (str_fname!=null)
str_sql = str_sql + "t1.fname = '"+str_fname+"'";2、在前台程序代码中判断,根据相应字段是否输入值生成不同SQL语句。
if (str_name==null){
str_sql ="select t1.* from t1, t2 where t1.id = t2.fid and t1.name = ?";
}
else if (str_fname==null){
str_sql ="select t1.* from t1, t2 where t1.id = t2.fid and t1.fname = ?";
}
问题中不是根据输入的参数是否有值来查询的。而是根据输入的参数跟表中哪个字段的值是相等的,来确定使用哪个字段来做为查询条件的。
类似:
定义一个变量 i = select count(*) from t1, t2
where t1.id = t2.fid
and t1.fname = ?if(i > 0) then
查询的sql为:select t1.* from t1, t2
where t1.id = t2.fid
and t1.fname = ?
else
查询的sql为:
select t1.* from t1, t2
where t1.id = t2.fid
and t1.name = ?
select t1.* from t1, t2
where t1.id = t2.fid
and t1.fname = ?
查询返回的结果是不是空,就把结果赋给你相应的对象,空的话再执行第二个sql
begin
for rec in(select type from A)
loop
insert into B(id,type)
select level,regexp_substr(rec.type,'[^,]+',1,level)
from dual
connect by level <= length(rec.type)-length(replace(rec.type,',',''));
end loop;
commit;
end;---
--例如,例子如此剩下的靠你自己了。[SYS@orcl] SQL>select level, regexp_substr('aaa,bds,asd,234er,er,rfgfg,dsdf','[^,]+',1,level)
2 from dual
3 connect by level <= length('aaa,bds,asd,234er,er,rfgfg,dsdf')-length(replace('aaa,bds,asd,234er,er,rfgfg,dsdf',',','')); LEVEL REGEXP_SUBSTR('AAA,BDS,ASD,234ER,ER,RFGFG,DSDF','[^,]+',1,LEVE
---------- --------------------------------------------------------------
1 aaa
2 bds
3 asd
4 234er
5 er
6 rfgfg已选择6行。