PL / SQL中的函数和过程有什么区别?
PL / SQL中的函数和过程有什么区别?
Answers:
过程没有返回值,而函数则具有。
例:
CREATE OR REPLACE PROCEDURE my_proc
(p_name IN VARCHAR2 := 'John') as begin ... end
CREATE OR REPLACE FUNCTION my_func
(p_name IN VARCHAR2 := 'John') return varchar2 as begin ... end
请注意,函数在参数列表和“ as”关键字之间如何具有return子句。这意味着期望函数体内的最后一条语句读取如下内容:
return(my_varchar2_local_variable);
其中my_varchar2_local_variable是该函数应返回的一些varchar2。
可以将函数内联到SQL语句中,例如
select foo
,fn_bar (foo)
from foobar
使用存储过程无法完成。查询优化器的体系结构限制了在此上下文中可以使用函数执行的操作,要求它们是纯函数(即,相同的输入始终会产生相同的输出)。这限制了在函数中可以执行的操作,但是如果将其定义为“纯”,则允许在查询中内联使用它。
否则,函数(不一定是确定性的)可以返回变量或结果集。如果函数返回结果集,则可以将其与查询中的其他选择结合起来。但是,您不能在相关子查询中使用像这样的非确定性函数,因为优化器无法预测将返回哪种结果集(这在计算上很棘手,就像暂停问题一样)。
它以完全简单的方式表达了这个意思。
职能 :
这些子程序返回一个值; 主要用于计算和返回值。
程序:
这些子程序不会直接返回值。主要用于执行动作。
示例程序:
CREATE OR REPLACE PROCEDURE greetings
BEGIN
dbms_output.put_line('Hello World!');
END ;
/
执行独立程序:
一个独立的过程可以通过两种方式调用:
•使用EXECUTE
关键字•从PL / SQL块中调用过程名称
也可以从另一个PL / SQL块中调用该过程:
BEGIN
greetings;
END;
/
功能:
CREATE OR REPLACE FUNCTION totalEmployees
RETURN number IS
total number(3) := 0;
BEGIN
SELECT count(*) into total
FROM employees;
RETURN total;
END;
/
接下来的程序totalCustomers
从另一个块调用该函数
DECLARE
c number(3);
BEGIN
c := totalEmployees();
dbms_output.put_line('Total no. of Employees: ' || c);
END;
/
Both stored procedures and functions are named blocks that reside in the database and can be executed as and when required.
The major differences are:
A stored procedure can optionally return values using out parameters, but can also be written in a manner without returning a value. But, a function must return a value.
A stored procedure cannot be used in a SELECT statement whereas a function can be used in a SELECT statement.
Practically speaking, I would go for a stored procedure for a specific group of requirements and a function for a common requirement that could be shared across multiple scenarios. For example: comparing between two strings, or trimming them or taking the last portion, if we have a function for that, we could globally use it for any application that we have.
The following are the major differences between procedure and function,
In the few words - function returns something. You can use function in SQL query. Procedure is part of code to do something with data but you can not invoke procedure from query, you have to run it in PL/SQL block.
This is what the difference i found. Please let me know if any .