LAB 3.1 Exercise Answers
This section gives you some suggested answers to the questions in Lab 3.1, with discussion related to how those answers resulted. The most important thing to realize is whether your answer works. You should figure out the implications of the answers here and what the effects are from any different answers you may come up with.
Why does PL/SQL have so many different types of characters? What are they used for?
Answer:The PL/SQL engine recognizes different characters as having different meaning and therefore processes them differently. PL/SQL is neither a pure mathematical language nor a spoken language, yet it contains elements of both. Letters will form various lexical units such as identifiers or key words, mathematic symbols will form lexical units known as delimiters that will perform an operation, and other symbols, such as /*, indicate comments that should not be processed.
What would be the equivalent of a verb and a noun in English in PL/SQL? Do you speak PL/SQL?
Answer:A noun would be similar to the lexical unit known as an identifier.A verb would be similar to the lexical unit known as a delimiter. Delimiters can simply be quotation marks, but others perform a function such as to multiply "*".
If you ran the previous example in a SQL*Plus, what would be the result?
Answer:Assuming SET SERVEROUTPUT ONhad been issued, you would get only born on.The reason is that the variables v_nameand v_dobhave no values.
Run the example and see what happens. Explain what is happening as the focus moves from one line to the next.
Answer:Three variables are declared.When each one is declared, its initial value is null. v_nameis set as a varchar2VARCHAR2 with a length of 30, v_dobis set as a character type date, and v_us_citizenis set to BOOLEAN. Once the executable section begins, the variables have no value and, therefore, when the DBMS_OUTPUT is told to print their values, it prints nothing.
This can be seen if the variables were replaced as follows: Instead of v_name, use NVL(v_name, 'No Name') and instead of v_dob use NVL (v_dob, '01-Jan-1999'). Then run the same block and you will get
No Name born on 01-Jan-1999
In order to make use of a variable, you must declare it in the declaration section of the PL/SQL block. You will have to give it a name and state its data type. You also have the option to give your variable an initial value. Note that if you do not assign a variable an initial value, it will be null. It is also possible to constrain the declaration to "not null," in which case you must assign an initial value. Variables must first be declared and then they can be referenced. PL/SQL does not allow forward references. You can set the variable to be a constant, which means it cannot change.
What would happen if you ran the above PL/SQL block? Would you receive an error message? If so, explain.
Answer: In this example, you declare a variable called exception. Next, you initialize this variable and display its value on the screen.
This example illustrates an invalid use of reserved words.To the PL/SQL compiler,"ex-ception" is a reserved word and it denotes the beginning of the exception-handling sec-tion.As a result, it cannot be used to name a variable. Consider the huge error message produced by this tiny example.
exception VARCHAR2(15); * ERROR at line 2: ORA-06550: line 2, column 4: PLS-00103: Encountered the symbol "EXCEPTION" when expecting one of the following: begin function package pragma procedure subtype type use <an identifier> <a double-quoted delimited-identifier> cursor form current The symbol "begin was inserted before "EXCEPTION" to continue. ORA-06550: line 4, column 4: PLS-00103: Encountered the symbol "EXCEPTION" when expecting one of the following: begin declare exit for goto if loop mod null pragma raise return select update while <an identifier> <a double-quoted delimited-identifier> <a bin ORA-06550: line 5, column 25: PLS-00103: Encountered the symbol "EXCEPTION" when expecting one of the following: ( ) - + mod not null others <an identifier> <a double-quoted delimited-identifier> <a bind variable> avg count current exists max min prior sql s ORA-06550: line 7, column 0: PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: begin declare end exception exit for goto if loop
Here is a question you should ask yourself: If you did not know that the word "exception" is a reserved word, do you think you would attempt to debug the preceding script after looking at this error message? I know I would not.
What would happen if you ran the preceding PL/SQL block?
Answer: In this example, you declare and initialize three numeric variables.The first declaration and initialization (v_var1 NUMBER(2) := 123) causes an error because the value 123 exceeds the specified precision.The second variable declaration and initialization (v_var2 NUMBER(3) := 123) does not cause any errors because the value 123 corresponds to the specified precision.The last declaration and initialization (v_var3 NUMBER(5,3) := 123456.123) causes an error because the value 123456.123 exceeds the specified precision.As a result, this example produces the following output:
DECLARE * ERROR at line 1: ORA-06502: PL/SQL: numeric or value error ORA-06512: at line 2
In the previous example, what has been declared? State the data type and value.
Answer:The variable v_name was declared with the identical data type as the column first_name from the database table STUDENT - varchar2(25).Additionally, the variable v_grade was declared the identical data type as the column grade_numeric on the grade database table number NUMBER(3). Each has a value of null.
Most Common Data Types
Stores variable-length character data.
Takes a required parameter that specifies a maximum length up to 32,767 bytes.
Does not use a constant or variable to specify the maximum length; an integer literal must be used.
The maximum width of a VARCHAR2 database column is 4000 bytes.
Stores fixed-length (blank-padded if necessary) character data.
Takes an optional parameter that specifies a maximum length up to 32,767 bytes.
Does not use a constant or variable to specify the maximum length; an integer literal must be used. If maximum length is not specified, it defaults to 1.
The maximum width of a CHAR database column is 2000 bytes; the default is 1 byte.
Stores fixed or floating-point numbers of virtually any size.
Precision is the total number of digits.
Scale determines where rounding occurs.
It is possible to specify precision and omit scale, in which case scale is 0 and only integers are allowed.
Constants or variables cannot be used to specify precision and scale; integer literals must be used.
Maximum precision of a NUMBER value is 38 decimal digits.
Scale can range from -84 to 127.
For instance, a scale of 2 rounds to the nearest hundredth (3.456 becomes 3.46).
Scale can be negative, which causes rounding to the left of the decimal point. For example, a scale of -3 rounds to the nearest thousandth (3456 becomes 3000). A scale of zero rounds to the nearest whole number. If you do not specify the scale, it defaults to zero.
Stores signed integer variables.
Compares to the NUMBER data type. BINARY_INTEGER variables are stored in the binary format, which takes less space.
Calculations are faster.
Can store any integer value in the range -2,147,483,747 through 2,147,483,747.
This data type is primarily used for indexing a PL/SQL table. This will be explained in more depth in Chapter 16, "PL/SQL Tables." You cannot create a column in a regular table of binary_integer type.
Stores fixed-length date values.
Valid dates for DATE variables include January 1, 4712 B.C. to De-cember 31, A.D. 9999.
When stored in a database column, date values include the time of day in seconds since midnight. The date portion defaults to the first day of the current month; the time portion defaults to midnight.
Dates are actually stored in binary format and will be displayed according to the default format.
This is a new data type introduced with Oracle 9i. It is an extension of the DATE data type. It stores fixed-length date values with precision down to a fraction of a second with up to 9 places after the decimal (the default is 6). Here is an example of the default this displays for this data type: '12-JAN-2002 09.51.44.000000 PM'
The "with timezone" or "with local timezone" option allows the TIMESTAMP to be related to a particular time zone. This will then be adjusted to the time zone of the database. For example, this would allow a global database to have an entry in London and New York recorded as being the same time even though it will display as noon in New York and 5 P.M. in London.
Stores the values TRUE and FALSE and the nonvalue NULL. Recall that NULL stands for a missing, unknown, or inapplicable value.
Only the values TRUE and FALSE and the nonvalue NULL can be assigned to a BOOLEAN variable.
The values TRUE and FALSE cannot be inserted into a database column.
Stores variable-length character strings.
The LONG data type is like the VARCHAR2 data type, except that the maximum length of a LONG value is 2 gigabytes.
You cannot select a value longer than 4000 bytes from a LONG column into a LONG variable.
LONG columns can store text, arrays of characters, or even short documents. You can reference LONG columns in UPDATE, INSERT, and (most) SELECT statements, but not in expressions, SQL function calls, or certain SQL clauses, such as WHERE, GROUP BY, and CONNECT BY.
Stores raw binary data of variable length up to 2 gigabytes.
LOB (Large Object)
There are four types of LOBS: BLOB, CLOB, NCLOB, and BFILE. These can store binary objects, such as image or video files, up to 4 gigabytes in length.
A BFILE is a large binary file stored outside the database. The maximum size is 4 gigabytes.
Internally, every Oracle database table has a ROWID pseudocolumn, which stores binary values called rowids.
Rowids uniquely identify rows and provide the fastest way to access particular rows.
Use the ROWID data type to store rowids in a readable format.
When you select or fetch a rowid into a ROWID variable, you can use the function ROWIDTOCHAR, which converts the binary value into an 18-byte character string and returns it in that format.
Extended rowids use a base 64 encoding of the physical address for each row. The encoding characters are AZ, az, 09, +, and /. Row ID in Oracle 9i is as follows: OOOOOOFFFBBBBBBRRR. Each component has a meaning. The first section, OOOOOO, signifies the database segment. The next section, FFF, indicates the tablespace-relative datafile number of the datafile that contains the row. The following section, BBBBBB, is the data block that contains the row. The last section, RRR, is the row in the block (keep in mind that this may change in future versions of Oracle).
What will the output be for the preceding script? Explain what is being declared and what the value of the variable is throughout the scope of the block.
Answer:The server output will be
I ate 2 cookies with 600 calories. I really ate 3 cookies with 900 calories. The truth is, I actually ate 8 cookies with 2400 calories. PL/SQL procedure successfully completed.
Initially the variable v_cookies_amtis declared to be a NUMBER with the value of 2, and the variable v_calories_per_cookieis declared to be a CONSTANT NUMBER with a value of 300 (since it is declared to be a tCONSTANT, it will not change its value). In the course of the procedure, the value of v_cookies_amt is later set to be 3, and then finally it is set to be its current value, 3 plus 5, thus becoming 8.
In the previous example, add the following expressions to the beginning of the procedure, then explain the values of the variables at the beginning and at the end of the script.
Answer: Initially the variable v_lnameis declared as a data type VARCHAR2 with a length of 30 and a value of null.The variable v_regdateis declared as data type date with a value of null.The variable v_pctincris declared as CONSTANT NUMBER with a length of 4 and a precision of 2 and a value of 1.15.The variable v_counteris declared as NUMBER with a value of 0.The variable v_YorNis declared as a variable of BOOLEAN data type and a value of TRUE.
The output of the procedure will be as follows (make sure you have entered SET SERVEROUTPUT ON earlier on in your SQL*Plus session):
1 1200 PL/SQL procedure successfully completed.
Once the executable section is complete, the variable v_counterwill be changed from null to 1.The value of v_new_costwill change from null to 1200 (800 times 1.50).
Note that a common way to find out the value of a variable at different points in a block is to add a DBMS_OUTPUT.PUT_LINE(v_variable_name); throughout the block.
What will the values of the variables be at the end of the script?
If the following example were run in SQL*Plus, what do you think would be displayed?
Answer:The following would result:
outer student id is 123 inner student id is 125 When am I displayed? outer student id is 123 PL/SQL procedure successfully completed.
Now run the example and see if it produces what you expected. Explain how the focus moves from one block to another in this example.
Answer:The variable e_Show_Exception_Scopeis declared as an exception type in the declaration section of the block.There is also a declaration of the variable called v_student_idof data type NUMBER that is initialized to the number 123.This variable has a scope of the entire block, but it is visible only outside of the inner block. Once the inner block begins, another variable, named v_student_id, is declared.This time it is of data type VARCHAR2(8) and is initialized to 125.This variable will have a scope and visibility only within the inner block.The use of DBMS_ OUTPUT helps to show which variable is visible.The inner block raises the exception e_Show_Exception_Scope; this means that the focus will move out of the execution section and into the exception section.The focus will look for an exception named e_Show_Exception_Scope. Since the inner block has no exception with this name, the focus will move to the outer block's exception section and it will find the exception.The inner variable v_student_idis now out of scope and visibility.The outer variable v_student_id(which has always been in scope) now regains visibility. Because the exception has an IF/THEN construct, it will execute the DBMS_ OUTPUT call.This is a simple use of nested blocks. Later in the book you will see more complex examples. Once you have covered exception handling in depth in Chapters 7, 10, and 11, you will see that there is greater opportunity to make use of nested blocks.
Answer:The value of v_counterwill then change from 1 to 6, which is ((1 + 5) *2))/2, and the value of new_costwill go from 1200 to 1800, which is (800 * 6)/4.The output from running this procedure will be:6 1800 PL/SQL procedure successfully completed.
Operators (Delimiters): the Separators in an ExpressionArithmetic ( ** , * , / , + , -) Comparison( =, <> , != , < , > , <= , >= , LIKE , IN , BETWEEN , IS NULL ) Logical ( AND, OR, NOT ) String ( ||, LIKE ) Expressions Operator Precedence ** , NOT +, - ( arithmetic identity and negation ) *, / + , - , || =, <>, != , <= , >= , < , > , LIKE, BETWEEN, IN, IS NULL ANDlogical conjunction ORlogical inclusion