我有以下简单的功能,我试图使用动态查询的简单功能 即sqlstatement(虽然在这个例子中我提到了简单的查询)
create or replace
FUNCTION test_simple_func ( testVal IN VARCHAR2)
RETURN number IS
total number(2) := 0;
DECLARE @sqlstatement VARCHAR(MAX);
BEGIN
SET @sqlstatement = 'Select * from employee';
select count(*) INTO total from employee;
RETURN total;
END;
我在这里没有弄错?
答案 0 :(得分:2)
这是在Oracle版本中:
CREATE OR REPLACE FUNCTION test_simple_func(
testVal IN VARCHAR2)
RETURN NUMBER
AS
total NUMBER;
sqlstatement VARCHAR2(4000);
BEGIN
sqlstatement := 'Select * from employee';
SELECT COUNT(*)
INTO total
FROM employee;
RETURN total;
END;
如果您想用作动态查询,那么您需要使用EXECUTE immediate
比如EXECUTE immediate sqlstatement
答案 1 :(得分:1)
与varchar限制为4000的SQL不同,PL / SQL的限制大约是32K
否则,PL / SQL函数中没有声明。 DECLARE用于Oracle中的匿名集团。
正确的合成器是
CREATE OR REPLACE
FUNCTION test_simple_func ( testVal IN VARCHAR2)
RETURN number IS
total number(2) := 0;
sqlstatement VARCHAR(32000);
BEGIN
sqlstatement := 'Select * from employee';
select count(*) INTO total from employee;
RETURN total;
END;
答案 2 :(得分:0)
declare
块应该在所有声明之前开始:
create or replace
FUNCTION test_simple_func ( testVal IN VARCHAR2)
RETURN number IS
DECLARE -- right place for declare
total number(2) := 0;
sqlstatement VARCHAR(4000);
BEGIN
SET sqlstatement = 'Select * from employee';
select count(*) INTO total from employee;
RETURN total;
END;
答案 3 :(得分:0)
根据我的记忆,Oracle不支持VARCHAR(MAX)
答案 4 :(得分:0)
这是执行动态查询的正确方法
CREATE OR REPLACE FUNCTION test_simple_func(
testVal IN VARCHAR2)
RETURN NUMBER
IS
total NUMBER(10) := 0;
sqlstatement CLOB;
BEGIN
sqlstatement := 'Select count(*) from employee';
--select count(*) INTO total from employee;
EXECUTE immediate sqlstatement INTO total;
RETURN total;
END;