1. Trang chủ
  2. » Công Nghệ Thông Tin

Teach Yourself PL/SQL in 21 Days- P3

50 334 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 50
Dung lượng 2,52 MB

Nội dung

Writing PL/SQL Expressions 77 3 AND The AND operator is used to join two comparison expressions when you are interested in testing whether both expressions are true. It can also be used for the same purpose with two Boolean variables—to check to see whether both are equal to true . The Syntax for the AND Operator boolean_expression AND boolean_expression In this syntax, boolean_expression can be any expression resulting in a Boolean, or true / false ,value. This is often a comparison expression such as (a = b) ,but can also be a variable of the BOOLEAN datatype. The AND operator returns a value of true if both expressions each evaluate to true ; other- wise, a value of false is returned. Use AND when you need to test several conditions and execute some code only when they are all true . Table 3.7 shows some sample expres- sions using the AND operator. T ABLE 3.7 Expressions Using the AND Operator Expression Result (5 = 5) AND (4 < 100) AND (2 >= 2) true (5 = 4) AND (5 = 5) false ‘Mon’ IN (‘Sun’,’Sat’) AND (2 = 2) false OR The OR operator is used to join two comparison expressions when you are interested in testing whether at least one of them is true. It can also be used with two Boolean vari- ables to see whether at least one is set to true . The Syntax for the OR Operator boolean_expression OR boolean_expression In this syntax, boolean_expression can be any expression resulting in a Boolean, or true / false ,value. This is often a comparison expression such as (a = b) ,but can also be a variable of the BOOLEAN datatype. The OR operator returns a value of true if any one of the expressions evaluates to true . A value of false is returned only if both the expressions evaluate to false . Table 3.8 shows some sample expressions using the OR operator. S YNTAX S YNTAX 05 7982 ch03 11.8.00 11:22 AM Page 77 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. T ABLE 3.8 Expressions Using the OR Operator Expression Result (5 <> 5) OR (4 >= 100) OR (2 < 2) false (5 = 4) OR (5 = 5) true ‘Mon’ IN (‘Sun’,’Sat’) OR (2 = 2) true String Operators PL/SQL has two operators specifically designed to operate only on character string data. These are the LIKE operator and the concatenation ( || ) operator. The LIKE operator is a comparison operator used for pattern matching and was described earlier in the section titled “Comparison Operators,” so only the concatenation operator is described here. The Syntax for the Concatenation Operator string_1 || string_2 In this syntax, string_1 and string_2 are both character strings and can be either string constants, string variables, or a string expression. The concatenation operator returns a result consisting of all the characters in string_1 followed by all the characters in string_2 . Listing 3.6 shows several ways in which you can use the concatenation operator. L ISTING 3.6 Use of the Concatenation Operator 1: --Demonstrate the concatenation operator 2: DECLARE 3: a VARCHAR2(30); 4: b VARCHAR2(30); 5: c VARCHAR2(30); 6: BEGIN 7: --Concatenate several string constants. 8: c := ‘Jack’ || ‘ AND ‘ || ‘Jill’; 9: DBMS_OUTPUT.PUT_LINE(c); 10: --Concatenate both string variables and constants. 11: a := ‘went up’; 12: b := ‘the hill’; 13: DBMS_OUTPUT.PUT_LINE(a || ‘ ‘ || b || ‘,’); 14: --Concatenate two string variables. 15: a := ‘to fetch a ‘; 16: b := ‘pail of water.’; 17: c := a || b; 18: DBMS_OUTPUT.PUT_LINE(c); 19: END; 20: / 78 Day 3 , S YNTAX , I NPUT 05 7982 ch03 11.8.00 11:22 AM Page 78 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Writing PL/SQL Expressions 79 3 Jack and Jill went up the hill, to fetch a pail of water. PL/SQL procedure successfully completed. The preceding code shows the concatenation operator used in several different ways. Notice that you do not always have to assign the result directly to a string variable. For example, in line 13, the concatenation operator is used to create a string expression that is passed as input to the PUT_LINE procedure. Using Comparison Operators with Strings You can use any of the PL/SQL comparison operators to compare one character string to another. Strings can be compared for equality, for inequality, to see if one string is less than another, to see if one string matches a given pattern, and so on. When using charac- ter strings in comparison expressions, the result depends on several things: • Character set • Datatype • Case (upper versus lower) The Effect of Character Set on String Comparisons When comparing two strings to see if one is greater or less than another, the result depends on the sort order of the underlying character set being used. In the typical ASCII environment, all lowercase letters are greater than all uppercase letters, digits are less than all letters, and the other characters fall in various places depending on their corre- sponding ASCII codes. However, if you were working in an EBCDIC environment, you would find that all the digits were greater than the letters and all lowercase letters are less than all uppercase letters, so be careful. The Datatype’s Effect on String Comparisons The underlying datatype has an effect when comparing two string variables, or when comparing a string variable with a constant. Remember that variables of the CHAR datatype are fixed-length and padded with spaces. Variables of the VARCHAR2 datatype are variable-length and are not automatically padded with spaces. When com- paring two CHAR datatypes, Oracle uses blank-padded comparison semantics. This means that Oracle conceptually adds enough trailing spaces to the shorter string to make it equal in length to the longer string and then does the comparison. Trailing spaces alone will not result in any differences being found between two springs. Oracle also does the same thing when comparing two string constants. However, when one of the values in a O UTPUT A NALYSIS N EW T ERM 05 7982 ch03 11.8.00 11:22 AM Page 79 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. comparison is a variable-length string, Oracle uses non-padded comparison semantics. The use of non-padded comparison semantics means that Oracle does not pad either of the values with spaces, and any trailing spaces will affect the result. Listing 3.7 shows several string comparisons that illustrate this point. L ISTING 3.7 Demonstration of String Comparison Semantics 1: --Demonstrate string comparision semantics 2: DECLARE 3: fixed_length_10 CHAR(10); 4: fixed_length_20 CHAR(20); 5: var_length_10 VARCHAR2(10); 6: var_length_20 VARCHAR2(20); 7: BEGIN 8: --Constants are compared using blank-padded comparison semantics, 9: --so the trailing spaces won’t affect the result. 10: IF ‘Jonathan’ = ‘Jonathan ‘ THEN 11: DBMS_OUTPUT.PUT_LINE 12: (‘Constant: ‘’Jonathan’’ = ‘’Jonathan ‘’’); 13: END IF; 14: --Fixed length strings are also compared with blank-padded 15: --comparison semantic, so the fact that one is longer doesn’t matter. 16: fixed_length_10 := ‘Donna’; 17: fixed_length_20 := ‘Donna’; 18: IF fixed_length_20 = fixed_length_10 THEN 19: DBMS_OUTPUT.PUT_LINE(‘Char: ‘’’ || fixed_length_10 || ‘’’ = ‘’’ 20: || fixed_length_20 || ‘’’’); 21: END IF; 22: --Comparison of a fixed length string and a literal also 23: --results is the use of blank-padded comparison semantics. 24: IF fixed_length_10 = ‘Donna’ THEN 25: DBMS_OUTPUT.PUT_LINE(‘Char and constant: ‘’’ 26: || fixed_length_10 || ‘’’ = ‘’’ || ‘Donna’ || ‘’’’); 27: END IF; 28: --But compare a variable length string 29: --against a fixed length, and the 30: --trailing spaces do matter. 31: var_length_10 := ‘Donna’; 32: IF fixed_length_10 = var_length_10 THEN 33: DBMS_OUTPUT.PUT_LINE(‘Char and Varchar2: ‘’’ 34: || fixed_length_10 || ‘’’ = ‘’’ 35: || var_length_10 || ‘’’’); 36: ELSE 37: DBMS_OUTPUT.PUT_LINE(‘Char and Varchar2: ‘’’ 38: || fixed_length_10 || ‘’’ NOT = ‘’’ 39: || var_length_10 || ‘’’’); 40: END IF; 41: --The maximum lengths of varchar2 strings do not matter, 42: --only the assigned values. 80 Day 3 I NPUT 05 7982 ch03 11.8.00 11:22 AM Page 80 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Writing PL/SQL Expressions 81 3 43: var_length_10 := ‘Donna’; 44: var_length_20 := ‘Donna’; 45: IF var_length_20 = var_length_10 THEN 46: DBMS_OUTPUT.PUT_LINE(‘Both Varchar2: ‘’’ 47: || var_length_20 || ‘’’ = ‘’’ 48: || var_length_10 || ‘’’’); 49: ELSE 50: DBMS_OUTPUT.PUT_LINE(‘Both Varchar2: ‘’’ 51: || var_length_20 || ‘’’ NOT = ‘’’ 52: || var_length_10 || ‘’’’); 53: END IF; 54: END; 55: / Constant: ‘Jonathan’ = ‘Jonathan ‘ Char: ‘Donna ‘ = ‘Donna ‘ Char and constant: ‘Donna ‘ = ‘Donna’ Char and Varchar2: ‘Donna ‘ NOT = ‘Donna’ Both Varchar2: ‘Donna’ = ‘Donna’ PL/SQL procedure successfully completed. You can see from the output that the first three comparisons in Listing 3.7 use blank-padded comparison semantics. The strings being compared are considered to be equal even though the number of trailing spaces differs in each case. The fourth comparison, however, compares a VARCHAR2 variable against a CHAR variable. Because one of the strings in question is variable-length, the trailing spaces count, and the two strings are not considered to be equal. The Effect of Case on String Comparisons PL/SQL string comparisons are always case-sensitive. The obvious ramification of this is that a lowercase string such as ‘aaa’ is not considered equal to its uppercase equivalent of ‘AAA’ . But case also makes a difference when comparing two strings to see which is greater. In an ASCII environment, the letter ‘A’ will be less than the letter ‘B’ . However, the letter ‘a’ will not only be greater than ‘B’ ; it will be greater than ‘Z’ . O UTPUT A NALYSIS If you need to perform case-insensitive string comparisons, use PL/SQL’s built-in UPPER() function. For example: IF UPPER(‘a’) < UPPER(‘B’) THEN . You can use the LOWER() function in the same manner. Tip 05 7982 ch03 11.8.00 11:22 AM Page 81 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Use of Comparison Operators with Dates Date comparison works pretty much as you might expect and has fewer complexities than string comparisons do. Earlier dates are considered to be less than later dates, and it follows that more recent dates are greater than earlier dates. The only complication arises from the fact that PL/SQL date variables also contain a time component. Listing 3.8 illustrates this and another potential problem to be aware of when comparing date values against each other. L ISTING 3.8 Date Comparison Example 1: --Demonstrate date comparisions 2: DECLARE 3: payment_due_date DATE; 4: BEGIN 5: --In real life the payment_due date might be read from 6: --a database or calculated based on information from a database. 7: payment_due_date := TRUNC(SYSDATE); 8: --Display the current date and the payment date. 9: DBMS_OUTPUT.PUT_LINE(‘Today is ‘ || TO_CHAR(SYSDATE,’dd-Mon-yyyy’)); 10: DBMS_OUTPUT.PUT_LINE(‘Payment is due on ‘ 11: || TO_CHAR(payment_due_date,’dd-Mon-yyyy’)); 12: IF payment_due_date = SYSDATE THEN 13: DBMS_OUTPUT.PUT_LINE(‘Payment is due today.’); 14: ELSE 15: DBMS_OUTPUT.PUT_LINE(‘Payment can wait a while.’); 16: END IF; 17: --In reality, the time does not matter when speaking of a due date. 18: IF TRUNC(payment_due_date) = TRUNC(SYSDATE) THEN 19: DBMS_OUTPUT.PUT_LINE(‘Wrong! Payment is due today!’); 20: ELSE 21: DBMS_OUTPUT.PUT_LINE(‘Wrong! Payment can wait a while.’); 22: END IF; 23: END; 24: / Today is 01-Jun-1997 Payment is due on 01-Jun-1997 Payment can wait a while. Wrong! Payment is due today! PL/SQL procedure successfully completed. Today’s date and the payment due date both match, yet the IF statement in line 12 failed to detect this. Why? Because SYSDATE is a function that returns the cur- rent date and time, with the time resolved down to the second. The payment_due_date variable will contain a time of midnight because the TRUNC function was used when the 82 Day 3 I NPUT O UTPUT A NALYSIS 05 7982 ch03 11.8.00 11:22 AM Page 82 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Writing PL/SQL Expressions 83 3 due date was set. See line 7. The only time that line 12 would function correctly would be for one second at midnight each day. In line 18, the TRUNC function is used to truncate the time values from the two dates, resulting in a comparison that works as desired in this case. Admittedly this is a contrived example, but it does illustrate the problem. Be especially careful comparing dates read from the database. Sometimes they have time components that you don’t expect. Even if programmers aren’t supposed to store a time, it’s a pretty easy mistake to make. Tip Having the time as part of a date variable is not necessarily a bad thing. It’s just some- thing you need to be aware of, especially when comparing dates with each other. Exploring Expressions When you combine values and operators to produce a result, you have an expression. You have already learned about the various datatypes available in PL/SQL and PL/SQL’s extensive collection of operators. In addition, in order to use expressions effectively in your code, you also need to understand • Operator precedence •Use of parentheses •Types of expressions • The effects of null values in an expression • Conversion between datatypes Understanding the effects of a null value on an expression is particularly important, especially when you move into retrieving data from a database. The remainder of this chapter discusses each of these items in detail. Expressions Defined Simply put, an expression is some combination of variables, operators, literals, and func- tions that returns a single value. Operators are the glue that hold an expression together and are almost always present. The other elements might not all be present in every expression. In its very simplest form, an expression might simply consist of a literal value, a variable name, or a function call. The first few entries in Table 3.9 are examples of this type of expression. More typical expressions involve two values and an operator, with the opera- tor defining the action to be taken and the result to be returned. Complex expressions 05 7982 ch03 11.8.00 11:22 AM Page 83 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. can be built up by stringing several simple expressions together with various operators and function calls. Finally, the unary operators can be applied to any expression or value. T ABLE 3.9 Sample Expressions Expression Comments 1000 Evaluates to one thousand some_variable_name Evaluates to the contents of the variable SYSDATE An Oracle function that returns the current date 1000 + 2000 A typical expression using a binary operator -1000 An expression using a unary operator 10 * 20 + 30 / 2 Two expressions joined together LENGTH(‘Lansing ‘ || ‘MI’) A function call evaluating a sub-expression is itself an expression 1-5**2<=10*4-20 Two expressions, each containing sub-expressions, joined together Take a look at the last example in Table 3.9. The comment notes that it is actually two expressions joined together, but which two? What value should Oracle return for this expression? The answer to both these questions can be found in the rules governing oper- ator precedence. Operator Precedence When evaluating an expression consisting of different values, datatypes, and operators, Oracle follows a specific set of rules that determine which operations are done first. Each operator has an assigned precedence. Operators with a higher precedence are evaluated first. Operators of the same precedence level are evaluated from left to right. Table 3.10 shows these precedence levels for each of the various operators. 84 Day 3 05 7982 ch03 11.8.00 11:22 AM Page 84 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Writing PL/SQL Expressions 85 3 T ABLE 3.10 Operator Precedence Precedence Operators Operation First ** , NOT Exponentiation and logical negation Second + , - Arithmetic identity and negation ( + and - used as unary operators) Third * , / Multiplication and division Fourth + , - , || Addition, subtraction, and string concate- nation Fifth = , <> , != , ~= , < , Comparison > , <= , >= , LIKE , BETWEEN , IN , IS NULL Sixth AND Logical conjunction Seventh OR Logical inclusion Take another look at the expression referred to in the previous section. The following list shows the steps Oracle would take to evaluate it: 1. 1-5**2<=10*4-20 2. 1-25<=10*4-20 3. 1-25<=40-20 4. -24<=20 5. true You can control the order in which Oracle evaluates an expression by using parentheses. Oracle will evaluate any part of an expression in parentheses first. If parentheses are nested, Oracle will always evaluate the innermost expression first and then move out- wards. Here is what happens to the preceding expression if you add some parentheses: 1. (1-5)**2<=10*(4-20) 2. (-4)**2<=10*(-16) 3. 16<=-160 4. false 05 7982 ch03 11.8.00 11:22 AM Page 85 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Types of Expressions One way of classifying expressions is by the datatype of the resulting value. Using this scheme, expressions can be classified as one of these types: •Arithmetic or numeric • Boolean •String • Date Any expression returning a numeric value is referred to as an arithmetic expression,or sometimes as a numeric expression. A Boolean expression is any expression that returns a true or false value. Comparison expressions are really special cases of this type, but they are not the only way to get a true / false value. A Boolean variable—or several Boolean variables linked together with the logical operators AND , OR , and NOT —will also return a Boolean result. String expressions are those that return character strings as results, and date expressions are those that result in a date-time value. Generally speaking, you can use an expression of the appropriate datatype anywhere in your PL/SQL code where a value is required. The exception to this would be in function and procedure calls that modify their arguments. Null Values in Expressions Until now, the discussion has ignored the effect of nulls in expressions. This was done in order to concentrate on the normal function of each of the operators and also because nulls pretty much have the same effect regardless of the operation being done. What is a null? The term is best understood as referring to an unknown value. Any vari- able or expression is considered null when the value of that variable or expression is unknown. This situation can occur if you declare a variable and use it in an expression without first assigning a value. Because the variable has no assigned value, the result of the expression can’t be known. More commonly, nulls are encountered when reading data from a database. Oracle, like any other relational database, does not force you to 86 Day 3 Use parentheses in complex expressions, even when they are not strictly nec- essary, in order to make the intended order of evaluation clear to other pro- grammers. Tip 05 7982 ch03 11.8.00 11:22 AM Page 86 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... true if that is the case Q When I am comparing strings, especially when comparing a CHAR string to a VARCHAR2 string, is there a convenient way to tell PL/SQL to ignore any trailing spaces in the CHAR string? A Yes Use the built -in RTRIM function For example: IF RTRIM(char_string) = varchar2_string then Q I’m comparing two dates and only want to know if they are in the same year Can I use the TRUNC function... value of pi is 3.14 Finding Errors In Day 1, you learned how to use the EDIT command directly from Oracle Instead of entering the code line by line, you can now practice using the EDIT command To show you how to debug compilation errors, I am going to make extensive use of the built -in editor If you haven’t done so already, you are going to enter the mypi function into the editor, including planned errors... calculating the diameter of a circle, you would then pass the value of the radius Using Functions, IF Statements, and Loops 107 The next line requires the return type In this case, you are returning a NUMBER The next line to enter is RETURN NUMBER IS You now need to start the body of your function by typing the keyword BEGIN: BEGIN Because you are not performing anything in this function except returning... first assignment, in line 11, causes no conversion at all because a string is assigned to a string variable The assignment statement in line 14, however, does represent an implicit conversion because it must convert the string representation of the date to Oracle’s internal format before it can assign the value to d1 In line 19, that date is again converted back to a string format Lines 23 through 28... the NOCOPY hint in the parameter mode statement When you use the NOCOPY hint, you give instructions, not directives, to the compiler to pass parameters by reference and not by value Note NOCOPY is a hint and not a directive Therefore, the PL/SQL engine can choose to ignore your request and do what it thinks is the correct behavior One thing to consider when using the NOCOPY hint is the resulting value... “Learning the Basics of PL/SQL, ” functions are similar to PL/SQL procedures except for the following differences: • Functions return a value • Functions are used as part of an expression Why should you write functions? You have many reasons The main reason is to reduce the total lines of coding and take a modular approach to writing code You can retype in each PL/SQL block the same repetitive lines... Listing 3.9 show an interesting use of the NVL function to account for the possibility of the variable n being null You can read more about NVL in Appendix B The built -in SQL DECODE function actually treats null as a specific value instead of an unknown value It might seem contradictory, but it’s useful DECODE is also described in Appendix B DO DON’T Do initialize all your variables in order to eliminate... are now ready to enter a block of PL/SQL code to see actual output and the passing of parameters Enter and then execute the code in Listing 4.7 Using Functions, INPUT IF Statements, and Loops 111 LISTING 4.7 Passing Parameters to squareme BEGIN DBMS_OUTPUT.PUT_LINE(‘9 squared is ‘ || squareme(9) ); END; Your output should be OUTPUT 9 squared is 81 One last word on passing values to a function: Values... number or a date to a character string Each of these functions takes three arguments: the value to be converted, a format string specifying how that conversion is to take place, and optionally a string containing language-specific parameters These functions are described in detail on Day 6, but Listing 3.11 gives some common examples of how you can use them INPUT LISTING 3.11 Examples of the Conversion... parameter value in memory If the variables or expressions are declared in the subprogram specification and referenced in the subprogram body, the parameters are considered formal In this case, a pointer to the real parameter value resides in memory SYNTAX Using Functions, IF Statements, and Loops 103 The Syntax for Defining a Parameter parameter_name [MODE] parameter_type [:= value | DEFAULT value] In this . string_1 || string_2 In this syntax, string_1 and string_2 are both character strings and can be either string constants, string variables, or a string. comparing strings, especially when comparing a CHAR string to a VARCHAR2 string, is there a convenient way to tell PL/SQL to ignore any trail- ing spaces in

Ngày đăng: 07/11/2013, 20:15

TỪ KHÓA LIÊN QUAN