• PL/SQL Some Advanced Fundamental


    1.Running Your First PL/SQL Program

    This is called anonymous block,a block with no name.Its only executable statement is a call to the procedure PUT_LINE.supplied in Oracle's built in package named DBMS_OUTPUT.

    1. SQL> set serveroutput on
    2. SQL> BEGIN
    3. 2 DBMS_OUTPUT.PUT_LINE('hello, world');
    4. 3 END;
    5. 4 /
    6. hello, world
    7. PL/SQL procedure successfully completed.
    8. SQL>

    2.Saving Scripts to Use Again Later.

    1. SQL> EDIT hello.sql
    2. SET SERVEROUTPUT ON
    3. BEGIN
    4. DBMS_OUTPUT.PUT_LINE('hello, world');
    5. END;
    6. /
    7. ~
    8. ~
    9. ~
    10. "hello.sql" [New] 6L, 74C written
    11. SQL> @hello.sql
    12. hello, world
    13. PL/SQL procedure successfully completed.
    14. SQL> @hello
    15. hello, world
    16. PL/SQL procedure successfully completed.
    17. SQL>

    3. Introduction to Program Structure

    In PL/SQL, there are only three types of blocks:

    • Anonymous blocks

    • Procedures

    • Functions

     Anonymous blocks

    1. BEGIN
    2. statements
    3. END;

    The second major form of anonymous block includes a declaration section. In this form, the initial keyword is DECLARE rather than BEGIN:

    1. DECLARE
    2. declarations
    3. BEGIN
    4. statements
    5. END;

    the most common forms of an anonymous block: 

    1. [ DECLARE
    2. declarations ]
    3. BEGIN
    4. statements
    5. [ EXCEPTION
    6. exception handlers ]
    7. END;

    Named blocks: procedures and functions

    • Procedure

    A named program that executes some predefined statements and then returns control to whatever called it. After creating a procedure,you can invoke it by name from other programs.

    • Function

    Similar to a procedure,except that it returns a value to the program that calls it. The data returned by a function is always of a specific, predefined datatype

    1. SQL>
    2. SQL> CREATE FUNCTION message_for_the_world
    3. 2 RETURN VARCHAR2
    4. 3 AS
    5. 4 BEGIN
    6. 5 RETURN 'hello, world';
    7. 6 END;
    8. 7 /
    9. Function created.
    10. SQL>

    .One way we could execute the function would be to declare a temporary variable and assign the output from the function to it, as shown here:

    1. SQL>
    2. SQL> DECLARE
    3. 2 msg VARCHAR2(30);
    4. 3 BEGIN
    5. 4 msg := message_for_the_world;
    6. 5 DBMS_OUTPUT.PUT_LINE(msg);
    7. 6 END;
    8. 7 /
    9. hello, world
    10. PL/SQL procedure successfully completed.
    11. SQL>

    since the function returns a VARCHAR2,the function can “stand in” wherever you could use a string. You don’t really need a temporary variable in the program.

    1. SQL> BEGIN
    2. 2 DBMS_OUTPUT.PUT_LINE(message_for_the_world);
    3. 3 END;
    4. 4 /
    5. hello, world
    6. PL/SQL procedure successfully completed.
    7. SQL>

    Variables

    In PL/SQL,before you can work with any kind of variable,you must first declare it; that is,you must give it a name and specify its datatype.

    Datatypes

    The most common datatypes in PL/SQL are in four families: string,number,date, and logical (Boolean).

    Strings

    Strings are “free form” data. A string can contain any valid character in the character set of a language. While there are several variations of strings,the datatype you will almost always use is VARCHAR2.

    The general format for a VARCHAR2 declaration is:

    variable_name VARCHAR2(n);
    1. SQL>
    2. SQL> DECLARE
    3. 2 small_string VARCHAR2(4);
    4. 3 line_of_text VARCHAR2(2000);
    5. 4 biggest_string_allowed VARCHAR2(32767);
    6. 5 BEGIN
    7. 6 biggest_string_allowed := 'Tiny';
    8. 7 line_of_text := 'Tiny';
    9. 8 IF biggest_string_allowed = line_of_text
    10. 9 THEN
    11. 10 DBMS_OUTPUT.PUT_LINE('They match!');
    12. 11 END IF;
    13. 12 END;
    14. 13 /
    15. They match!
    16. PL/SQL procedure successfully completed.
    17. SQL>

    Numbers

    PL/SQL,just like the Oracle database server,offers a variety of numeric datatypes to suit different purposes. There are generally two types of numeric data: whole number and decimal (in which digits to the right of the decimal point are allowed)

    The declaration of a NUMBER looks like this:

    variable_name NUMBER [ ( precision [, scale ] ) ]; 

    Precision and scale,if present,must be literal values (and integers at that); you cannot use variables or constants in the declaration.

    The following examples demonstrate the different ways you can declare variables of type NUMBER:

    The bean_counter variable can hold values with up to ten digits of precision, three of which are to the right of the decimal point. If you assign 12345.6784 to bean_counter,it is rounded to 12345.678. If you assign 1234567891.23 to the variable,the operation will return an error because there are more digits than allowed for in the precision:

    bean_counter NUMBER (10,3);

    • The any_number variable can span the full range of supported values,because the default precision and scale are unspecified:

    any_number NUMBER;

    Dates

    the only true date
    datatype you could use was DATE:

    1. DECLARE
    2. l_birth_date DATE;

    Handy built-in functions for dates include the following:

    SYSDATE

    Returns the current system date and time down to the nearest second

    SYSTIMESTAMP (supported in Oracle9i only)

    Returns the current system date and time down to the nearest .000001 seconds

    TO_CHAR

    Converts a date to a human-readable string

    TO_DATE

    Converts a human-readable string to a date

    Booleans

    Oracle’s SQL does not support this datatype; you cannot create a table with a column of datatype BOOLEAN. You can create a table with a column of datatype VARCHAR2(1) and store the text “T” or “F”,representing TRUE or FALSE,in that column.

    Here is another example of a Boolean declaration:

    1. DECLARE
    2. too_young_to_vote BOOLEAN;

    Boolean values and variables are very useful in PL/SQL. Because a Boolean variable can only be TRUE,FALSE,or NULL,you can use that variable to explain what is happening in your code. With Booleans you can write code that is easily readable, because it is more English-like. You can replace a complicated Boolean expression involving many different variables and tests with a single Boolean variable that directly expresses the intention and meaning of the text.

    Declaring Variables

    1. Variables to which you do not assign an initial value will default to NULL. In other
    2. words:
    3. number_of_teeth NUMBER;
    4. is equivalent to:
    5. number_of_teeth NUMBER := NULL;
    6. is equivalent to:
    7. number_of_teeth NUMBER DEFAULT NULL;

    Common Operators

     Assignment Operator

    Given two variables a and b, an assignment statement is of the following form:

    a := b;

    You can store a string in a VARCHAR2,but you can’t store it in a NUMBER. The statement:

    first_name := 'Steven';

    Assuming that pi is declared as NUMBER, here is the assignment:

    pi := 3.141592654;

    If is_lukewarm is a BOOLEAN, an assignment might look like:

    is_lukewarm := FALSE;

    Arithmetic Operators

    1. a + b
    2. Result of adding a and b
    3. a - b
    4. Result of subtracting b from a
    5. a * b
    6. Result of multiplying a and b
    7. a / b
    8. Result of dividing a by b
    9. a**b
    10. Result of raising a to the bth power

    Logical Operators

    This class of operators act on Boolean values and return Boolean values. In the following, a and b are declared to be of datatype BOOLEAN.

    a AND b

    Logical conjunction operator. If both operands a and b are true then the result is TRUE. Otherwise, if at least one expression is FALSE, then the result is FALSE

    a OR b

    Logical disjunction operator. If at least one expression is TRUE,then the result is TRUE. It doesn’t matter what the other operand is—it can be null or true or false.

    NOT b

    Logical negation operator. The result is the logical “opposite” of a b,as long as b is not null. If b is null,though,it’s kind of a strange case,because NOT b is then also null!

    Non-Null Comparison Operators

    a = b

    Evaluates to TRUE if a and b are non-null and contain the same value. Evaluates to FALSE if a and b are non-null and contain different values. Evaluates to NULL if one or both of the operands is null. This works for non-null numbers,strings,dates,Booleans,and,under certain conditions, other datatypes.

    a != b

    The logical inverse of =,evaluates to TRUE if a and b are non-null and contain different values. If a or b is null, the result is null. The following statement fragments illustrate the four variants of the inequality operator; all of these are equivalent:

    1. IF favorite_flavor != 'ROCKY ROAD' THEN ...
    2. IF favorite_flavor <> 'ROCKY ROAD' THEN ...
    3. IF favorite_flavor ~= 'ROCKY ROAD' THEN ...
    4. IF favorite_flavor ^= 'ROCKY ROAD' THEN ...

    These various forms of the operator can make life easier for programmers who already use them in other languages.

    1. In all of the following illustrative cases, a, b, c, and d are assumed non-null:
    2. a > b
    3. Evaluates to TRUE if a is greater than b.
    4. a < b
    5. Evaluates to TRUE if a is less than b.
    6. a >= b
    7. Evaluates to TRUE if a is greater than b,or if a is equal to b. This is just a shortcut for the compound expression a > b OR a = b.
    8. a <= b
    9. Evaluates to TRUE if a is less than b,or if a is equal to b. Same as a < b OR a =
    10. b.
    11. a IN (b, c [, d, ... ] )
    12. Convenience equality operator,short for the compound expression (a = b) OR
    13. (a = c) [ OR (a = d) .... ]
    14. a BETWEEN b AND c
    15. Inclusive range checking operator,short for the compound expression a >= b
    16. AND a <= c.
    17. Note that with these comparison operators,if any of the operands are null,the result
    18. will be null.

    Test for Nullity

    To test correctly whether a particular variable or expression is null,you must use the IS NULL operator. When testing for the presence of a non-null value,use IS NOT NULL.

    1. a IS NULL
    2. Evaluates to TRUE if a is null.
    3. a IS NOT NULL
    4. Evaluates to TRUE if a is not null.
    1. IF number_of_pages IS NULL
    2. THEN
    3. DBMS_OUTPUT.PUT_LINE('Warning: number of pages is unknown.');
    4. END IF;

    String Patterns and Wildcards: LIKE, %, _

    expression

    The string you want to examine to see if the pattern is present.

    pattern

    Another string that includes one or more of the wildcard characters,% or _. The percent wildcard matches any number (zero or more) of characters,and the underscore matches any one single character.

    String Concatenation: ||

    PL/SQL uses two vertical bars || as an operator that will connect two strings. Consider the expression:

    a || b

    If a and b are strings,this evaluates to a string consisting of the “joining” of them. Null operands are treated as strings with zero length. So for example, the following:

    full_name := 'Steven ' || 'Feuerstein';

    stores in the full_name variable the same result as the following:

    full_name := 'Steven Feuerstein';

    You can also concatenate a series of strings:

    my_family := 'Steven ' || 'Veva ' || NULL || 'Chris ' || 'Eli';

    which stores in my_family the string:

    Steven Veva Chris Eli

    IF Statements

    1. IF condition1
    2. THEN
    3. statements
    4. [ ELSIF condition2
    5. THEN
    6. statements ] ...
    7. [ ELSIF conditionn
    8. THEN
    9. statements ]
    10. [ ELSE
    11. last_statements ]
    12. END IF;
    1. IF book_count > 10000
    2. THEN
    3. ready := TRUE;
    4. DBMS_OUTPUT.PUT_LINE ('We''re ready to open the library!');
    5. END IF;
    6. IF hourly_wage < 10
    7. THEN
    8. hourly_wage := hourly_wage * 1.5;
    9. ELSE
    10. hourly_wage := hourly_wage * 1.1;
    11. END IF;
    12. IF salary BETWEEN 10000 AND 40000
    13. THEN
    14. bonus := 1500;
    15. ELSIF salary > 40000 AND salary <= 100000
    16. THEN
    17. bonus := 1000;
    18. ELSE
    19. bonus := 0;
    20. END IF;

    Simple CASE statement

    The general syntax of the so-called simple CASE statement is:

    1. CASE selector
    2. WHEN expression1 THEN statements
    3. [ WHEN expression2 THEN statements ]
    4. ...
    5. [ ELSE statements ]
    6. END CASE;

    Searched CASE statement

    This alternate form is more flexible; it omits the selector and supports individual conditions instead of testing for equality with a selector. In other words:

    1. CASE
    2. WHEN condition1 THEN statements
    3. [ WHEN condition2 THEN statements ]
    4. ...
    5. [ ELSE statements ]
    6. END CASE;
    1. CASE
    2. WHEN salary BETWEEN 10000 AND 40000 THEN
    3. bonus := 1500;
    4. WHEN salary > 40000 AND salary <= 100000 THEN
    5. bonus := 10000;
    6. ELSE
    7. bonus := 0;
    8. END CASE;

    CASE expressions

    In PL/SQL,the CASE keyword can serve more than one purpose. We’ve just seen an example of CASE serving as a statement,but it can also serve as an expression—that is, it can return a value.

    1. gender_name :=
    2. CASE gender_code
    3. WHEN 'M' THEN 'MALE'
    4. WHEN 'F' THEN 'FEMALE'
    5. ELSE 'UNKNOWN'
    6. END;

    Executing in Circles: Loop Statements

    A very common requirement in programming is to execute the same functionality repetitively—in a loop. Programmers call this iteration,and it is a mainstay of virtually all procedural languages.

    1. FOR loop (numeric and cursor)
    2. This loop executes its body of code for a specific, limited number of iterations.
    3. Simple or infinite loop
    4. This loop executes its body of code until it encounters an EXIT statement.
    5. WHILE loop
    6. This loop executes its body of code until the WHILE condition evaluates to
    7. FALSE.

    FOR Loop

    Use the FOR loop when you know in advance how many times you want the loop to execute (its number of iterations).

    1. BEGIN
    2. show_books_borrowed (1);
    3. show_books_borrowed (2);
    4. show_books_borrowed (3);
    5. show_books_borrowed (4);
    6. show_books_borrowed (5);
    7. show_books_borrowed (6);
    8. END;
    9. /
    1. Alternatively, we could just use a FOR loop to achieve the same result:
    2. BEGIN
    3. FOR month_num IN 1 .. 6
    4. LOOP
    5. show_books_borrowed (month_num);
    6. END LOOP;
    7. END;
    8. /
    9. I’d rather use the loop, wouldn’t you? The exact syntax is:
    10. FOR loop_counter IN [ REVERSE ] lower_bound .. upper_bound
    11. LOOP
    12. statements
    13. END LOOP;
    14. Where:
    15. loop_counter
    16. An identifier that has not been declared in the program,this variable gives you a
    17. way of detecting the “trip number” through the loop.
    18. lower_bound
    19. A numeric expression that Oracle uses to compute the smallest value assigned to
    20. loop_counter. Often,this will just be the number 1. You should make this an
    21. integer,but if you don’t,PL/SQL automatically rounds it to an integer. If the
    22. lower bound is greater than the upper bound,the loop will not execute; if it is
    23. null, your program will end in a runtime error.
    24. REVERSE
    25. Without this keyword,the loop counter increases by one with every trip through
    26. the loop,from the lower to the upper bound. With REVERSE,though,the loop
    27. will decrease by one instead, going from the upper to the lower bound.
    28. .. (yes, that really is two consecutive dots)
    29. This is a special operator that means “visit all the integers between lower_bound
    30. and upper_bound.”
    31. upper_bound
    32. Numeric expression that provides the highest number the counter will be. This
    33. must be equal to or greater than the lower bound in order for the loop to execute.

    Simple (Infinite) Loop

    1. LOOP
    2. statements
    3. END LOOP;

    This is also called an infinite loop*,because the LOOP syntax itself does not offer any way to stop the loop. Here, for example, is an infinite loop:

    1. LOOP
    2. l_date_published := SYSDATE;
    3. END LOOP;

    You can usually tell when you have written an infinite loop: your SQL*Plus session seems to go into a coma. Now,there are actually some situations in which an “infinite” loop is desirable (such as a program that wakes up every ten minutes to check for a message). In general,though,you want to avoid infinite loops,and PL/SQL gives you an easy way to do that: the EXIT statement: EXIT;

    This means simply “stop looping now and proceed to the next executable statement in the program.” To make things simpler for you,Oracle provides the EXIT WHEN feature in PL/SQL:

    1. LOOP
    2. statements
    3. EXIT WHEN condition;
    4. END LOOP;
    1. counter := 0;
    2. LOOP
    3. counter := counter + 1;
    4. prior_approx := approx;
    5. approx := new_approx(approx);
    6. EXIT WHEN counter = 1000 OR prior_approx - approx = 0.0;
    7. END LOOP;

    WHILE Loop

    The WHILE loop executes as long as (“while”) the specified Boolean condition evaluates to TRUE. It looks like this:

    1. WHILE condition
    2. LOOP
    3. statements
    4. END LOOP;

    This loop is the equivalent of: 

    1. LOOP
    2. EXIT WHEN NOT condition;
    3. statements
    4. END LOOP;
    1. prior_approx := approx;
    2. approx := new_approx(approx);
    3. counter := 0;
    4. WHILE counter <= 1000 AND prior_approx - approx != 0.0
    5. LOOP
    6. counter := counter + 1;
    7. prior_approx := approx;
    8. approx := new_approx(approx);
    9. END LOOP;

    Simple or WHILE Loop?

     Here,then,is my extrapolation: when you write longer,complicated loops,the END LOOP statement may be 50,100,or even 200 lines away from the WHILE LOOP statement. Further,the WHILE condition could also involve 2,5,or 10 different variables and complex formulas. In this case,you will find yourself repeating perhaps 5 lines of code before the WHILE statement and at the end of the loop. How can you maintain that code effectively,so that any change in one set of assignments occurs in the other as well? Here’s the bottom line: if as you write a WHILE loop you find yourself repeating the setup and next-iteration code,try switching to a simple loop. You will very likely be able to write and maintain just one version of the code.

    Code Formatting: Requirements and Guidelines

    1. As you begin to write your own code,you will have many questions about the best
    2. approach to capitalization,indentation,spacing,and other aspects of programming
    3. style. This section lists some of the features of the language in this area,and should
    4. help you get started with good habits

    Upper- or Lowercase?

    PL/SQL is case-insensitive (except for the values of literal strings). That means you can type keywords and identifiers in uppercase or lowercase or mixed-case—it doesn’t make any difference. So all of these statements are identical:

    1. favorite_flavor VARCHAR2(20);
    2. Favorite_Flavor varchar2(20);
    3. fAvOrItE_flaVOR vArCHAr(20);

    Spacing and Line Breaks

    1. You’ll sometimes hear programmers talk of whitespace in their programs.
    2. Whitespace consists of spaces,tabs,and/or line breaks. PL/SQL allows any amount
    3. of whitespace to separate keywords and identifiers. The declaration:
    4. favorite_flavor VARCHAR2(20);
    5. is completely equivalent to:
    6. favorite_flavor VARCHAR2(20);
    7. and also to the ludicrous:
    8. favorite_flavor
    9. VARCHAR2
    10. ( 20 ) ;
  • 相关阅读:
    java毕业生设计园艺生活网站计算机源码+系统+mysql+调试部署+lw
    ipad手写笔有必要买原装吗?第三方性价比高的手写笔推荐
    Java-SpringBoot-使用多态给项目解耦
    泡泡玛特,难成“迪士尼”
    bootstrap-validator实现验证表单
    线性空间的定义与性质
    大数据如何应用于业务和决策?_光点科技
    前端骨架屏应用
    Unity - Shader Compiled Log
    高效构建 vivo 企业级网络流量分析系统
  • 原文地址:https://blog.csdn.net/u011868279/article/details/126149023