Show error sql

MySQL SHOW ERRORS Summary: in this tutorial, you will learn how to use the MySQL SHOW ERRORS statement to display error information generated by a query. Introduction to MySQL SHOW ERRORS statement The SHOW ERRORS is a diagnostic statement that displays information for errors. The SHOW ERRORS is similar to the SHOW WARNINGS except […]

Содержание

  1. MySQL SHOW ERRORS
  2. Introduction to MySQL SHOW ERRORS statement
  3. MySQL SHOW ERRORS statement example
  4. 10 Using Procedures and Packages
  5. PL/SQL Procedures and Packages
  6. Anonymous Blocks
  7. Database Triggers
  8. Stored Procedures and Functions
  9. Procedure Names
  10. Procedure Parameters
  11. Parameter Modes
  12. Parameter Datatypes
  13. Tables and Records
  14. Default Parameter Values
  15. DECLARE Keyword
  16. Creating Stored Procedures and Functions
  17. Privileges Required to Create Procedures and Functions
  18. Altering Stored Procedures and Functions
  19. External Procedures
  20. PL/SQL Packages
  21. Creating Packages
  22. The OR REPLACE Clause
  23. Privileges Required to Create Packages
  24. Creating Packaged Objects
  25. Local Objects
  26. Naming Packages and Package Objects
  27. Dropping Packages and Procedures
  28. Privileges Required to Drop Procedures and Packages
  29. Package Invalidations and Session State
  30. Remote Dependencies
  31. Timestamps
  32. Figure 10-1 Dependency Relationships
  33. Disadvantages of the Timestamp Model
  34. Signatures
  35. What Is a Signature?
  36. When Does a Signature Change?
  37. Examples of Signatures
  38. Controlling Remote Dependencies
  39. Dependency Resolution
  40. Suggestions for Managing Dependencies
  41. Cursor Variables
  42. Declaring and Opening Cursor Variables
  43. Examples of Cursor Variables
  44. Fetching Data
  45. Implementing Variant Records
  46. Hiding PL/SQL Code
  47. Error Handling
  48. Declaring Exceptions and Exception Handling Routines
  49. Figure 10-2 Exceptions and User-Defined Errors
  50. Unhandled Exceptions
  51. Handling Errors in Distributed Queries
  52. Handling Errors in Remote Procedures
  53. Compile Time Errors
  54. Debugging
  55. Invoking Stored Procedures
  56. A Procedure or Trigger Calling Another Procedure
  57. Interactively Invoking Procedures From Oracle Tools
  58. Calling Procedures within 3GL Applications
  59. Name Resolution When Invoking Procedures
  60. Privileges Required to Execute a Procedure
  61. Specifying Values for Procedure Arguments
  62. Invoking Remote Procedures
  63. Remote Procedure Calls and Parameter Values
  64. Referencing Remote Objects
  65. Synonyms for Procedures and Packages
  66. Calling Stored Functions from SQL Expressions
  67. Using PL/SQL Functions
  68. Syntax
  69. Naming Conventions
  70. Name Precedence
  71. Arguments
  72. Using Default Values
  73. Meeting Basic Requirements
  74. Controlling Side Effects
  75. Calling Packaged Functions
  76. Referencing Packages with an Initialization Part
  77. Avoiding Problems
  78. Overloading
  79. Serially Reusable PL/SQL Packages
  80. Package States
  81. Why Serially Reusable Packages?
  82. Syntax
  83. Semantics
  84. Example 1
  85. Example 2
  86. Example 3
  87. Privileges Required
  88. Supplied Packages
  89. Packages Supporting SQL Features
  90. Packages Supporting Additional Functionality
  91. Describing Stored Procedures
  92. DBMS_DESCRIBE Package
  93. Security
  94. Types
  95. Errors
  96. DESCRIBE_PROCEDURE Procedure
  97. Syntax
  98. Return Values
  99. Examples
  100. Listing Information about Procedures and Packages
  101. The DBMS_ROWID Package
  102. Summary
  103. Exceptions
  104. ROWID_CREATE Function
  105. Syntax
  106. Example
  107. ROWID_INFO Procedure
  108. Syntax
  109. Example
  110. ROWID_TYPE Function
  111. Syntax
  112. Example
  113. ROWID_OBJECT Function
  114. Syntax
  115. Example
  116. ROWID_RELATIVE_FNO Function
  117. Syntax
  118. Example
  119. ROWID_BLOCK_NUMBER Function
  120. Syntax
  121. Example
  122. ROWID_ROW_NUMBER Function
  123. Syntax
  124. Example
  125. ROWID_TO_ABSOLUTE_FNO Function
  126. Syntax
  127. Example
  128. ROWID_TO_EXTENDED Function
  129. Syntax
  130. Example
  131. Usage
  132. ROWID_TO_RESTRICTED Function
  133. Syntax
  134. Example
  135. ROWID_VERIFY Function
  136. Syntax
  137. Example
  138. The UTL_HTTP Package

MySQL SHOW ERRORS

Summary: in this tutorial, you will learn how to use the MySQL SHOW ERRORS statement to display error information generated by a query.

Introduction to MySQL SHOW ERRORS statement

The SHOW ERRORS is a diagnostic statement that displays information for errors.

The SHOW ERRORS is similar to the SHOW WARNINGS except that it shows only errors, not warnings and notes.

The following SHOW ERRORS displays all errors:

To limit the number of errors to return, you use the SHOW ERRORS LIMIT statement:

The LIMIT clause has the same meaning as for the SELECT statement.

To get the total number of errors, you use the following form of the SHOW ERRORS statement:

Or you can select it from the system variable @@error_count :

MySQL SHOW ERRORS statement example

This statement returns id from the products table in the sample database:

However, the products table does not have the id column.

To show the error, you use the SHOW ERRORS statement:

To get the total number of errors, you use the error_count variable:

In this tutorial, you will have learned how to use the MySQL SHOW ERRORS statement to display error information.

Источник

10
Using Procedures and Packages

This chapter discusses the procedural capabilities of Oracle, including:

If you are using Trusted Oracle, also see the Trusted Oracle documentation for additional information.

PL/SQL Procedures and Packages

PL/SQL is a modern, block-structured programming language. It provides you with a number of features that make developing powerful database applications very convenient. For example, PL/SQL provides procedural constructs, such as loops and conditional statements, that you do not find in standard SQL.

You can directly issue SQL data manipulation language (DML) statements inside PL/SQL blocks, and you can use procedures, supplied by Oracle, to perform data definition language (DDL) statements.

PL/SQL code executes on the server, so using PL/SQL allows you to centralize significant parts of your database applications for increased maintainability and security. It also enables you to achieve a significant reduction of network overhead in client/server applications.

Some Oracle tools, such as Oracle Forms, contain a PL/SQL engine, and can execute PL/SQL locally.

You can even use PL/SQL for some database applications in place of 3GL programs that use embedded SQL or the Oracle Call Interface (OCI).

There are several kinds of PL/SQL program units:

  • anonymous PL/SQL blocks
  • triggers
  • stand-alone stored procedures and functions
  • packages, that can contain stored procedures and functions

For complete information about the PL/SQL language, see the PL/SQL User’s Guide and Reference .

Anonymous Blocks

An anonymous PL/SQL block consists of an optional declarative part, an executable part, and one or more optional exception handlers .

You use the declarative part to declare PL/SQL variables, exceptions, and cursors. The executable part contains PL/SQL code and SQL statements, and can contain nested blocks. Exception handlers contain code that is called when the exception is raised, either as a predefined PL/SQL exception (such as NO_DATA_FOUND or ZERO_DIVIDE ), or as an exception that you define.

The following short example of a PL/SQL anonymous block prints the names of all employees in department 20 in the EMP table, using the DBMS_OUTPUT package (described on page 12-22):

If you try this block out using SQL*Plus make sure to issue the command SET SERVEROUTPUT ON so that output using the DBMS_OUTPUT procedures such as PUT_LINE is activated. Also, terminate the example with a slash (/) to activate it.

Exceptions allow you to handle Oracle error conditions within PL/SQL program logic. This allows your application to prevent the server from issuing an error that could cause the client application to abort. The following anonymous block handles the predefined Oracle exception NO_DATA_FOUND (which would result in an ORA — 01403 error if not handled):

You can also define your own exceptions, declare them in the declaration part of a block, and define them in the exception part of the block. An example follows:

PL/SQL User’s Guide and Reference for a complete treatment of exceptions.

Anonymous blocks are most often used either interactively, from a tool such as SQL*Plus, or in a precompiler, OCI, or SQL*Module application. They are normally used to call stored procedures, or to open cursor variables.

A description of cursor variables on page 10-26.

Database Triggers

A database trigger is a special kind of PL/SQL anonymous block. You can define triggers to fire before or after SQL statements, either on a statement level or for each row that is affected. See Chapter 13, «Using Database Triggers» in this Guide for more information.

Stored Procedures and Functions

A stored procedure or function is a PL/SQL program unit that

  • has a name
  • can take parameters, and return values
  • is stored in the data dictionary
  • can be invoked by many users

The term stored procedure is sometimes used generically in this Guide to cover both stored procedures and stored functions.

Procedure Names

Since a procedure is stored in the database, it must be named, to distinguish it from other stored procedures, and to make it possible for applications to call it. Each publicly-visible procedure in a schema must have a unique name. The name must be a legal PL/SQL identifier.

If you plan to call a stored procedure using a stub generated by SQL*Module, the stored procedure name must also be a legal identifier in the calling host 3GL language such as Ada or C.

Procedure and function names that are part of packages can be overloaded. That is, you can use the same name for different subprograms as long as their formal parameters differ in number, order, or datatype family. See PL/SQL User’s Guide and Reference for more information about subprogram name overloading.

Procedure Parameters

Stored procedures and functions can take parameters. The following example shows a stored procedure that is similar to the anonymous block on page 10-3:

In the stored procedure example, the department number is an input parameter, which is used when the parameterized cursor C1 is opened.

The formal parameters of a procedure have three major parts:

The name of the parameter, which must be a legal PL/SQL identifier.

The parameter mode, which indicates whether the parameter is an input-only parameter ( IN ), an output-only parameter ( OUT ), or is both an input and an output parameter ( IN OUT ). If the mode is not specified, IN is assumed.

datatype

The parameter datatype is a standard PL/SQL datatype.

Parameter Modes

You use parameter modes to define the behavior of formal parameters. The three parameter modes, IN (the default), OUT , and IN OUT , can be used with any subprogram. However, avoid using the OUT and IN OUT modes with functions. The purpose of a function is to take zero or more arguments and return a single value. It is poor programming practice to have a function return multiple values. Also, functions should be free from side effects , which change the values of variables not local to the subprogram.

Table 10-1 summarizes the information about parameter modes. Parameter modes are explained in detail in the PL/SQL User’s Guide and Reference .

Table 10-1 Parameter Modes

the default

must be specified

must be specified

passes values to a subprogram

returns values to the caller

passes initial values to a subprogram; returns updated values to the caller

formal parameter acts like a constant

formal parameter acts like an uninitialized variable

formal parameter acts like an initialized variable

formal parameter cannot be assigned a value

formal parameter cannot be used in an expression; must be assigned a value

formal parameter should be assigned a value

actual parameter can be a constant, initialized variable, literal, or expression

actual parameter must be a variable

actual parameter must be a variable

Parameter Datatypes

The datatype of a formal parameter consists of one of the following:

  • an unconstrained type name, such as NUMBER or VARCHAR2
  • a type that is constrained using the %TYPE or %ROWTYPE attributes

Numerically constrained types such as NUMBER(2) or VARCHAR2(20) are not allowed in a parameter list.

%TYPE and %ROWTYPE Attributes

However, you can use the type attributes %TYPE and %ROWTYPE to constrain the parameter. For example, the GET_EMP_NAMES procedure specification in «Procedure Parameters» on page 10-5 could be written as

to have the DEPT_NUM parameter take the same datatype as the DEPTNO column in the EMP table. The column and table must be available when a declaration using %TYPE (or %ROWTYPE ) is elaborated.

Using %TYPE is recommended, since if the type of the column in the table changes, it is not necessary to change the application code.

If the GET_EMP_NAMES procedure is part of a package, then you can use previously-declared public (package) variables to constrain a parameter datatype. For example:

You use the %ROWTYPE attribute to create a record that contains all the columns of the specified table. The following example defines the GET_EMP_REC procedure, which returns all the columns of the EMP table in a PL/SQL record, for the given EMPNO :

You could call this procedure from a PL/SQL block as follows:

Stored functions can also return values that are declared using %ROWTYPE . For example:

Tables and Records

You can pass PL/SQL tables as parameters to stored procedures and functions. You can also pass tables of records as parameters.

Default Parameter Values

Parameters can take default values. You use the DEFAULT keyword or the assignment operator to give a parameter a default value. For example, the specification for the GET_EMP_NAMES procedure on page 10-5 could be written as

When a parameter takes a default value, it can be omitted from the actual parameter list when you call the procedure. When you do specify the parameter value on the call, it overrides the default value.

DECLARE Keyword

Unlike in an anonymous PL/SQL block, you do not use the keyword DECLARE before the declarations of variables, cursors, and exceptions in a stored procedure. In fact, it is an error to use it.

Creating Stored Procedures and Functions

Use your normal text editor to write the procedure. At the beginning of the procedure, place the command

For example, to use the example on page 10-8, you can create a text (source) file called get_emp.sql containing the following code:

Then, using an interactive tool such as SQL*Plus, load the text file containing the procedure by entering the command

to load the procedure into the current schema from the get_emp.sql file ( .sql is the default file extension). Note the slash (/) at the end of the code. This is not part of the code; it just activates the loading of the procedure.

When developing a new procedure, it is usually much more convenient to use the CREATE OR REPLACE. PROCEDURE command. This replaces any previous version of that procedure in the same schema with the newer version, but note that this is done without warning.

You can use either the keyword IS or AS after the procedure parameter list.

Use the CREATE [ OR REPLACE ] FUNCTION . command to store functions. See the Oracle8 SQL Reference for the complete syntax of the CREATE PROCEDURE and CREATE FUNCTION commands.

Privileges Required to Create Procedures and Functions

To create a stand-alone procedure or function, or package specification or body, you must meet the following prerequisites:

    You must have the CREATE PROCEDURE system privilege to create a procedure or package in your schema, or the CREATE ANY PROCEDURE system privilege to create a procedure or package in another user’s schema.

To create without errors, that is, to compile the procedure or package successfully, requires the following additional privileges: The owner of the procedure or package must have been explicitly granted the necessary object privileges for all objects referenced within the body of the code; the owner cannot have obtained required privileges through roles.

If the privileges of a procedure’s or package’s owner change, the procedure must be reauthenticated before it is executed. If a necessary privilege to a referenced object is revoked from the owner of the procedure (or package), the procedure cannot be executed.

The EXECUTE privilege on a procedure gives a user the right to execute a procedure owned by another user. Privileged users execute the procedure under the security domain of the procedure’s owner. Therefore, users never have to be granted the privileges to the objects referenced by a procedure. This allows for more disciplined and efficient security strategies with database applications and their users. Furthermore, all procedures and packages are stored in the data dictionary (in the SYSTEM tablespace). No quota controls the amount of space available to a user who creates procedures and packages.

Altering Stored Procedures and Functions

To alter a stored procedure or stored function, you must first DROP it, using the DROP PROCEDURE or DROP FUNCTION command, then recreate it using the CREATE PROCEDURE or CREATE FUNCTION command. Alternatively, use the CREATE OR REPLACE PROCEDURE or CREATE OR REPLACE FUNCTION command, which first drops the procedure or function if it exists, then recreates it as specified.

The procedure or function is dropped without any warning.

External Procedures

A PL/SQL procedure executing on an Oracle Server can call an external procedure, written in a 3GL. The 3GL procedure executes in a separate address space from that of the Oracle Server.

For information about external procedures, see the PL/SQL User’s Guide and Reference .

PL/SQL Packages

A package is a group of PL/SQL types, objects, and stored procedures and functions. The specification part of a package declares the public types, variables, constants, and subprograms that are visible outside the immediate scope of the package. The body of a package defines the objects declared in the specification, as well as private objects that are not visible to applications outside the package.

The following example shows a package specification for a package named EMPLOYEE_MANAGEMENT . The package contains one stored function and two stored procedures.

The body for this package defines the function and the procedures:

If you want to try this example, first create the sequence number EMP_SEQUENCE . You can do this using the following SQL*Plus statement:

Creating Packages

Each part of a package is created with a different command. Create the package specification using the CREATE PACKAGE command. The CREATE PACKAGE command declares public package objects.

To create a package body, use the CREATE PACKAGE BODY command. The CREATE PACKAGE BODY command defines the procedural code of the public procedures and functions declared in the package specification. (You can also define private (or local) package procedures, functions, and variables within the package body. See «Local Objects» on page 10-15.

The OR REPLACE Clause

It is often more convenient to add the OR REPLACE clause in the CREATE PACKAGE or CREATE PACKAGE BODY commands when you are first developing your application. The effect of this option is to drop the package or the package body without warning. The CREATE commands would then be

Privileges Required to Create Packages

The privileges required to create a package specification or package body are the same as those required to create a stand-alone procedure or function; see page 10-10.

Creating Packaged Objects

The body of a package can contain

  • procedures declared in the package specification
  • functions declared in the package specification
  • definitions of cursors declared in the package specification
  • local procedures and functions, not declared in the package specification
  • local variables

Procedures, functions, cursors, and variables that are declared in the package specification are global . They can be called, or used, by external users that have execute permission for the package, or that have EXECUTE ANY PROCEDURE privileges.

When you create the package body, make sure that each procedure that you define in the body has the same parameters, by name, datatype, and mode , as the declaration in the package specification. For functions in the package body, the parameters as well as the return type must agree in name and type.

Local Objects

You can define local variables, procedures, and functions in a package body. These objects can only be accessed by other procedures and functions in the body of the same package. They are not visible to external users, regardless of the privileges they hold.

Naming Packages and Package Objects

The names of a package and all public objects in the package must be unique within a given schema. The package specification and its body must have the same name. All package constructs must have unique names within the scope of the package, unless overloading of procedure names is desired.

Dropping Packages and Procedures

A stand-alone procedure, a stand-alone function, a package body, or an entire package can be dropped using the SQL commands DROP PROCEDURE , DROP FUNCTION , DROP PACKAGE BODY , and DROP PACKAGE , respectively. A DROP PACKAGE statement drops both a package’s specification and body.

The following statement drops the OLD_SAL_RAISE procedure in your schema:

Privileges Required to Drop Procedures and Packages

To drop a procedure or package, the procedure or package must be in your schema or you must have the DROP ANY PROCEDURE privilege. An individual procedure within a package cannot be dropped; the containing package specification and body must be re-created without the procedures to be dropped.

Package Invalidations and Session State

Each session that references a package object has its own instance of the corresponding package, including persistent state for any public and private variables, cursors, and constants. If any of the session’s instantiated packages (specification or body) are subsequently invalidated and recompiled, all other dependent package instantiations (including state) for the session are lost.

For example, assume that session S instantiates packages P1 and P2, and that a procedure in package P1 calls a procedure in package P2. If P1 is invalidated and recompiled (for example, as the result of a DDL operation), the session S instantiations of both P1 and P2 are lost. In such situations, a session receives the following error the first time it attempts to use any object of an invalidated package instantiation:

The second time a session makes such a package call, the package is reinstantiated for the session without error.

Oracle has been optimized to not return this message to the session calling the package that it invalidated. Thus, in the example above, session S would receive this message the first time it called package P2 , but would not receive it when calling P1 .

In most production environments, DDL operations that can cause invalidations are usually performed during inactive working hours; therefore, this situation might not be a problem for end-user applications. However, if package specification or body invalidations are common in your system during working hours, you might want to code your applications to detect for this error when package calls are made. For example, the user-side application might reinitialize any user-side state that depends on any session’s package state (that was lost) and reissue the package call.

Remote Dependencies

Dependencies among PL/SQL library units (packages, stored procedures, and stored functions) can be handled in two ways:

Timestamps

If timestamps are used to handle dependencies among PL/SQL library units, whenever you alter a library unit or a relevant schema object all of its dependent units are marked as invalid and must be recompiled before they can be executed.

Each library unit carries a timestamp that is set by the server when the unit is created or recompiled. Figure 10-1 demonstrates this graphically. Procedures P1 and P2 call stored procedure P3. Stored procedure P3 references table T1. In this example, each of the procedures is dependent on table T1. P3 depends upon T1 directly, while P1 and P2 depend upon T1 indirectly.

Figure 10-1 Dependency Relationships

If P3 is altered, P1 and P2 are marked as invalid immediately if they are on the same server as P3. The compiled states of P1 and P2 contain records of the timestamp of P3. So if the procedure P3 is altered and recompiled, the timestamp on P3 no longer matches the value that was recorded for P3 during the compilation of P1 and P2.

If P1 and P2 are on a client system, or on another Oracle Server in a distributed environment, the timestamp information is used to mark them as invalid at runtime.

Disadvantages of the Timestamp Model

The disadvantage of this dependency model is that is unnecessarily restrictive. Recompilation of dependent objects across the network are often performed when not strictly necessary, leading to performance degradation.

Furthermore, on the client side, the timestamp model can lead to situations that block an application from running at all, if the client-side application is built using PL/SQL version 2. (Earlier releases of tools such as Oracle Forms that used PL/SQL version 1 on the client side did not use this dependency model, since PL/SQL version 1 had no support for stored procedures.)

For releases of Oracle Forms that are integrated with PL/SQL version 2 on the client side, the timestamp model can present problems. First of all, during the installation of the application, the application is rendered invalid unless the client-side PL/SQL procedures that it uses are recompiled at the client site. Also, if a client-side procedure depends on a server procedure, and the server procedure is changed or automatically recompiled, the client-side PL/SQL procedure must then be recompiled. Yet in many application environments (such as Forms runtime applications), there is no PL/SQL compiler available on the client. This blocks the application from running at all. The client application developer must then redistribute new versions of the application to all customers.

Signatures

To alleviate some of the problems with the timestamp-only dependency model, Oracle provides the additional capability of remote dependencies using signatures . The signature capability affects only remote dependencies. Local (same server) dependencies are not affected, as recompilation is always possible in this environment.

The signature of a subprogram contains information about the

  • name of the subprogram
  • base types of the parameters of the subprogram
  • modes of the parameters ( IN , OUT , IN OUT )

Only the types and modes of parameters are significant. The name of the parameter does not affect the signature.

The user has control over whether signatures or timestamps govern remote dependencies. See «Controlling Remote Dependencies» on page 10-24 for more information. If the signature dependency model is in effect, a dependency on a remote library unit causes an invalidation of the dependent unit if the dependent unit contains a call to a subprogram in the parent unit, and the signature of this subprogram has been changed in an incompatible manner.

For example, consider a procedure GET_EMP_NAME stored on a server BOSTON_SERVER . The procedure is defined as

When GET_EMP_NAME is compiled on the BOSTON_SERVER , its signature as well as its timestamp is recorded.

Now assume that on another server, in California, some PL/SQL code calls GET_EMP_NAME identifying it using a DBlink called BOSTON_SERVER , as follows:

When this California server code is compiled, the following actions take place:

  • a connection is made to the Boston server
  • the signature of GET_EMP_NAME is transferred to the California server
  • the signature is recorded in the compiled state of PRINT_ENAME

At runtime, during the remote procedure call from the California server to the Boston server, the recorded signature of GET_EMP_NAME that was saved in the compiled state of PRINT_ENAME gets sent across to the Boston server., regardless of whether there were any changes or not.

If the timestamp dependency mode is in effect, a mismatch in timestamps causes an error status to be returned to the calling procedure.

However, if the signature mode is in effect, any mismatch in timestamps is ignored, and the recorded signature of GET_EMP_NAME in the compiled state of PRINT_ENAME on the California server is compared with the current signature of GET_EMP_NAME on the Boston server. If they match, the call succeeds. If they do not match, an error status is returned to the PRINT_NAME procedure.

Note that the GET_EMP_NAME procedure on the Boston server could have been changed. Or, its timestamp could be different from that recorded in the PRINT_NAME procedure on the California server, due to, for example, the installation of a new release of the server. As long as the signature remote dependency mode is in effect on the California server, a timestamp mismatch does not cause an error when GET_EMP_NAME is called.

What Is a Signature?

A signature is associated with each compiled stored library unit. It identifies the unit using the following criteria:

  • the name of the unit, that is, the package, procedure, or function name
  • the types of each of the parameters of the subprogram
  • the modes of the parameters
  • the number of parameters
  • the type of the return value for a function

When Does a Signature Change?

Datatypes

A signature changes when you change from one class of datatype to another. Within each datatype class, there can be several types. Changing a parameter datatype from one type to another within a class does not cause the signature to change.

Table 10-2 shows the classes of types.

Table 10-2 Datatype Classes

VARCHAR2

SMALLINT

DEC Character Types:

CHARACTER

DOUBLE PRECISION Raw Types:

LONG RAW

BINARY_INTEGER

PLS_INTEGER

BOOLEAN MLS Label Type:

MLSLABEL

POSITIVE

POSITIVEN

NATURALN

Modes

Changing to or from an explicit specification of the default parameter mode IN does not change the signature of a subprogram. For example, changing

does not change the signature. Any other change of parameter mode does change the signature.

Default Parameter Values

Changing the specification of a default parameter value does not change the signature. For example, procedure P1 has the same signature in the following two examples:

An application developer who requires that callers get the new default value must recompile the called procedure, but no signature-based invalidation occurs when a default parameter value assignment is changed.

Examples of Signatures

In the GET_EMP_NAME procedure defined on page 10-5, if the procedure body is changed to

then the specification of the procedure has not changed, and so its signature has not changed.

But if the procedure specification is changed to

and the body is changed accordingly, then the signature changes, because the parameter HIRE_DATE has a different datatype.

However, if the name of that parameter changes to WHEN_HIRED , and the datatype remains VARCHAR2 , and the mode remains OUT , then the signature does not change. Changing the name of a formal parameter does not change the signature of the unit.

Consider the following example:

If the package specification is changed so that the record’s field names are changed, but the types remain the same, this does not affect the signature. For example, the following package specification has the same signature as the previous package specification example:

Changing the name of the type of a parameter does not cause a change in the signature if the type remains the same as before. For example, the following package specification for EMP_PACKAGE is the same as the first one on page 10-23:

Controlling Remote Dependencies

Whether the timestamp or the signature dependency model is in effect is controlled by the dynamic initialization parameter REMOTE_DEPENDENCIES_MODE .

  • If the initialization parameter file contains the specification

and this is not explicitly overridden dynamically, then only timestamps are used to resolve dependencies.

  • If the initialization parameter file contains the parameter specification

and this not explicitly overridden dynamically, then signatures are used to resolve dependencies.

  • You can alter the mode dynamically by using the DDL commands

to alter the dependency model for the current session, or

to alter the dependency model on a system-wide basis after startup.

If the REMOTE_DEPENDENCIES_MODE parameter is not specified, either in the INIT . ORA parameter file, or using the ALTER SESSION or ALTER SYSTEM DDL commands, TIMESTAMP is the default value. So, unless you explicitly use the REMOTE_DEPENDENCIES_MODE parameter, or the appropriate DDL command, your server is operating using the timestamp dependency model.

When you use REMOTE_DEPENDENCIES_MODE = SIGNATURE you should be aware of the following:

  • If you change the default value of a parameter of a remote procedure, the local procedure calling the remote procedure is not invalidated. If the call to the remote procedure does not supply the parameter, the default value is used. In this case, because invalidation/recompilation does not automatically occur, the old default value is used. If you wish to see the new default values, you must recompile the calling procedure manually.
  • If you add a new overloaded procedure in a package (a new procedure with the same name as an existing one), local procedures that call the remote procedure are not invalidated. If it turns out that this overloading ought to result in a rebinding of existing calls from the local procedure under the TIMESTAMP mode, this rebinding does not happen under the SIGNATURE mode, because the local procedure does not get invalidated. You must recompile the local procedure manually to achieve the new rebinding.
  • If the types of parameters of an existing packaged procedure are changed so that the new types have the same shape as the old ones, the local calling procedure is not invalidated/recompiled automatically. You must recompile the calling procedure manually to get the semantics of the new type.

Dependency Resolution

When REMOTE_DEPENDENCIES_MODE = TIMESTAMP (the default value), dependencies among library units are handled by comparing timestamps at runtime. If the timestamp of a called remote procedure does not match the timestamp of the called procedure, the calling (dependent) unit is invalidated, and must be recompiled. In this case, if there is no local PL/SQL compiler, the calling application cannot proceed.

In the timestamp dependency mode, signatures are not compared. If there is a local PL/SQL compiler, recompilation happens automatically when the calling procedure is executed.

When REMOTE_DEPENDENCIES_MODE = SIGNATURE , the recorded timestamp in the calling unit is first compared to the current timestamp in the called remote unit. If they match, then the call proceeds normally. If the timestamps do not match, then the signature of the called remote subprogram, as recorded in the calling subprogram, is compared with the current signature of the called subprogram. If they do not match, using the criteria described in the section «What Is a Signature?» on page 10-20, then an error is returned to the calling session.

Suggestions for Managing Dependencies

Oracle recommends that you follow these guidelines for setting the REMOTE_DEPENDENCIES_MODE parameter:

  • Server-side PL/SQL users can set the parameter to TIMESTAMP (or let it default to that) to get the timestamp dependency mode.
  • Server-side PL/SQL users can choose to use the signature dependency mode if they have a distributed system and wish to avoid possible unnecessary recompilations.
  • Client-side PL/SQL users should set the parameter to SIGNATURE . This allows
    • installation of new applications at client sites, without the need to recompile procedures
    • ability to upgrade the server, without encountering timestamp mismatches.
  • When using SIGNATURE mode on the server side, make sure to add new procedures to the end of the procedure (or function) declarations in a package spec. Adding a new procedure in the middle of the list of declarations can cause unnecessary invalidation and recompilation of dependent procedures.

Cursor Variables

Cursor variables are references to cursors. A cursor is a static object; a cursor variable is a pointer to a cursor. Since cursor variables are pointers, they can be passed and returned as parameters to procedures and functions. A cursor variable can also refer to («point to») different cursors in its lifetime.

Some additional advantages of cursor variables are

  • Encapsulation : queries are centralized in the stored procedure that opens the cursor variable.
  • Ease of maintenance : if you need to change the cursor, you only need to make the change in one place: the stored procedure. There is no need to change each application.
  • Convenient security : the user of the application is the username used when the application connects to the server. The user must have execute permission on the stored procedure that opens the cursor. But the user does not need to have read permission on the tables used in the query. This capability can be used to limit access to the columns in the table, as well as access to other stored procedures.

See the PL/SQL User’s Guide and Reference for a complete discussion of cursor variables.

Declaring and Opening Cursor Variables

You normally allocate memory for a cursor variable in the client application, using the appropriate ALLOCATE command. In Pro*C, you use the EXEC SQL ALLOCATE command. In the OCI, you use the Cursor Data Area.

You can also use cursor variables in applications that run entirely in a single server session. You can declare cursor variables in PL/SQL subprograms, open them, and use them as parameters for other PL/SQL subprograms.

Examples of Cursor Variables

This section includes several examples of cursor variable usage in PL/SQL. For additional cursor variable examples that use the programmatic interfaces, see the following manuals:

  • Pro*C/C++ Precompiler Programmer’s Guide
  • Programmer’s Guide to the Oracle Precompilers
  • Programmer’s Guide to the Oracle Call Interface
  • SQL*Module User’s Guide and Reference

Fetching Data

The following package defines a PL/SQL cursor variable type EMP_VAL_CV_TYPE , and two procedures. The first procedure opens the cursor variable, using a bind variable in the WHERE clause. The second procedure ( FETCH_EMP_DATA ) fetches rows from the EMP table using the cursor variable.

The following example shows how you can call the EMP_DATA package procedures from a PL/SQL block:

Implementing Variant Records

The power of cursor variables comes from their ability to point to different cursors. In the following package example, a discriminant is used to open a cursor variable to point to one of two different cursors:

You can call the OPEN_CV procedure to open the cursor variable and point it to either a query on the EMP table or on the DEPT table. How would you use this? The following PL/SQL block shows that you can fetch using the cursor variable, then use the ROWTYPE_MISMATCH predefined exception to handle either fetch:

Hiding PL/SQL Code

You can deliver your stored procedures in object code format using the PL/SQL Wrapper. Wrapping your PL/SQL code hides your application internals. To run the PL/SQL Wrapper, enter the WRAP command at your system prompt using the following syntax:

For complete instructions on using the PL/SQL Wrapper, see the PL/SQL User’s Guide and Reference .

Error Handling

Oracle allows user-defined errors in PL/SQL code to be handled so that user-specified error numbers and messages are returned to the client application. Once received, the client application can handle the error based on the user-specified error number and message returned by Oracle.

User-specified error messages are returned using the RAISE_APPLICATION_ERROR procedure:

This procedure terminates procedure execution, rolls back any effects of the procedure, and returns a user-specified error number and message (unless the error is trapped by an exception handler). ERROR_NUMBER must be in the range of -20000 to -20999. Error number -20000 should be used as a generic number for messages where it is important to relay information to the user, but having a unique error number is not required. TEXT must be a character expression, 2 Kbytes or less (longer messages are ignored). KEEP_ERROR_STACK can be TRUE , if you want to add the error to any already on the stack, or FALSE , if you want to replace the existing errors. By default, this option is FALSE .

Some of the Oracle-supplied packages, such as DBMS_OUTPUT , DBMS_DESCRIBE , and DBMS_ALERT , use application error numbers in the range -20000 to -20005. See the descriptions of these packages for more information.

The RAISE_APPLICATION_ERROR procedure is often used in exception handlers or in the logic of PL/SQL code. For example, the following exception handler selects the string for the associated user-defined error message and calls the RAISE_APPLICATION_ERROR procedure:

Several examples earlier in this chapter also demonstrate the use of the RAISE_APPLICATION_ERROR procedure. The next section has an example of passing a user-specified error number from a trigger to a procedure. For information on exception handling when calling remote procedures, see «Handling Errors in Remote Procedures» on page 10-35.

Declaring Exceptions and Exception Handling Routines

User-defined exceptions are explicitly defined and signaled within the PL/SQL block to control processing of errors specific to the application. When an exception is raised (signaled), the normal execution of the PL/SQL block stops and a routine called an exception handler is invoked. Specific exception handlers can be written to handle any internal or user-defined exception.

Application code can check for a condition that requires special attention using an IF statement. If there is an error condition, two options are available:

  • Issue a RAISE statement that names the appropriate exception. A RAISE statement stops the execution of the procedure and control passes to an exception handler (if any).
  • Call the RAISE_APPLICATION_ERROR procedure to return a user-specified error number and message.

You can also define an exception handler to handle user-specified error messages. For example, Figure 10-2 illustrates

  • an exception and associated exception handler in a procedure
  • a conditional statement that checks for an error (such as transferring funds not available) and issues a user-specified error number and message within a trigger
  • how user-specified error numbers are returned to the calling environment (in this case, a procedure) and how that application can define an exception that corresponds to the user-specified error number

Declare a user-defined exception in a procedure or package body (private exceptions) or in the specification of a package (public exceptions). Define an exception handler in the body of a procedure (stand-alone or package).

Figure 10-2 Exceptions and User-Defined Errors

Unhandled Exceptions

In database PL/SQL program units, an unhandled user-error condition or internal error condition that is not trapped by an appropriate exception handler causes the implicit rollback of the program unit. If the program unit includes a COMMIT statement before the point at which the unhandled exception is observed, the implicit rollback of the program unit can only be completed back to the previous commit.

Additionally, unhandled exceptions in database-stored PL/SQL program units propagate back to client-side applications that call the containing program unit. In such an application, only the application program unit call is rolled back (not the entire application program unit) because it is submitted to the database as a SQL statement.

If unhandled exceptions in database PL/SQL program units are propagated back to database applications, the database PL/SQL code should be modified to handle the exceptions. Your application can also trap for unhandled exceptions when calling database program units and handle such errors appropriately. For more information, see «Handling Errors in Remote Procedures» on page 10-35.

Handling Errors in Distributed Queries

You can use a trigger or stored procedure to create a distributed query. This distributed query is decomposed by the local Oracle into a corresponding number of remote queries, which are sent to the remote nodes for execution. The remote nodes execute the queries and send the results back to the local node. The local node then performs any necessary post-processing and returns the results to the user or application.

If a portion of a distributed statement fails, for example, due to an integrity constraint violation, Oracle returns error number ORA-02055 . Subsequent statements or procedure calls return error number ORA-02067 until a rollback or rollback to savepoint is issued.

You should design your application to check for any returned error messages that indicate that a portion of the distributed update has failed. If you detect a failure, you should rollback the entire transaction (or rollback to a savepoint) before allowing the application to proceed.

Handling Errors in Remote Procedures

When a procedure is executed locally or at a remote location, four types of exceptions can occur:

  • PL/SQL user-defined exceptions, which must be declared using the keyword EXCEPTION
  • PL/SQL predefined exceptions, such as NO_DATA_FOUND
  • SQL errors, such as ORA-00900 and ORA-02015
  • Application exceptions, which are generated using the RAISE_APPLICATION_ERROR () procedure

When using local procedures, all of these messages can be trapped by writing an exception handler, such as shown in the following example:

Notice that the WHEN clause requires an exception name. If the exception that is raised does not have a name, such as those generated with RAISE_APPLICATION_ERROR , one can be assigned using PRAGMA_EXCEPTION_INIT , as shown in the following example:

When calling a remote procedure, exceptions are also handled by creating a local exception handler. The remote procedure must return an error number to the local, calling procedure, which then handles the exception as shown in the previous example. Because PL/SQL user-defined exceptions always return ORA-06510 to the local procedure, these exceptions cannot be handled. All other remote exceptions can be handled in the same manner as local exceptions.

Compile Time Errors

When you use SQL*Plus to submit PL/SQL code, and the code contains errors, you receive notification that compilation errors have occurred, but no immediate indication of what the errors are. For example, if you submit a stand-alone (or stored) procedure PROC1 in the file proc1.sql as follows:

and there are one or more errors in the code, you receive a notice such as

In this case, use the SHOW ERRORS command in SQL*Plus to get a list of the errors that were found. SHOW ERRORS with no argument lists the errors from the most recent compilation. You can qualify SHOW ERRORS using the name of a procedure, function, package, or package body:

See the SQL*Plus User’s Guide and Reference for complete information about the SHOW ERRORS command.

Before issuing the SHOW ERRORS command, use the SET CHARWIDTH command to get long lines on output. The value 132 is usually a good choice:

For example, assume you want to create a simple procedure that deletes records from the employee table using SQL*Plus:

Notice that the CREATE PROCEDURE statement has two errors: the DELETE statement has an error (the ‘E’ is absent from WHERE ) and the semicolon is missing after END .

After the CREATE PROCEDURE statement is issued and an error is returned, a SHOW ERRORS statement would return the following lines:

Notice that each line and column number where errors were found is listed by the SHOW ERRORS command.

Alternatively, you can query the following data dictionary views to list errors when using any tool or application:

The error text associated with the compilation of a procedure is updated when the procedure is replaced, and deleted when the procedure is dropped.

Original source code can be retrieved from the data dictionary using the following views: ALL_SOURCE , USER_SOURCE , and DBA_SOURCE .

Oracle8 Reference for more information about these data dictionary views.

Debugging

You can debug stored procedures and triggers using the DBMS_OUTPUT supplied package. You put PUT and PUT_LINE statements in your code to output the value of variables and expressions to your terminal. See «Output from Stored Procedures and Triggers» on page 12-22 for more information about the DBMS_OUTPUT package.

A more convenient way to debug, if your platform supports it, is to use the Oracle Procedure Builder, which is part of the Oracle Developer/2000 tool set. Procedure Builder lets you execute PL/SQL procedures and triggers in a controlled debugging environment, and you can set breakpoints, list the values of variables, and perform other debugging tasks. See the Oracle Procedure Builder Developer’s Guide for more information.

Invoking Stored Procedures

Procedures can be invoked from many different environments. For example:

  • A procedure can be called within the body of another procedure or a trigger.
  • A procedure can be interactively called by a user using an Oracle tool (such as SQL*Plus)
  • A procedure can be explicitly called within an application (such as a SQL*Forms or precompiler application).
  • A stored function can be called from a SQL statement in a manner similar to calling a built-in SQL function, such as LENGTH or ROUND .

Some common examples of invoking procedures from within these environments follow. For more information, see «Calling Stored Functions from SQL Expressions» on page 10-44.

A Procedure or Trigger Calling Another Procedure

A procedure or trigger can call another stored procedure. For example, included in the body of one procedure might be the line

This line calls the SAL_RAISE procedure. EMP_ID is a variable within the context of the procedure. Note that recursive procedure calls are allowed within PL/SQL; that is, a procedure can call itself.

Interactively Invoking Procedures From Oracle Tools

A procedure can be invoked interactively from an Oracle tool such as SQL*Plus. For example, to invoke a procedure named SAL_RAISE , owned by you, you can use an anonymous PL/SQL block, as follows:

Interactive tools such as SQL*Plus require that you follow these lines with a slash (/) to execute the PL/SQL block.

An easier way to execute a block is to use the SQL*Plus command EXECUTE , which effectively wraps BEGIN and END statements around the code you enter. For example:

Some interactive tools allow session variables to be created. For example, when using SQL*Plus, the following statement creates a session variable:

Once defined, any session variable can be used for the duration of the session. For example, you might execute a function and capture the return value using a session variable:

See the SQL*Plus User’s Guide and Reference for SQL*Plus information. See your tools manual for information about performing similar operations using your development tool.

Calling Procedures within 3GL Applications

A 3GL database application such as a precompiler or OCI application can include a call to a procedure within the code of the application.

To execute a procedure within a PL/SQL block in an application, simply call the procedure. The following line within a PL/SQL block calls the FIRE_EMP procedure:

In this case, : EMPNO is a host (bind) variable within the context of the application.

To execute a procedure within the code of a precompiler application, you must use the EXEC call interface. For example, the following statement calls the FIRE_EMP procedure in the code of a precompiler application:

: EMPNO is a host (bind) variable.

For more information about calling PL/SQL procedures from within 3GL applications, see the following manuals:

Name Resolution When Invoking Procedures

References to procedures and packages are resolved according to the algorithm described in «Name Resolution in SQL Statements» on page 4-46.

Privileges Required to Execute a Procedure

If you are the owner of a stand-alone procedure or package, you can execute the stand-alone procedure or packaged procedure, or any public procedure or packaged procedure at any time, as described in the previous sections. If you want to execute a stand-alone or packaged procedure owned by another user, the following conditions apply:

  • You must have the EXECUTE privilege for the stand-alone procedure or package containing the procedure, or have the EXECUTE ANY PROCEDURE system privilege. If you are executing a remote procedure, you must have been granted the EXECUTE privilege or EXECUTE ANY PROCEDURE system privilege directly, not via a role.
  • You must include the owner’s name in the call, as in:

A stored subprogram or package executes in the privilege domain of the owner of the procedure. The owner must have been explicitly granted the necessary object privileges to all objects referenced within the body of the code.

Specifying Values for Procedure Arguments

When you invoke a procedure, specify a value or parameter for each of the procedure’s arguments. Identify the argument values using either of the following methods, or a combination of both:

  • List the values in the order the arguments appear in the procedure declaration.
  • Specify the argument names and corresponding values, in any order.

For example, these statements each call the procedure UPDATE_SAL to increase the salary of employee number 7369 by 500:

The first statement identifies the argument values by listing them in the order in which they appear in the procedure specification.

The second statement identifies the argument values by name and in an order different from that of the procedure specification. If you use argument names, you can list the arguments in any order.

The third statement identifies the argument values using a combination of these methods. If you use a combination of order and argument names, values identified in order must precede values identified by name.

If you have used the DEFAULT option to define default values for IN parameters to a subprogram (see the PL/SQL User’s Guide and Reference ), you can pass different numbers of actual parameters to the 1subprogram, accepting or overriding the default values as you please. If an actual value is not passed, the corresponding default value is used. If you want to assign a value to an argument that occurs after an omitted argument (for which the corresponding default is used), you must explicitly designate the name of the argument, as well as its value.

Invoking Remote Procedures

Invoke remote procedures using an appropriate database link and the procedure’s name. The following SQL*Plus statement executes the procedure FIRE_EMP located in the database pointed to by the local database link named NY :

For information on exception handling when calling remote procedures, see page 10-35.

Remote Procedure Calls and Parameter Values

You must explicitly pass values to all remote procedure parameters even if there are defaults. You cannot access remote package variables and constants.

Referencing Remote Objects

Remote objects can be referenced within the body of a locally defined procedure. The following procedure deletes a row from the remote employee table:

The list below explains how to properly call remote procedures, depending on the calling environment.

  • Remote procedures (stand-alone and packaged) can be called from within a procedure, OCI application, or precompiler application by specifying the remote procedure name, a database link, and the arguments for the remote procedure.
  • In the previous example, you could create a synonym for REMOTE_PROCEDURE @ DBLINK . This would enable you to call the remote procedure from an Oracle tool application, such as a SQL*Forms application, as well from within a procedure, OCI application, or precompiler application.
  • If you did not want to use a synonym, you could write a local cover procedure to call the remote procedure.

Here, LOCAL_PROCEDURE is defined as in the first item of this list.

Synonyms can be used to create location transparency for the associated remote procedures.

Unlike stored procedures, which use compile-time binding, runtime binding is used when referencing remote procedures. The user account to which you connect depends on the database link.

All calls to remotely stored procedures are assumed to perform updates; therefore, this type of referencing always requires two-phase commit of that transaction (even if the remote procedure is read-only). Furthermore, if a transaction that includes a remote procedure call is rolled back, the work done by the remote procedure is also rolled back. A procedure called remotely cannot execute a COMMIT , ROLLBACK , or SAVEPOINT statement.

A distributed update modifies data on two or more nodes. A distributed update is possible using a procedure that includes two or more remote updates that access data on different nodes. Statements in the construct are sent to the remote nodes and the execution of the construct succeeds or fails as a unit. If part of a distributed update fails and part succeeds, a rollback (of the entire transaction or to a savepoint) is required to proceed. Consider this when creating procedures that perform distributed updates.

Pay special attention when using a local procedure that calls a remote procedure. If a timestamp mismatch is found during execution of the local procedure, the remote procedure is not executed and the local procedure is invalidated.

Synonyms for Procedures and Packages

Synonyms can be created for stand-alone procedures and packages to

  • hide the identity of the name and owner of a procedure or package
  • provide location transparency for remotely stored procedures (stand-alone or within a package)

When a privileged user needs to invoke a procedure, an associated synonym can be used. Because the procedures defined within a package are not individual objects (that is, the package is the object), synonyms cannot be created for individual procedures within a package.

Calling Stored Functions from SQL Expressions

You can include user-written PL/SQL functions in SQL expressions. (You must be using PL/SQL release 2.1 or greater.) By using PL/SQL functions in SQL statements, you can do the following:

  • Increase user productivity by extending SQL. Expressiveness of the SQL statement increases where activities are too complex, too awkward, or unavailable with SQL.
  • Increase query efficiency. Functions used in the WHERE clause of a query can filter data using criteria that would otherwise have to be evaluated by the application.
  • Manipulate character strings to represent special datatypes (for example, latitude, longitude, or temperature).
  • Provide parallel query execution. If the query is parallelized, SQL statements in your PL/SQL function may be executed in parallel also (using the parallel query option).

Using PL/SQL Functions

PL/SQL functions must be created as top-level functions or declared within a package specification before they can be named within a SQL statement. Stored PL/SQL functions are used in the same manner as built-in Oracle functions (such as SUBSTR or ABS ).

PL/SQL functions can be placed wherever an Oracle function can be placed within a SQL statement; that is, wherever expressions can occur in SQL. For example, they can be called from the following:

  • the select list of the SELECT command
  • the condition of the WHERE and HAVING clause
  • the CONNECT BY , START WITH , ORDER BY , and GROUP BY clauses
  • the VALUES clause of the INSERT command
  • the SET clause of the UPDATE command

You cannot call stored PL/SQL functions from a CHECK constraint clause of a CREATE or ALTER TABLE command or use them to specify a default value for a column. These situations require an unchanging definition.

Unlike functions, which are called as part of an expression, procedures are called as statements. Therefore, PL/SQL procedures are not directly callable from SQL statements. However, functions called from a PL/SQL statement or referenced in a SQL expression can call a PL/SQL procedure.

Syntax

Use the following syntax to reference a PL/SQL function from SQL:

For example, to reference a function that you have created that is called MY_FUNC , in the MY_FUNCS_PKG package, in the SCOTT schema, and that takes two numeric parameters, you could call it as:

Naming Conventions

If only one of the optional schema or package names is given, the first identifier can be either a schema name or a package name. For example, to determine whether PAYROLL in the reference PAYROLL . TAX_RATE is a schema or package name, Oracle proceeds as follows:

  • Oracle first checks for the PAYROLL package in the current schema.
  • If a PAYROLL package is not found, Oracle looks for a schema named PAYROLL that contains a top-level TAX_RATE function. If the TAX_RATE function is not found in the PAYROLL schema, an error message is returned.
  • If the PAYROLL package is found in the current schema, Oracle looks for a TAX_RATE function in the PAYROLL package. If a TAX_RATE function is not found in the PAYROLL package, an error message is returned.

You can also refer to a stored top-level function using any synonym that you have defined for it.

Name Precedence

In SQL statements, the names of database columns take precedence over the names of functions with no parameters. For example, if schema SCOTT creates the following two objects:

Then in the following two statements, the reference to NEW_SAL refers to the column EMP . NEW_SAL :

To access the function NEW_SAL , you would enter the following:

Example

For example, to call the TAX_RATE PL/SQL function from schema SCOTT , execute it against the SS_NO and SAL columns in TAX_TABLE , and place the results in the variable INCOME_TAX , specify the following:

These sample calls to PL/SQL functions are allowed in SQL expressions:

Arguments

To pass any number of arguments to a function, supply the arguments within the parentheses. You must use positional notation; named notation is not currently supported. For functions that do not accept arguments, omit the parentheses.

The argument’s datatypes and the function’s return type are limited to those types that are supported by SQL. For example, you cannot call a PL/SQL function that returns a PL/SQL BINARY_INTEGER from a SQL statement.

Using Default Values

The stored function gross_pay initializes two of its formal parameters to default values using the DEFAULT clause, as follows:

When calling gross_pay from a procedural statement, you can always accept the default value of st_hrs . That is because you can use named notation, which lets you skip parameters, as in:

However, when calling gross_pay from a SQL expression, you cannot accept the default value of st_hrs unless you accept the default value of ot_hrs . That is because you cannot use named notation.

Meeting Basic Requirements

To be callable from SQL expressions, a user-defined PL/SQL function must meet the following basic requirements:

  • It must be a stored function, not a function defined within a PL/SQL block or subprogram.
  • It must be a row function, not a column (group) function; that is, it cannot take an entire column of data as its argument.
  • All its formal parameters must be IN parameters; none can be an OUT or IN OUT parameter.
  • The datatypes of its formal parameters must be Oracle Server internal types such as CHAR , DATE , or NUMBER , not PL/SQL types such as BOOLEAN , RECORD , or TABLE .
  • Its return type (the datatype of its result value) must be an Oracle Server internal type.

For example, the following stored function meets the basic requirements:

Controlling Side Effects

To execute a SQL statement that calls a stored function, the Oracle Server must know the purity level of the function, that is, the extent to which the function is free of side effects. In this context, side effects are references to database tables or packaged variables.

Side effects can prevent the parallelization of a query, yield order-dependent (and therefore indeterminate) results, or require that package state be maintained across user sessions (which is not allowed). Therefore, the following rules apply to stored functions called from SQL expressions:

  • The function cannot modify database tables; therefore, it cannot execute an INSERT , UPDATE , or DELETE statement.
  • Functions that read or write the values of packaged variables cannot be executed remotely or in parallel.
  • Only functions called from a SELECT , VALUES , or SET clause can write the values of packaged variables.
  • The function cannot call another subprogram that breaks one of the foregoing rules. Also, the function cannot reference a view that breaks one of the foregoing rules. (Oracle replaces references to a view with a stored SELECT operation, which can include function calls.)

For stand-alone functions, Oracle can enforce these rules by checking the function body. However, the body of a packaged function is hidden; only its specification is visible. So, for packaged functions, you must use the pragma (compiler directive) RESTRICT_REFERENCES to enforce the rules.

The pragma tells the PL/SQL compiler to deny the packaged function read/write access to database tables, packaged variables, or both. If you try to compile a function body that violates the pragma, you get a compilation error.

Calling Packaged Functions

To call a packaged function from SQL expressions, you must assert its purity level by coding the pragma RESTRICT_REFERENCES in the package specification (not in the package body). The pragma must follow the function declaration but need not follow it immediately. Only one pragma can reference a given function declaration.

To code the pragma RESTRICT_REFERENCES , you use the syntax

means «writes no database state» (does not modify database tables)

means «reads no database state» (does not query database tables)

means «writes no package state» (does not change the values of packaged variables)

means «reads no package state» (does not reference the values of packaged variables)

You can pass the arguments in any order, but you must pass the argument WNDS . No argument implies another; for example, RNPS does not imply WNPS .

In the example below, the function compound neither reads nor writes database or package state, so you can assert the maximum purity level. Always assert the highest purity level that a function allows. That way, the PL/SQL compiler will never reject the function unnecessarily.

Later, you might call compound from a PL/SQL block, as follows:

Referencing Packages with an Initialization Part

Packages can have an initialization part, which is hidden in the package body. Typically, the initialization part holds statements that initialize public variables.

In the following example, the SELECT statement initializes the public variable prime_rate :

The initialization code is run only once-the first time the package is referenced. If the code reads or writes database state or package state other than its own, it can cause side effects. Moreover, a stored function that references the package (and thereby runs the initialization code) can cause side effects indirectly. So, to call the function from SQL expressions, you must use the pragma RESTRICT_REFERENCES to assert or imply the purity level of the initialization code.

To assert the purity level of the initialization code, you use a variant of the pragma RESTRICT_REFERENCES , in which the function name is replaced by a package name. You code the pragma in the package specification, where it is visible to other users. That way, anyone referencing the package can see the restrictions and conform to them.

To code the variant pragma RESTRICT_REFERENCES , you use the syntax

where the arguments WNDS , WNPS , RNDS , and RNPS have the usual meaning.

In the example below, the initialization code reads database state and writes package state. However, you can assert WNPS because the code is writing the state of its own package, which is permitted. So, you assert WNDS , WNPS , RNPS -the highest purity level the function allows. (If the public variable prime_rate were in another package, you could not assert WNPS .)

You can place the pragma anywhere in the package specification, but placing it at the top (where it stands out) is a good idea.

To imply the purity level of the initialization code, your package must have a RESTRICT_REFERENCES pragma for one of the functions it declares. From the pragma, Oracle can infer the purity level of the initialization code (because the code cannot break any rule enforced by a pragma). In the next example, the pragma for the function discount implies that the purity level of the initialization code is at least WNDS :

To draw an inference, Oracle can combine the assertions of all RESTRICT_REFERENCES pragmas. For example, the following pragmas (combined) imply that the purity level of the initialization code is at least WNDS , RNDS :

Avoiding Problems

To call a packaged function from SQL expressions, you must assert its purity level using the pragma RESTRICT_REFERENCES . However, if the package has an initialization part, the PL/SQL compiler might not let you assert the highest purity level the function allows. As a result, you might be unable to call the function remotely, in parallel, or from certain SQL clauses.

This happens when a packaged function is purer than the package initialization code. Remember, the first time a package is referenced,

its initialization code is run. If that reference is a function call, any additional side effects caused by the initialization code occur during the call. So, in effect, the initialization code lowers the purity level of the function.

To avoid this problem, move the package initialization code into a subprogram. That way, your application can run the code explicitly (rather than implicitly during package instantiation) without affecting your packaged functions.

A similar problem arises when a packaged function is purer than a subprogram it calls. This lowers the purity level of the function. Therefore, the RESTRICT_REFERENCES pragma for the function must specify the lower purity level. Otherwise, the PL/SQL compiler will reject the function. In the following example, the compiler rejects the function because its pragma asserts RNDS but the function calls a procedure that reads database state:

Overloading

PL/SQL lets you overload packaged (but not stand-alone) functions. That is, you can use the same name for different functions if their formal parameters differ in number, order, or datatype family.

However, a RESTRICT_REFERENCES pragma can apply to only one function declaration. So, a pragma that references the name of overloaded functions always applies to the nearest foregoing function declaration.

In the following example, the pragma applies to the second declaration of valid :

Serially Reusable PL/SQL Packages

PL/SQL packages normally consume user global area (UGA) memory corresponding to the number of package variables and cursors in the package. This limits scalability because the memory increases linearly with the number of users. The solution is to allow some packages to be marked as SERIALLY_REUSABLE (using pragma syntax).

For serially reusable packages, the package global memory is not kept in the UGA per user, but instead it is kept in a small pool and reused for different users. This means that the global memory for such a package is only used within a unit of work. At the end of that unit of work, the memory can therefore be released to the pool to be reused by another user (after running the initialization code for all the global variables).

The unit of work for serially reusable packages is implicitly a CALL to the server, for example, an OCI call to the server, or a PL/SQL client-to-server RPC call or server-to-server RPC call.

Package States

The state of a nonreusable package (one not marked SERIALLY_REUSABLE ) persists for the lifetime of a session. A package’s state includes global variables, cursors, and so on.

The state of a serially reusable package persists only for the lifetime of a CALL to the server. On a subsequent call to the server, if a reference is made to the serially reusable package, Oracle creates a new instantiation (described below) of the serially reusable package and initializes all the global variables to NULL or to the default values provided. Any changes made to the serially reusable package state in the previous CALL s to the server are not visible.

Creating a new instantiation of a serially reusable package on a CALL to the server does not necessarily imply that Oracle allocates memory or configures the instantiation object. Oracle simply looks for an available instantiation work area (which is allocated and configured) for this package in a least-recently used (LRU) pool in SGA. At the end of the CALL to the server this work area is returned back to the LRU pool. The reason for keeping the pool in the SGA is that the work area can be reused across users who have requests for the same package.

Why Serially Reusable Packages?

Since the state of a non-reusable package persists for the lifetime of the session, this locks up UGA memory for the whole session. In applications such as Oracle Office a log-on session can typically exist for days together. Applications often need to use certain packages only for certain localized periods in the session and would ideally like to de-instantiate the package state in the middle of the session once they are done using the package.

With SERIALLY_REUSABLE packages the application developers have a way of modelling their applications to manage their memory better for scalability. Package state that they care about only for the duration of a CALL to the server should be captured in SERIALLY_REUSABLE packages.

Syntax

A package can be marked serially reusable by a pragma. The syntax of the pragma is:

A package specification can be marked serially reusable whether or not it has a corresponding package body. If the package has a body, the body must have the serially reusable pragma if its corresponding specification has the pragma; and it cannot have the serially reusable pragma unless the specification also has the pragma.

Semantics

A package that is marked SERIALLY_REUSABLE has the following properties:

    Its package variables are meant for use only within the WORK boundaries, which correspond to CALL s to the server (either OCI call boundaries or PL/SQL RPC calls to the server).

If the application programmer makes a mistake and depends on a package variable that is set in a previous unit of work, the application program can fail. PL/SQL cannot check for such cases.

Example 1

This example has a serially reusable package specification (there is no body). It demonstrates how package variables behave across CALL boundaries.

Suppose your Enterprise Manager (or SQL*Plus) application issues the following:

The above program will print:

If the package had not had the pragma SERIALLY_REUSABLE , the program would have printed ’10’.

Example 2

This example has both a package specification and body which are serially reusable. Like Example 1, this example demonstrates how the package variables behave across CALL boundaries.

Example 3

This example demonstrates that any open cursors in serially reusable packages get closed automatically at the end of a WORK boundary (which is a CALL ), and that in a new CALL these cursors need to be opened again.

Privileges Required

To call a PL/SQL function from SQL, you must either own or have EXECUTE privileges on the function. To select from a view defined with a PL/SQL function, you are required to have SELECT privileges on the view. No separate EXECUTE privileges are needed to select from the view.

Supplied Packages

Several packaged procedures are provided with the Oracle Server, either to extend the functionality of the database or to give PL/SQL access to some SQL features. You may take advantage of the functionality provided by these packages when creating your application, or you may simply want to use these packages for ideas in creating your own stored procedures.

This section lists each of the supplied packages and indicates where they are described in more detail. These packages run as the invoking user rather than the package owner. The packaged procedures are callable through public synonyms of the same name.

Packages Supporting SQL Features

Oracle supplies the following packaged procedures to give PL/SQL access to some features of SQL:

  • DBMS_DDL
  • DBMS_SESSION
  • DBMS_TRANSACTION
  • DBMS_UTILITY

Table 10-6 describes each of these packages. The footnotes at the end of Table 10-6 explain any restrictions on the use of each procedure. You should consult the package specifications for the most up-to-date information on these packages.

Table 10-3 DBMS_DDL

DBMS_DDL

ALTER PROCEDURE Pro*C COMPILE

ALTER FUNCTION func COMPILE

ALTER PACKAGE pack COMPILE

Note 1: not allowed in triggers

Note 2: not allowed in procedures called from SQL*Forms

Note 3: not allowed in read-only transactions

Note 4: not allowed in remote (coordinated) sessions

Note 5: not allowed in recursive sessions

Note 6: not allowed in stored procedures

Package Procedure(Arguments) SQL Command Equivalent
Table 10-4 DBMS_SESSION

ALTER SESSION CLOSE DATABASE dblink

This procedure reinitializes the state of all packages;

there is no SQL equivalent

ALTER SESSION SET

nls_param_values

SET ROLE .

ALTER SESSION SET

SQL_TRACE = [ TRUE | FALSE ]

This function returns a unique session ID ;

there is no SQL equivalent.

This function is used to determine if a role is enabled;

there is no SQL equivalent.

ALTER SESSION SET

This procedure lets you reclaim unused memory;

Note 1: not allowed in triggers

Note 2: not allowed in procedures called from SQL*Forms

Note 3: not allowed in read-only transactions

Note 4: not allowed in remote (coordinated) sessions

Note 5: not allowed in recursive sessions

Note 6: not allowed in stored procedures

Package Procedure(Arguments) SQL Command Equivalent
Table 10-5 DBMS_TRANSACTION

See Also: Oracle8 Distributed Database Systems

See Also: Oracle8 Tuning

See Also: Oracle8 Distributed Database Systems

See Also: Oracle8 Distributed Database Systems

Package Procedure(Arguments) SQL Command Equivalent
Table 10-6 DBMS_UTILITYs

This procedure is equivalent to calling alter_compile on all procedures, functions, and packages accessible by you. Compilation is completed in dependency order.

This procedure is equivalent to calling analyze_object on all objects in the given schema.

ANALYZE TABLE | INDEX [ .]

for each partition of the object, run in parallel using job queues. This procedure submits a job for each partition; you can control the number of concurrent jobs with the initialization parameter JOB_QUEUE_PROCESSES .

Object_type must be T (table) or I (index). Command_type can be:

— C (compute statistics)

— E (estimate statistics)

— D (delete statistics)

— V (validate structure).

For V, command_opt can be ‘CASCADE’ when object_type is T. For C or E, command_opt can be FOR table, FOR all LOCAL indexes, FOR all columns or a combination of some of the ‘for’ options of analyze statistics (table).

Sample_clause specifies the sample clause to use when command_type is E.

This function formats the error stack into a variable.

(continued)

This function formats the error stack into a variable.

This function formats the current call stack into a variable.

See Also: Oracle8 Distributed Database Systems .

Package Procedure(Arguments) SQL Command Equivalent

Note 1: not allowed in triggers

Note 2: not allowed in procedures called from SQL*Forms

Note 3: not allowed in read-only transactions

Note 4: not allowed in remote (coordinated) sessions

Note 5: not allowed in recursive sessions

For more details on each SQL command equivalent, see the Oracle8 SQL Reference .

The COMMIT , ROLLBACK , ROLLBACK . TO SAVEPOINT , and SAVEPOINT procedures are directly supported by PL /SQL; they are included in the DBMS_TRANSACTION package for completeness.

Packages Supporting Additional Functionality

Several packages are supplied with Oracle to extend the functionality of the database ( DBMS _* and UTL _* packages). The cross-reference column in Table 10-7 tells you where to look for more information on each of these packages.

Table 10-7 Supplied Packages: Additional Functionality

DBMS_ALERT

Supports asynchronous notification of database events.

DBMS_DESCRIBE

Lets you describe the arguments of a stored procedure.

DBMS_JOB

Lets you schedule administrative procedures that you want performed at periodic intervals.

Oracle8 Administrator’s Guide

DBMS_LOCK

Lets you use the Oracle Lock Management services for your applications.

DBMS_OUTPUT

Lets you output messages from triggers, procedures, and packages.

DBMS_PIPE

Allows sessions in the same instance to communicate with each other.

DBMS_SHARED_POOL

Lets you keep objects in shared memory, so that they will not be aged out with the normal LRU mechanism.

Oracle8 Tuning

Lets you register an application name with the database for auditing or performance tracking purposes.

Oracle8 Tuning

DBMS_SYSTEM

Provides system-level utilities, such as letting you enable SQL trace for a session.

Oracle8 Tuning

DBMS_SPACE

Provides segment space information not available through standard views.

Oracle8 Administrator’s Guide

DBMS_SQL

Lets you write stored procedures and anonymous PL / SQL blocks using dynamic SQL ; lets you parse any DML or DDL statement.

DBMS_ROWID

Lets you get information about ROWID s, including the data block number, the object number, and other components.

DBMS_LOB

Lets you manipulate large objects using PL / SQL programs running on the Oracle Server.

Lets you add a message (of a predefined object type) onto a queue or dequeue a message.

DBMS_AQADM

Lets you perform administrative functions on a queue or queue table for messages of a predefined object type.

TRUST_ADMIN

Lets you maintain the Trusted Servers List, which is used in conjunction with the list at the Central Authority to determine if a privileged database link from a particular server can be accepted.

Oracle8 Distributed Database Systems

Lets you administer Heterogeneous Services by registering or dropping distributed external procedures, remote libraries, and non-Oracle systems. Also lets you create or drop some initialization variables for non-Oracle systems.

Oracle8 Distributed Database Systems

DMBS_HS_EXTPROC

Lets you use Heterogeneous Services to establish security for distributed external procedures.

Oracle8 Distributed Database Systems

PASSTHROUGH

Lets you use Heterogeneous Services to send pass-through SQL statements to non-Oracle systems.

Oracle8 Distributed Database Systems

DBMS_REFRESH

Lets you create groups of snapshots that can be refreshed together to a transactionally consistent point in time. Use of this feature requires the distributed option.

Oracle8 Replication

DBMS_SNAPSHOT

Lets you refresh one or more snapshots that are not part of the same refresh group, purge snapshot log. Use of this feature requires the distributed option.

Oracle8 Replication

DBMS_DEFER_QUERY

Lets you build and administer deferred remote procedure calls. Use of this feature requires the replication option.

Oracle8 Replication

DBMS_REPCAT

Lets you use Oracle’s symmetric replication facility. Use of this feature requires the replication option.

Oracle8 Replication

DBMS_REPCAT_ADMIN

Lets you create users with the privileges needed by the symmetric replication facility. Use of this feature requires the replication option.

Oracle8 Replication

UTL_HTTP

Lets you make HTTP callouts from PL / SQL and SQL to access data on the Internet or to call Oracle Web Server Cartridges.

Describing Stored Procedures

You can use the DBMS_DESCRIBE package to get information about a stored procedure or function.

This package provides the same functionality as the Oracle Call Interface OCIDescribeA ny() call. The procedure DESCRIBE_PROCEDURE in this package accepts the name of a stored procedure, and a description of the procedure and each of its parameters. For more information on the OCIDescribeA ny() call, see the Oracle Call Interface Programmer’s Guide .

DBMS_DESCRIBE Package

To create the DBMS_DESCRIBE package, submit the DBMSDESC . SQL and PRVTDESC . PLB scripts when connected as the user SYS . These scripts are run automatically by the CATPROC . SQL script. See «Privileges Required to Execute a Procedure» on page 10-40 for information on the necessary privileges for users who will be executing this package.

Security

This package is available to PUBLIC and performs its own security checking based on the schema object being described.

Types

The DBMS_DESCRIBE package declares two PL/SQL table types, which are used to hold data returned by DESCRIBE_PROCEDURE in its OUT parameters. The types are

Errors

DBMS_DESCRIBE can raise application errors in the range -20000 to -20004. The errors are

DESCRIBE_PROCEDURE Procedure

Syntax

The parameters for DESCRIBE_PROCEDURE are shown in Table 10-8. The syntax is:

Table 10-8 DBMS_DESCRIBE.DESCRIBE_PROCEDURE Parameters

object_name

The name of the procedure being described. The syntax for this parameter follows the rules used for identifiers in SQL. The name can be a synonym. This parameter is required and may not be null. The total length of the name cannot exceed 197 bytes. An incorrectly specified OBJECT_NAME can result in one of the following exceptions:

ORA-20000 — A package was specified. You can only specify a stored procedure, stored function, packaged procedure, or packaged function.

ORA-20001 — The procedure or function that you specified does not exist within the given package.

ORA-20002 — The object that you specified is a remote object. This procedure cannot currently describe remote objects.

ORA-20003 — The object that you specified is invalid and cannot be described.

ORA-20004 — The object was specified with a syntax error.

reserved1 reserved2

Reserved for future use. Must be set to null or the empty string.

overload

A unique number assigned to the procedure’s signature. If a procedure is overloaded, this field holds a different value for each version of the procedure.

position

Position of the argument in the parameter list. Position 0 returns the values for the return type of a function.

If the argument is a composite type, such as record, this parameter returns the level of the datatype. See the Programmer’s Guide to the Oracle Call Interface write-up of the ODESSP call for an example of its use.

argument_name

The name of the argument associated with the procedure that you are describing.

datatype

The Oracle datatype of the argument being described. The datatypes and their numeric type codes are:

0 placeholder for procedures with no arguments

1 VARCHAR, VARCHAR, STRING

2 NUMBER, INTEGER, SMALLINT, REAL,

3 BINARY_INTEGER, PLS_INTEGER,

96 CHAR (ANSI FIXED CHAR), CHARACTER

250 PL/SQL RECORD

251 PL/SQL TABLE

252 PL/SQL BOOLEAN

default_value

1 if the argument being described has a default value; otherwise, the value is 0.

Describes the mode of the parameter:

2 IN OUT

The data length, in bytes, of the argument being described.

precision

If the argument being described is of datatype 2 (NUMBER), this parameter is the precision of that number.

If the argument being described is of datatype 2 (NUMBER, etc.), this parameter is the scale of that number.

If the argument being described is of datatype 2 (NUMBER, etc.), this parameter is the radix of that number.

Return Values

All values from DESCRIBE_PROCEDURE are returned in its OUT parameters. The datatypes for these are PL/SQL tables, to accommodate a variable number of parameters.

Examples

One use of the DESCRIBE_PROCEDURE procedure would be as an external service interface.

For example, consider a client that provides an OBJECT _ NAME of SCOTT . ACCOUNT_UPDATE where ACCOUNT_UPDATE is an overloaded function with specification:

The describe of this procedure might look similar to the output shown below.

The following PL/SQL procedure has as its parameters all of the PL/SQL datatypes:

If you describe this procedure using the package below:

Then the results, as shown below, list all the numeric codes for the PL/SQL datatypes:

Listing Information about Procedures and Packages

The following data dictionary views provide information about procedures and packages:

  • ALL_ERRORS, USER_ERRORS, DBA_ERRORS
  • ALL_SOURCE, USER_SOURCE, DBA_SOURCE
  • USER_OBJECT_SIZE, DBA_OBJECT_SIZE

The OBJECT_SIZE views show the sizes of the PL/SQL objects. For a complete description of these data dictionary views, see your Oracle8 Reference .

The following statements are used in Examples 1 through 3:

The first CREATE PROCEDURE statement has an error in the DELETE statement. (The ‘p’ is absent from ’emp’.)

Example 1: Listing Compilation Errors for Objects

The following query returns all the errors for the objects in the associated schema:

The following results are returned:

Example 2: Listing Source Code for a Procedure

The following query returns the source code for the HIRE_EMP procedure created in the example statement at the beginning of this section:

The following results are returned:

Example 3: Listing Size Information for a Procedure

The following query returns information about the amount of space in the SYSTEM tablespace that is required to store the HIRE_EMP procedure:

The following results are returned:

The DBMS_ROWID Package

The functions in this package let you get the information that you need about ROWID s. You can find out the data block number, the object number, and other components of the ROWID without having to write code to interpret the base-64 character external ROWID .

The specification for the DBMS_ROWID package is in the file dbmsutil.sql . This package is loaded when you create a database, and run catproc.sql .

Some of the functions in this package take a single parameter: a ROWID . This can be a character or a binary ROWID , either restricted or extended, as required. For each function described in this section, both the parameter types and the return type are described.

You can call the DBMS_ROWID functions and procedures from PL/SQL code, and you can also use the functions in SQL statements.

ROWID_INFO is a procedure. It can only be used in PL/SQL code.

SQL Example

You can use functions from the DBMS_ROWID package just like any built-in SQL function. That is, you can use them wherever an expression can be used. In this example, the ROWID_BLOCK_NUMBER function is used to return just the block number of a single row in the EMP table:

PL/SQL Example

This example returns the ROWID for a row in the EMP table, extracts the data object number from the ROWID , using the ROWID_OBJECT function in the DBMS_ROWID package, then displays the object number:

Summary

Table 10-9 DBMS_ROWID Functions

Package Name Description Cross-reference

ROWID_CREATE

Create a ROWID , for testing only.

ROWID_INFO

Procedure that returns the type and components of a ROWID

ROWID_TYPE

Returns the ROWID type: 0 is restricted, 1 is extended.

ROWID_OBJECT

Returns the object number of the extended ROWID .

ROWID_RELATIVE_FNO

Returns the file number of a ROWID .

ROWID_BLOCK_NUMBER

Returns the block number of a ROWID .

ROWID_ROW_NUMBER

Returns the row number.

ROWID_TO_ABSOLUTE_FNO

Returns the absolute file number associated with the ROWID for a row in a specific table.

ROWID_TO_EXTENDED

Converts a ROWID from restricted format to extended.

ROWID_TO_RESTRICTED

Converts an extended ROWID to restricted format.

ROWID_VERIFY

Checks if a ROWID can be correctly extended by the ROWID_TO_EXTENDED function.

90

Function Name Description See Page

Table 10-9 lists the functions and procedures in the DBMS_ROWID package.

Exceptions

The DBMS_ROWID package functions and procedures can raise the ROWID_INVALID exception. The exception is defined in the DBMS_ROWID package as:

ROWID_CREATE Function

The ROWID_CREATE function lets you create a ROWID , given the component parts as parameters. This function is mostly useful for testing ROWID operations, since only the Oracle Server can create a valid ROWID that points to data in a database.

Syntax

Set the ROWID_TYPE parameter to 0 for a restricted ROWID , and to 1 to create an extended ROWID .

If you specify ROWID _ TYPE as 0, the required OBJECT_NUMBER parameter is ignored, and ROWID_CREATE returns a restricted ROWID .

Example

Create a dummy extended ROWID :

Find out what the ROWID_OBJECT function returns:

The variable OBJ_NUMBER now contains 9999.

ROWID_INFO Procedure

This procedure returns information about a ROWID , including its type (restricted or extended), and the components of the ROWID . This is a procedure, and cannot be used in a SQL statement.

Syntax

The IN parameter ROWID_IN determines if the ROWID is a restricted (0) or extended (1) ROWID .

The OUT parameters return the information about the ROWID , as indicated by their names.

For information about the ROWID_TYPE parameter, see the ROWID_TYPE function on page 10-86.

Example

To read back the values for the ROWID that you created in the ROWID_CREATE example:

ROWID_TYPE Function

This function returns 0 if the ROWID is a restricted ROWID , and 1 if it is extended.

Syntax

Example

ROWID_OBJECT Function

This function returns the data object number for an extended ROWID . The function returns zero if the input ROWID is a restricted ROWID .

Syntax

Example

ROWID_RELATIVE_FNO Function

This function returns the relative file number of the ROWID specified as the IN parameter. (The file number is relative to the tablespace.)

Syntax

Example

The example PL/SQL code fragment returns the relative file number:

ROWID_BLOCK_NUMBER Function

This function returns the database block number for the input ROWID .

Syntax

Example

The example SQL statement selects the block number from a ROWID and inserts it into another table:

ROWID_ROW_NUMBER Function

This function extracts the row number from the ROWID IN parameter.

Syntax

Example

Select a row number:

ROWID_TO_ABSOLUTE_FNO Function

This function extracts the absolute file number from a ROWID , where the file number is absolute for a row in a given schema and table. The schema name and the name of the schema object (such as a table name) are provided as IN parameters for this function.

Syntax

Example

ROWID_TO_EXTENDED Function

This function translates a restricted ROWID that addresses a row in a schema and table that you specify to the extended ROWID format.

Syntax

Example

Assume that there is a table called RIDS in the schema SCOTT , and that the table contains a column ROWID_COL that holds ROWID s (restricted), and a column TABLE_COL that point to other tables in the SCOTT schema. You can convert the ROWID s to extended format with the statement:

Usage

ROWID_TO_EXTENDED returns the ROWID in the extended character format. If the input ROWID is NULL , the function returns NULL . If a zero-valued ROWID is supplied (00000000.0000.0000), a zero-valued restricted ROWID is returned.

If the schema and object names are provided as IN parameters, this function verifies SELECT authority on the table named, and converts the restricted ROWID provided to an extended ROWID , using the data object number of the table. That ROWID_TO_EXTENDED returns a value, however, does not guarantee that the converted ROWID actually references a valid row in the table, either at the time that the function is called, or when the extended ROWID is actually used.

If the schema and object name are not provided (are passed as NULL ), then this function attempts to fetch the page specified by the restricted ROWID provided. It treats the file number stored in this ROWID as the absolute file number. This can cause problems if the file has been dropped, and its number has been reused prior to the migration. If the fetched page belongs to a valid table, the data object number of this table is used in converting to an extended ROWID value. This is very inefficient, and Oracle recommends doing this only as a last resort, when the target table is not known. The user must still know the correct table name at the time of using the converted value.

If an extended ROWID value is supplied, the data object number in the input extended ROWID is verified against the data object number computed from the table name parameter. If the two numbers do not match, the INVALID_ROWID exception is raised. If they do match, the input ROWID is returned.

See the ROWID_VERIFY function on page 10-90 for a method to determine if a given ROWID can be converted to the extended format.

ROWID_TO_RESTRICTED Function

This function converts an extended ROWID into restricted ROWID format.

Syntax

Example

ROWID_VERIFY Function

This function returns 0 if the input restricted ROWID can be converted to extended format, given the input schema name and table name, and it returns 1 if the conversion is not possible. Note that you can use this function in a BOOLEAN context in a SQL statement, as shown in the example.

Syntax

Example

Considering the schema in the example for the ROWID_TO_EXTENDED function on page 10-88, you can use the following statement to find bad ROWID s prior to conversion:

The UTL_HTTP Package

The stored package UTL_HTTP makes HTTP (hyper-text transfer protocol) callouts from PL/SQL and SQL. You can use it to access data on the internet, or to call Oracle Web Server Cartridges. The package contains two similar entrypoints, each of which takes a string URL (universal resource locator), contacts that site, and returns the data (typically HTML — hyper-text markup language) obtained from that site.

This is the specification of packaged function UTL_HTTP . REQUEST :

UTL_HTTP . REQUEST returns up to the first 2000 bytes of the data retrieved from the given URL. For example:

This is the specification of packaged function UTL_HTTP . REQUEST_PIECES , which uses type UTL_HTTP . HTML_PIECES :

UTL_HTTP . REQUEST_PIECES returns a PL/SQL-table of 2000-byte pieces of the data retrieved from the given URL. The optional second argument places a bound on the number of pieces retrieved. For example, the following block retrieves up to 100 pieces of data (each 2000 bytes, except perhaps the last) from the URL. It prints the number of pieces retrieved and the total length, in bytes, of the data retrieved.

Here is the output:

Below is the specification for package UTL_HTTP . It describes the exceptions that can be raised by functions REQUEST and REQUEST_PIECES :

Источник

В SQL*Plus предлагается набор команд для администрирования и управления базами данных Oracle, которые помогают решать административные задачи. Все они кратко рассматриваются в этой статье блога.

Команда CLEAR

Команда CLEAR удаляет несколько текущих параметров, включая параметры столбцов и параметры буфера SQL*Plus. Она применяется для обеспечения утраты силы тех параметров, которые уже больше не нужны в текущем сеансе SQL*Plus. В листинге ниже показан пример вывода команды CLEAR.


SQL> CLEAR BREAKS
breaks cleared
SQL> CLEAR BUFFER
buffer cleared
SQL> CLEAR COLUMNS
columns cleared
SQL> CLEAR SQL
sql cleared
SQL> CLEAR TIMING
SQL> CLEAR SCREEN

Сама по себе команда CLEAR просто очищает экран, не влияя на параметры SQL*Plus.Команды CLEAR BUFFER и CLEAR SQL достигают того же эффекта за счет удаления SQL- кода из буфера памяти SQL*Plus. Команды CLEAR COLUMNS и CLEAR BREAKS удаляют,соответственно, любые определения столбцов и разбивки. Команда CLEAR TIMING приводит к отключению всех таймеров. Команда CLEAR SCR (или CLEAR SCREEN) применяется для очистки экрана.

Команда STORE

Во время сеанса SQL*Plus наверняка будет возникать необходимость изменить те или иные параметры среды для того, чтобы выполнить специфический SQL-сценарий или команду. Если необходимо сберечь эти параметры на будущее, можно воспользоваться командой STORE. После сохранения с ее помощью нужных значений в сценарии,этот сценарий можно запускать в любое время и восстанавливать исходные значения всех переменных. То есть в случае запуска отчета, требующего изменения значений некоторых переменных, достаточно будет просто запустить после окончания работы с отчетом сценарий, содержащий исходные значения, и исходные значения всех переменных тут же восстановятся.

Приведенный ниже пример показывает, как применять команду STORE для сохранения параметров среды SQL*Plus:

SQL> STORE SET mysqlplus.sql
Created file mysqlplus.sql
SQL> 

Выполнение показанной выше команды приведет к сохранению всех текущих значений среды в файле по имени sqlplus.sql. После сохранения избранных переменных среды в файле их можно легко использовать повторно, запустив этот файл сценария.

(О том, как выполнять сценарии, более подробно речь пойдет позже в этой главе.) Чтобы восстановить сохраненные значения всех системных переменных, в данном случае достаточно будет ввести такую команду: 

SQL> START mysqlplus.sql

При желании для запуска сценария можно использовать и команду @mysqlplus.sql или @@mysqlplus.sql. Этот сценарий можно добавить в сценарий профиля пользователя, чтобы все переменные имели желаемые значения при каждом запуске SQL*Plus.Команда STORE может использоваться с тремя параметрами: CREATE, REPLACE или APPEND. По умолчанию она применяется с параметром CREATE, который приводит к созданию нового файла. Для замены существующего файла и сохранения в нем команд SQL*Plus служит параметр REPLACE, а для добавления команд в существующий файл — параметр APPEND.

Команда SHOW

Команда SHOW применяется для отображения значений переменных. Для выяснения значений отдельных переменных вместе с ней указывается имя необходимой переменной: 

SQL> SHOW TTITLE
ttitle ON and is the following 49 characters:
Annual Financial Report for the Women's Club, 2005
SQL>

Команда SHOW ALL приводит к отображению текущих значений всех переменных среды SQL*Plus. Другие наиболее важные параметры, которые могут применяться с командой SHOW, кратко описаны в следующих подразделах.

Команда SHOW RECYCLEBIN

Команда SHOW RECYCLEBIN является одной из наиболее полезных. Она позволяет выяснить, есть ли такие таблицы, которые возможно восстановить с помощью команды FLASHBACK TO BEFORE DROP. В случае удаления таблица уничтожается не сразу — она остается в корзине (Recycle Bin) до тех пор, пока либо не будет удалена навсегда с помощью команды DROP TABLE PURGE, либо в базе данных не перестанет хватать места.

О возможности выполнения ретроспективного отката таблиц (Flashback Table) более подробно будет рассказываться в главе 8, но ниже для примера показано, как может выглядеть вывод команды SHOW RECYCLEBIN при наличии таблицы в корзине:

SQL> CREATE TABLE test (name varchar2(30));
Table created.
SQL> DROP TABLE test;
Table dropped.
SQL> SHOW RECYCLEBIN
ORIGINAL NAME        RECYCLEBIN NAME       OBJECT TYPE          DROP TIME
------------------------------------------------------------------------------
TEST          BIN$oGZbms6pRa6xlbFglGjgUw==$0    TABLE        2008-06-27:13:13:58
SQL>

Здесь видно, что таблица TEST после удаления с помощью команды DROP TABLE автоматически переименовывается базой данных и сохраняется в корзине

Команда SHOW USER

Команда SHOW USER отображает имя используемой в текущий момент учетной записи пользователя:

SQL> SHOW USER
USER is "SYSTEM"
SQL> 

Команда SHOW SGA

Команда SHOW SGA отображает информацию о текущем распределении памяти SGA:

SQL> SHOW SGA
Total System Global Area            452984832 bytes
Fixed Size                            1309568 bytes
Variable Size                       237765760 bytes
Database Buffers                    209715200 bytes
Redo Buffers                           194304 bytes
SQL> 

Команда SHOW PARAMETERS

Команда SHOW PARAMETERS отображает список всех текущих стандартных и нестандартных значений параметров инициализации:

SQL> SHOW PARAMETERS
NAME                          TYPE     VALUE
---------------------------  --------  ------
O7_DICTIONARY_ACCESSIBILITY  boolean   FALSE
. . .
SQL> 

Кроме того, команда SHOW PARAMETERS может применяться для просмотра значений параметров инициализации только конкретного типа, как показано ниже:

 
SQL> SHOW PARAMETERS MEMORY
NAME                              TYPE       VALUE
---------------------------- -----------     ------
hi_shared_memory_address        integer        0
memory_max_target               big integer    820M
memory_target                   big integer    820M
shared_memory_address           integer        0
SQL>

Команда SHOW SPPARAMETER позволяет просматривать значения всех параметров инициализации, которые перечислены в файле SPFILE, как показано в следующем примере: 

SQL> SHOW SPPARAMETER db_name
SID            NAME           TYPE       VALUE
-------- ---------------- ----------- -----------
*              db_name       string       orcl
SQL>

Команда SHOW ERRORS

Командой SHOW ERRORS очень удобно пользоваться для просмотра ассоциируемых с процедурой или функцией ошибок компиляции. Ее можно выполнять сразу же после компиляции той или иной единицы PL/SQL. В случае отсутствия ошибок ее вывод будет выглядеть следующим образом: 

SQL> SHOW ERRORS PROCEDURE TEST_PROC
NO ERRORS.
SQL>

Вас заинтересует / Intresting for you:

Syntax

SHOW ERRORS [LIMIT [offset,] row_count]
SHOW ERRORS [LIMIT row_count OFFSET offset]
SHOW COUNT(*) ERRORS

Contents

  1. Syntax
  2. Description
  3. Examples

Description

This statement is similar to SHOW WARNINGS, except that instead of
displaying errors, warnings, and notes, it displays only errors.

The LIMIT clause has the same syntax as for the
SELECT statement.

The SHOW COUNT(*) ERRORS statement displays the number of
errors. You can also retrieve this number from the error_count variable.

SHOW COUNT(*) ERRORS;
SELECT @@error_count;

The value of error_count might be greater than the number of messages displayed by SHOW WARNINGS if the max_error_count system variable is set so low that not all messages are stored.

For a list of MariaDB error codes, see MariaDB Error Codes.

Examples

SELECT f();
ERROR 1305 (42000): FUNCTION f does not exist

SHOW COUNT(*) ERRORS;
+-----------------------+
| @@session.error_count |
+-----------------------+
|                     1 |
+-----------------------+

SHOW ERRORS;
+-------+------+---------------------------+
| Level | Code | Message                   |
+-------+------+---------------------------+
| Error | 1305 | FUNCTION f does not exist |
+-------+------+---------------------------+

  • ← SHOW ENGINES

  • ↑ SHOW ↑

  • SHOW EVENTS →

Comments

Content reproduced on this site is the property of its respective owners,
and this content is not reviewed in advance by MariaDB. The views, information and opinions
expressed by this content do not necessarily represent those of MariaDB or any other party.

title summary aliases

SHOW ERRORS | TiDB SQL Statement Reference

An overview of the usage of SHOW ERRORS for the TiDB database.

/docs/dev/sql-statements/sql-statement-show-errors/

/docs/dev/reference/sql/statements/show-errors/

SHOW ERRORS

This statement shows errors from previously executed statements. The error buffer is cleared as soon as a statement executes successfully. In which case, SHOW ERRORS will return an empty set.

The behavior of which statements generate errors vs. warnings is highly influenced by the current sql_mode.

Synopsis

ShowErrorsStmt:

ShowErrorsStmt

Examples

mysql> select invalid;
ERROR 1054 (42S22): Unknown column 'invalid' in 'field list'
mysql> create invalid;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your TiDB version for the right syntax to use line 1 column 14 near "invalid"
mysql> SHOW ERRORS;
+-------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| Level | Code | Message                                                                                                                                                   |
+-------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| Error | 1054 | Unknown column 'invalid' in 'field list'                                                                                                                  |
| Error | 1064 | You have an error in your SQL syntax; check the manual that corresponds to your TiDB version for the right syntax to use line 1 column 14 near "invalid"  |
+-------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql> CREATE invalid2;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your TiDB version for the right syntax to use line 1 column 15 near "invalid2"
mysql> SELECT 1;
+------+
| 1    |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

mysql> SHOW ERRORS;
Empty set (0.00 sec)

MySQL compatibility

This statement is understood to be fully compatible with MySQL. Any compatibility differences should be reported via an issue on GitHub.

See also

  • SHOW WARNINGS

Понравилась статья? Поделить с друзьями:
  • She live in moscow найти ошибку
  • Sharp ar 6020v ошибка f2
  • Sharp 6020 коды ошибок
  • Sharedlibrary dll ошибка
  • Shaders error invalid program final