- A function is a named PL/SQL block that returns a value.
- A function can be stored in the database as a schema object for repeated execution.
- A function is called as part of an expression.
A function is named PL/SQL block that can accept parameters and be invoked. Generally speaking, you use a function to compute a value. Functions and procedures are structured alike. A function must have a RETURN clause in the header and at least one RETURN statement in the executable section.
Function is called as part of a SQL expression or as part of a PL/SQL expression.
CREATE [OR REPLACE] FUNCTION function_name
[( parameter1[mode1] datatype1, parameter2[mode2] datatype2 …)]
RETURN datatype // 只是 datatype , 不需要指定具体,只要类型
IS | AS
PL/SQL Block; ( 必须包含一个 RETURN 语句, 只返回 1 个值 )
SHOW ERRORS (可以查看错误,同时也可以在 procedure 等使用 )
例子 :
Function 的用法 与 procedure 不同,一般不应该使用 OUT, 因为一般都是调用 Function 计算某些事情,返回一个结果。
Although the three parameter modes, IN(the default), OUT, and IN OUT, can be used with any subprogram, avoid using the OUT and IN OUT modes with functions. The purpose of a function is to accept zero or more arguments(actual parameters) and return a single value.
- 扩展了 SQL , 比如某个地方过于复杂的 SQL , 使用一个 function 代替
- 编译好后,每次执行,效率提高
- 增加了 数据独立性,只要知道执行函数就可以了,不必知道内部接口
- Select list of a SELECT command
- Condition of the WHERE and HAVING clauses
- CONNECT BY, START WITH, ORDER BY and GROUP BY clauses
- VALUES calues of the INSERT command
- SET clause of the UPDATE command
Only stored functions are called from SQL statements. Stored procedures cannot be called.
DROP FUNCTION function_name
例如 : DROP FUNCTION get_sal;
( The CREATE OR REPLACE ) syntax is equivalent to dropping a function and recreating it. ( 权限保留 )