使用PL / SQL函数主体返回SQL查询

时间:2018-11-15 16:14:54

标签: sql oracle plsql oracle-apex

我正在使用Oracle APEX,并且试图将动态SQL查询存储在PL / SQL Function主体中。这是我当前对经典报告的SQL查询:

SELECT 
    RELEASE,
    COUNT(*) as "Total Tests", --total
    SUM(CASE WHEN TYPE = 'P1' THEN 1 ELSE 0 END) as "P1",
    SUM(CASE WHEN TYPE = 'P2' THEN 1 ELSE 0 END) as "P2",
    SUM(CASE WHEN TYPE = 'P3' THEN 1 ELSE 0 END) as "P3",
    SUM(CASE WHEN TYPE = 'P4' THEN 1 ELSE 0 END) as "P4"
    FROM TABLENAME
group by RELEASE
ORDER BY case
    when RELEASE = '19.3' then 1
    when RELEASE = '18.11' then 2
    when RELEASE = '18.9' then 3
    when RELEASE = '18.7' then 4
    when RELEASE = '17.3' then 5
    else 6
end asc

我正在尝试将'tablename'存储在页面项中,以便每当用户更改页面项时,此查询将自动从给定表中提取。我试图围绕它构建一个pl / sql函数,但继续遇到“字符串”错误。

有人知道如何将其转换为动态pl / sql函数吗?

谢谢。

1 个答案:

答案 0 :(得分:3)

您应该

  • 创建经典报告,其来源是返回查询的函数
  • 该查询应如下所示:

    return '
      SELECT 
        RELEASE,
        COUNT(*) as "Total Tests", --total
        SUM(CASE WHEN TYPE = ''P1'' THEN 1 ELSE 0 END) as "P1",
        SUM(CASE WHEN TYPE = ''P2'' THEN 1 ELSE 0 END) as "P2",
        SUM(CASE WHEN TYPE = ''P3'' THEN 1 ELSE 0 END) as "P3",
        SUM(CASE WHEN TYPE = ''P4'' THEN 1 ELSE 0 END) as "P4"
        FROM ' || 
        SYS.DBMS_ASSERT.sql_object_name(:P1_TABLE_NAME) ||
      ' group by RELEASE 
      ORDER BY case
        when RELEASE = ''19.3''  then 1
        when RELEASE = ''18.11'' then 2
        when RELEASE = ''18.9''  then 3
        when RELEASE = ''18.7''  then 4
        when RELEASE = ''17.3''  then 5
        else 6
      end asc';
    
  • DBMS_ASSERT在这里是为了防止SQL注入

  • 将“使用通用列名”设置为“是”
  • 页面项目的名称为:P1_TABLE_NAME(在我的示例中);它应该是一个文本字段,请按Enter键提交

仅此而已。