SQL数据集
你可以利用自定义的SQL定义一个数据集,例如:
select * from EMPLOYEE
实现动态SQL
数据库数据集的SQL也支持动态参数设置,例如:
select * from EMPLOYEE where DEPT_ID=${$dept_id}
其中${}是BaskServer的表达式的定义方法
$dept_id表示使用报表中名称为dept_id的参数。
在SQL数据集中只是使用参数,但是参数的定义需要到使用这个数据集的文件对象上定义,不同的文件有不同的定义方式,具体的参数定义可以参考:
利用表达式我们可以实现更为丰富的SQL语句编写。
范例1
${
if (isEmpty($dept_id)) {
return "select * from EMPLOYEE"
} else {
return "select * from EMPLOYEE where DEPT_ID = ${$dept_id}"
}
}
范例2
${
var sql = "select * from EMPLOYEE where 1=1"
if (isNotEmpty($dept_id)) {
sql = sql + "and DEPT_ID = ${$dept_id}"
}
if (isNotEmpty($employee_id)) {
sql = sql + "and EMPLOYEE_ID = ${$employee_id}"
}
if (isNotEmpty($sex)) {
sql = sql + "and SEX = ${$sex}"
}
return sql;
}
又因为BaskServer中表达式可对一个普通值进行判断,值为null或为false皆返回false,否则返回true(类似Javascript语法),所以上面的SQL又可简写成下面的样子:
${
var sql = "select * from EMPLOYEE where 1=1"
if ($dept_id) {
sql = sql + "and DEPT_ID = ${$dept_id}"
}
if ($employee_id) {
sql = sql + "and EMPLOYEE_ID = ${$employee_id}"
}
if ($sex) {
sql = sql + "and SEX = ${$sex}"
}
return sql;
}
多行字符串拼接(v2.0.3+)
SQL 语句支持多行字符串拼接,使用 + 号连接字符串:
${
var sql = "select emp_id, emp_name, salary"
+ " from employee"
+ " where dept_id = '${$dept_id}'"
+ " order by salary desc";
return sql;
}
+号可放在字符串之前或之后,均合法。
模糊查询(LIKE)
在查询表单中对应参数控件的值前缀和值后缀各添加 %,即可在提交时自动为参数值添加通配符:
select * from employee
where employee_name like ${$employee_name}
表单控件配置:值前缀 %,值后缀 %,提交时参数值变为 %张%,实现模糊查询效果。
IN 查询(集合类型参数)
当 SQL 需要 IN 条件,且查询值来自报表参数时,参数类型必须设置为集合:
select * from employee
where dept_id in ${$deptIds}
order by salary desc
集合参数注意事项:
- 参数类型必须选择集合
- 若设置了默认值,多个值之间用英文半角逗号(
,)分隔,例如:D11,D12 - 若不设置默认值,需使用脚本判断参数是否为空:
${
var sql = "select * from employee where 1=1";
if ($deptIds) {
sql = sql + " and dept_id in ${$deptIds}";
}
if ($degrees) {
sql = sql + " and degree in ${$degrees}";
}
sql = sql + " order by salary desc";
return sql;
}
上面的sql变量的拼装时没有使用sql+="..."方式,原因是BaskServer中表达式语法不支持这种赋值写法,所以使用的是sql=sql+....。