PL/SQL Function

- 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.

Syntax for Creating Functions

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 等使用 )

例子 :

image

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.

Executing Functions ( 执行 Function )

image

Function 好处

- 扩展了 SQL , 比如某个地方过于复杂的 SQL , 使用一个 function 代替

- 编译好后,每次执行,效率提高

- 增加了 数据独立性,只要知道执行函数就可以了,不必知道内部接口

调用 Function

image

Locations to Call User-Defined Functions

- 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

1: SELECT employee_id, tax(salary) 2: FROM employees 3: WHERE tax( salary ) > ( SELECT MAX( tax(salary)) 4: FROM employees WHERE departmentd_id = 30 ) 5: ORDER BY tax( salary ) DESC ;

Only stored functions are called from SQL statements. Stored procedures cannot be called.

Function 限制

  • When called from a SELECT statement or a parallelized UPDATE or DELETE statement, the function cannot modify any database tables
  • When called from an UPDATE, or DELETE statement, the function cannot query or modify any database tables modified by that statement.
  • When called from a SELECT, INSERT, UPDATE, or DELETE statement, the function cannot execute SQL transaction control statements( such as COMMIT ), session control statements ( such as SET ROLE ), or system control statement ( such as ALTER SYSTEM ), Also, it cannot execute DDL statements( such as CREATE) because they are followed by an automatic commit.
  • The function cannot call another subprogram that breaks one of the above restrictions.

Removing Functions

DROP FUNCTION function_name

例如 : DROP FUNCTION get_sal;

( The CREATE OR REPLACE ) syntax is equivalent to dropping a function and recreating it. ( 权限保留 )

你可能感兴趣的:(function)