我正在将用Java代码编写的查询移动到过程中。在场景中,根据条件的满足,查询的一部分将附加在相同的内容中。我如何在PL / SQL中的存储过程中实现相同的功能?
示例:
String query = "select * from employee where employee_id =5";
if(true)//some condition
query.append(" AND first_name ='pankaj'");
结果应该是:
query= "select * from employee where employee_id =5 AND first_name ='pankaj'"
答案 0 :(得分:1)
为此,您应该使用execute immediate,它允许您动态创建查询字符串然后执行它。以下是此命令文档的链接 - https://docs.oracle.com/cd/B19306_01/appdev.102/b14261/executeimmediate_statement.htm
答案 1 :(得分:1)
您可以在没有动态SQL的情况下执行此操作:
CREATE OR REPLACE PROCEDURE getEmployees(
in_useWhere IN NUMBER,
out_cursor OUT SYS_REFCURSOR
)
AS
BEGIN
OPEN out_cursor FOR
SELECT * FROM EMPLOYEES
WHERE employee_id = 5
AND ( in_useWhere = 0 OR firstname = 'pankaj' );
END;
/
SHOW ERRORS;
或者,如果您想指定employee_id
和(可选)first_name
来获取:
CREATE OR REPLACE PROCEDURE getEmployees(
in_employee_id IN EMPLOYEES.EMPLOYEE_ID%TYPE,
in_firstName IN EMPLOYEES.FIRST_NAME%TYPE,
out_cursor OUT SYS_REFCURSOR
)
AS
BEGIN
OPEN out_cursor FOR
SELECT * FROM EMPLOYEES
WHERE employee_id = in_employee_id
AND ( in_firstName IS NULL OR first_name = in_firstName );
END;
/
SHOW ERRORS;
答案 2 :(得分:0)
在PL / SQL中,字符串追加运算符为||
(两个管道符)。因此,代码的PL / SQL等价物是
DECLARE
query VARCHAR2(1000) := 'SELECT * FROM EMPLOYEE WHERE EMPLOYEE_ID = 5';
BEGIN
IF some_condition = TRUE THEN
query := query || ' AND FIRST_NAME = ''pankaj''';
END IF;
END;
祝你好运。