您的位置:首页 > 数据库

拼接查询条件为list集合的sql函数

2017-08-30 23:42 323 查看
当deptId 为1时 sql语句不做更改

当deptId 为其他数字时 list中的id项作为sql查询条件

刚开始编写的时候思路是用or语句进行循环遍历 重复加上or的sql语句来查询

发现比较复杂 最后采取了sql的in函数来实现

public String getDeptIdSql(List<Long> deptIdList){
Iterator<Long> it = deptIdList.iterator();
//当部门id为1时  不采用筛选
while(it.hasNext()){
Long deptId = it.next();
if(deptId == 1){
return "";
}
}
//拼接in条件语句
String s = "";
for(int i = 0; i < deptIdList.size();i++){
if(i!=(deptIdList.size()-1)){
s += deptIdList.get(i) + ",";
}else{
s += deptIdList.get(i);
}
}
String sql = " and mtMaintenanceStandard.dept_Id in (" + s + ") ";
return sql;
}


编写完成后发现函数有可以提高函数的复用性,将mtMaintenanceStandard.dept_Id设为传入的变量

最后得到

public String getDeptIdSql(String condition,List<Long> deptIdList){
Iterator<Long> it = deptIdList.iterator();
//当部门id为1时  不采用筛选
while(it.hasNext()){
Long deptId = it.next();
if(deptId == 1){
return "";
}
}
//拼接in条件语句
String s = "";
for(int i = 0; i < deptIdList.size();i++){
if(i!=(deptIdList.size()-1)){
s += deptIdList.get(i) + ",";
}else{
s += deptIdList.get(i);
}
}
String sql = " and " + condition + " in (" + s + ") ";
return sql;
}


更为通用的版本是不用判断deptId是否为1

public String getDeptIdSql(String condition,List<Long> deptIdList){
String s = "";
for(int i = 0; i < deptIdList.size();i++){
if(i!=(deptIdList.size()-1)){
s += deptIdList.get(i) + ",";
}else{
s += deptIdList.get(i);
}
}
String sql = " and " + condition + " in (" + s + ") ";
return sql;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数 sql 遍历