我正在 oracle 中编写一个存储过程,我想从一开始就为变量赋值:
CREATE PROCEDURE proc
(
param1
, param2
)
AS
variable1 INT AS SELECT MAX(value) FROM table WHERE field = param1;
BEGIN
...
是否允许或者我应该在可执行块中执行它?
我正在 oracle 中编写一个存储过程,我想从一开始就为变量赋值:
CREATE PROCEDURE proc
(
param1
, param2
)
AS
variable1 INT AS SELECT MAX(value) FROM table WHERE field = param1;
BEGIN
...
是否允许或者我应该在可执行块中执行它?
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;
...
您可以使用本地函数而不是变量:
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 的值分配给它,因为只有在变量声明之后才允许声明函数。