【问题标题】:PL/SQL Oracle Query With IF Statement带有 IF 语句的 PL/SQL Oracle 查询
【发布时间】:2013-04-11 11:59:11
【问题描述】:

我想实现一个只返回登录用户并只显示那里记录的查询,我做了如下并且它有效:

SELECT * FROM EMPLOYEE
WHERE UPPER(username) = v('APP_USER')

但是,我有另一个名为 User_Type 的列,用户可以是类型 1、2 或 3。如果我的用户类型为 1,我希望查询也返回所有表记录,因为用户类型 1 是管理员。

我想过这样做:

BEGIN
SELECT * FROM Employee 
WHERE upper(username) = v('APP_USER')
IF User_Type = 1
THEN SELECT * FROM Employee
END IF;
END;
/

但它在 APEX Oracle PLSQL 中不起作用。

有什么建议吗?

【问题讨论】:

    标签: sql oracle if-statement plsql oracle-apex


    【解决方案1】:

    据我了解,您需要试试这个:

    DECLARE
      emp employee%ROWTYPE; -- Create a record type
      tbl_emp IS TABLE OF emp;
      -- ^^^ Create a table of that record type
      v_user_type employee.user_type%TYPE;
      -- ^^^ Variable to store user type
    BEGIN
      SELECT user_type
        INTO v_user_type
        FROM Employee 
       WHERE upper(username) = v('APP_USER');
    
      IF v_user_type = 1 THEN
        SELECT *
               BULK COLLECT INTO tbl_emp
          FROM employee;
        -- ^^ Returns the entire table
      ELSE
        SELECT *
               BULK COLLECT INTO tbl_emp
          FROM employee;
         WHERE upper(username) = v('APP_USER');
        -- ^^ Returns the row related to the user.
      END IF;
    END;
    /
    

    输出存储在嵌套表变量tbl_emp中。

    编辑:

    也可以使用纯SQL来实现,像这样:

    SELECT *
      FROM employee e
     WHERE EXISTS (SELECT 1
                     FROM employees e_in
                    WHERE e_in.user_type = 1
                      AND UPPER(e_in.username) = v('APP_USER'))
        OR UPPER(e.username) = v('APP_USER')
    

    选择最适合您的。

    【讨论】:

      【解决方案2】:

      您想要来自用户的所有记录,其中UPPER(username)v('APP_USER')User_Type 为1?然后就用OR:

      SELECT * FROM Employee WHERE upper(username) = v('APP_USER') OR User_Type = 1
      

      如果这不是你的意思,那你能解释清楚点吗?

      【讨论】:

      • 仅使用 app_user 时,仅返回该用户名记录,除非该用户的用户类型为“1”,然后返回整个表。
      • 我不明白。可能有很多记录满足upper(username) = v('APP_USER')
      【解决方案3】:

      试试:

      select distinct e2.*
      from employee e1
      join employee e2 on (e1.username = e2.username or e1.User_Type = 1)
      where UPPER(e1.username) = v('APP_USER')
      

      【讨论】:

      • 非常容易理解和紧凑,但我只是有点担心性能,因为我是一个大 distinctphobic。您能解释一下对性能的影响吗?
      • 如果有多个员工记录满足UPPER(e1.username) = v('APP_USER') 条件,则包含distinct - 如果这种情况永远不会发生,则可以删除distinct。在查询一个相当大的表(例如几十万条记录)时,它可能会对性能产生重大影响,但员工表通常相对较小,因此性能影响可能相对较小。
      猜你喜欢
      • 2018-06-27
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多