我正在oracle中编写存储过程,我想从一开始就为变量赋值:
CREATE PROCEDURE proc
(
param1
, param2
)
AS
variable1 INT AS SELECT MAX(value) FROM table WHERE field = param1;
BEGIN
...
是否允许或应该在可执行块中执行此操作?
答案 0 :(得分:4)
Oracle将查询值分配给这样的变量......
SELECT MAX(value) INTO variable1 FROM table WHERE field = param1;
...因为它确实无法将变量初始化为声明块中的查询值。它必须位于执行和/或异常块中:
CREATE PROCEDURE proc
(
param1; -- don't forget the data type here!
, param2; -- or here!
)
AS
variable1 INT;
BEGIN
SELECT MAX(value) INTO variable1 FROM table WHERE field = param1;
...
答案 1 :(得分:2)
您可以使用本地函数而不是变量:
create or replace procedure proc(param1 in varchar2) as
function max_val return number is
l_result number;
begin
select max(value)
into l_result
from t1
where field = param1;
return l_result;
end;
begin
dbms_output.put_line('max val for ' || param1 || ': ' || max_val);
end;
不幸的是,你不能声明一个局部变量并为其赋值max_val,因为只有在声明变量之后才允许声明函数。