Вы находитесь на странице: 1из 10

Learning PL/SQL Variables are used in all programming languages to store and manipulate data.

In PL/SQL, yu can use variables to store information from a database table and then perform calculations on it. Variables provide: 1. Reusability Variables can be reused. You can refer to a variable in executable section as often you need. 2. Temporary storage You must first declare a variable in declaration section of your PL/SQL code. When you declare a variable, a temporary storage area is allocated in memory. You use this memory area to store data temporarily. 3. The ability to manipulate data Once you have declared a variable, you can manipulate the value of the data it holds in the execution section of your PL/SQL code. Identifiers are used to name PL/SQL objects such as variables, types, cursors, and subprograms. A variable is essentially a data storage location. An identifier is used to name and reference a variable. Variable identifier must start with a letter. Variables can include numbers, letters and special characters such as $, _, and pound sign. PL/SQL variables are not case-sensitive PL/SQL variables can not be longer than 30 characters. You can not use PL/SQL reserved words. You must assign a data type to every variable you declare. The data type is used to specify: the storage format of the data and any constraints that are to be placed on a variable's value. Data type specifies the range of valid values a variable can hold. PL/SQL has five data type categories: 1. bind Some times called host variables. Bind variables are non-PL/SQL variables in the sense that they are created in the host environment. They are declared outside a PL/SQL block and they can be used by multiple PL/SQL subprograms. 2. Composite Composite types can hold both single and multiple values, such as entire database record. Some what similar to structs in C. 3. large object (LOB) LOB data type is used to store a large amount of information, such as database column. This type is generally useful for referring to large files, such as movie file, that exist outside the database.

4. Reference Reference data types to store pointers, which point to storage locations. You might use a pointer to point to a particular row in a table. 5. Scalar Scalar data types hold a single value only, such as a string or a number. The value of a scalar variable depends on its data type. Like, VARCHAR2, NUMBER, BOOLEAN, etc. You must declare all variables, apart from bind variables, in the declarative section of PL/SQL code before you can reference it in the executable section. It is good practice to initialize a variable by assigning it a value in the declarative section. However, you can assign or change a variable's value in the executable section. You can also use variables as parameters in subprograms or to hold values returned by functions. Syntax used to declare a variable: <identifier> CONSTANT <data_type> NOT NULL :=| DEFAULT expr

<identifier> clause is mandatory and it should be unique. Ex: manager_id VARCHAR2; CONSTANT clause is optional. You must initialize variables declared with CONSTANT clause in the declarative section, not in the executable section. Ex: c_comm CONSTANT NUMBER := 1400; <data_type> is mandatory. You must specify a data type when declaring a variable. It can be a scalar, composite, reference or LOB data type. Ex: location VARCHAR2; NOT NULL clause is optional. This is to ensure that a variable cannot contain a NULL value. You must initialize variables declared with the NOT NULL clause in the declarative section. Ex: emp_deptno NUMBER(2) NOT NULL := 10; :=| DEFAULT expr It is good practice to initialize a variable in the declarative section. You use the := assignment operator to assign a variable to the value specified in expr. You can alternatively use the DEFAULT statement to assign a default value to the variable. You can change a variable's default or initial value in the executable section. Ex: location VARCHAR2 DEFAULT 'Atlanta' String literals in PL/SQL must be enclosed by single quotes. Ex: my_name VARCHAR2(20) := 'John'; You use the DBMS_OUTPUT.PUT_LINE command to output a value. Ex: DBMS_OUTPUT.PUT_LINE('My name is: ' || my_name);

Guidelines when declaring and initializing variables: Delimit string literals: If you want to use a single quote in a string literal, you must include an extra quotation mark as an escape character. Alternatively, you can use the q notation. Ex: event1 VARCHAR2(20) := 'Father''s day'; event2 VARCHAR2(20) := q'%Father's day%'; You should avoid naming a variable after a table column. When you reference a variable with a table column name in SQL, the Oracle Server assumes you are referencing the column rather than the variable, which can result in errors. Four categories of scalar data type: a. Character b. Date c. Number d. Boolean Text and Number data types: BINARY_INTEGER : similar to signed int in C. ( 4byte signed int) Calculations performed on BINARY_INTEGER variables are faster than on NUMBER variables, although it is not as efficient as the PLS_INTEGER type. Ex: count_loop BINARY_INTEGER := 0; CHAR : 2 byte char. Used to hold fixed-length character data. However it is recommended to use VARCHAR2 data type to hold character data. You can specify a maximum length, or accept the default of 1 character. Syntax: CHAR[(max_length)] Ex: dept_name CHAR(8) := 'Accounts'; NUMBER: data type to hold interger, fixed or floating-point numeric values. You can specify precision, which is the number of significant digits the variable can hold, and scale, which is the number of digits to the left or right of the decimal point. Syntax: NUMBER[(precision, scale)] Ex: c_tax_rate CONSTANT NUMBER(3, 2) : = 8.25; PLS_INTEGER : signed integer values between -2^31 and 2^31. Variables of this data type requires less storage than NUMBER and BINARY_INTEGER variables. Calculations performed on them are also faster. Ex: count_loop PLS_INTEGER := 0; VARCHAR2(max_length) : data type to hold variable length character data. There is no default maximum character length. You must specify the length manually. Ex: dept_name VARCHAR2(9) := 'Accounts';

Oracle Database 10g includes two data types to represent floating point numbers. BINARY_DOUBLE 9bytes. Literals of this type end with d, like 140d. BINARY_FLOAT 5bytes. Literals of this type end with f, like 35f. Use these data types to perform scientific calculations. Date and Time data types: DATE: data type to hold 7-byte fixed length date time value. DATE variables hold, year, month, day, hour, minute and second information. Ex: orderdate DATE := SYSDATE + 7; SYSDATE is a PL/SQL function. TIMESTAMP : data type is an extension of the DATE data type. It also includes fractions of a second. You have the option to specify the number of digits in the fractional section, or accept the default of 6. Ex: orderdate TIMESTAMP(5) := SYSDATE + 7; TIMESTAMP WITH LOCAL TIME ZONE : data type is an extension of the TIMESTAMP data type. Regards the date time as belonging to the local time zone. In PL/SQL, the local time zone is the same as the session time zone. TIMESTAMP WITH TIME ZONE : extension of the TIMESTAMP data type. It includes the difference in hours and minutes between local time and UTC time. Ex: orderdate TIMESTAMP WITH TIME ZONE := SYSDATE + 7; BOOLEAN type: typically used in logical calculations. Three possible values: TRUE, FALSE, or NULL. NULL value represents an inapplicable or unknown value. Ex: valid BOOLEAN NOT NULL := TRUE; What if the data type and precison of a table column do not match the data type of a variable holding a value from the column???? Solution: Rather than explicitly declaring a variable's data type, you can use %TYPE attribute to anchor the variable's data type so that it matches that of a table column. This avoids errors caused by mismatching data types, and additionally allows you to change table column definitions without having to update your code. The %TYPE attribute also overrides the NOT NULL constraint in the table columns. Even if the source column includes the constraint, the variable can still contain the NULL value. You can also use the %TYPE attribute to anchor a variable's data type to a variable previously declared in the same code block, or to a global variable.

Syntax: <identifier> <anchor_variable/table_column_name>%TYPE; First, name the variable using a unique identifier. Then instead of explicitly stating a data type, you specify the source table and column name, or alternatively the name of a previously declared variable. Finally, you append the %TYPE attribute. Ex: emp_lname employess.last_name%TYPE; - the variable's type is inherited from the last_name column in the employees table. balance NUMBER(7,2); min_balance balance%TYPE := 1000; You use Boolean variables with the operators AND, OR, and NOT to test validity of an expression. DBMS_RANDOM.VALUE() - this function returns a randomly generated number between zero and one. := --> assignment operator = --> equality test operator Small Example: DECLARE rand NUMBER; result BOOLEAN; BEGIN rand := DBMS_RANDOM.VALUE(); IF rand > 0.5 THEN result := true; ELSE result := false; END IF; IF result = true THEN DBMS_OUTPUT.PUT_LINE('The result was true'); ELSE DBMS_OUTPUT.PUT_LINE('The result was false'); END IF; END;

Bind Variables: Declared outside PL/SQL block. Typically, they are created in host environment and are also called host variables. Can be used in multiple PL/SQL programs. Any variables scalar variables declared in PL/SQL block are avaiable only when you execute the block. When block executes, the memory used by the variable is freed. However, bind variables are accessible even after the block is executed. These variables can be passed as runtime values into or out of PL/SQL subprograms. Can be used and manipulated by multiple subprograms used in SQL statement and PL/SQL blocks. Syntax: VARIABLE <identifier> <data_type> Ex: VARIABLE emp_salary NUMBER; To create a bind variable, you use the VARIABLE command. Bind variables must have an identifier. The data type of the bind variable must be specified. Bind variables are referenced by preceding the variable name with a colon. Bind variable can be used in any SQL statement or PL/SQL program. Ex: VARIABLE emp_salary NUMBER BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = 120; END; PRINT emp_salary DEFINE : command can be used to create a user variable. It specifies teh value of a user variable. Variables should be CHAR type only. These user variables can be used many times in the same PL/SQL block. These user variables can be referenced same way as substituion variables, like preceding & with the variable.

Control Statements: Conditional control enables you to control the execution of statements in a block of PL/SQL code. You can direct the control of execution through your program using IF and CASE statements. IF statements enable you to perform actions selectively, based on specified conditions. 3 distinctive IF logic structures: 1. IF THEN END IF; 2. IF THEN ELSE END IF; 3. IF THEN ELSIF ELSE END IF; You can use an IF THEN statement to test a particular condition. In the syntax of a standard IF THEN statement, the condition is a Boolean variable or expression that results in TRUE, FALSE or NULL. IF <condition> THEN ....executable statements.... END IF; IF THEN ELSE is based on either/or logic, one of the statements will always be executed. You can only have one ELSE keyword in an IF statement. IF condition1 THEN statements1 ELSIF conditionN THEN statementsN [ELSE else statements] END IF;

CASE control structures Alternative to IF ELSIF statement. More compact way of writing code to check for multiple conditions. 2 types of CASE controls: CASE statement : evaluates a condition and performs an action. Like, switch. End with END CASE; 2 types of CASE statements: Simple CASE statement : Associates PL/SQL statements with a value. It chooses which sequence of statements to be executed based on expression that returns one of those values. CASE employee_dept WHEN 'W' THEN award_salary_bonus(employee_id); WHEN 'M' THEN award_montly_bonus(employee_id); ELSE RAISE invalid_employee_type; END CASE; Searched CASE statement : evaluating a list of Boolean conditions. The statement associated with the first condition that results in TRUE is executed. CASE WHEN salary >= 10000 AND salary <= 20000 THEN given_bonus(employee_id, 1500); WHEN salary > 20000 AND salary <= 40000 THEN give_bonus(employee_id, 500); ELSE give_bonus(employee_id, 0); END CASE; CASE expression : evaluates a condition and returns a value. End with END; Usually used with SQL statements. 2 types: Simple CASE expression : cannot contain any operators and you can only compare one value(scalar value) SELECT ename, empno, (CASE dept_no WHEN 10 THEN 'Accounts' WHEN 20 THEN 'Sales' ELSE 'Unknown' END) department FROM emp ORDER BY ename;

Searched CASE expression Simple CASE statements enable you to choose which of several sequences of stmts to execute based on results of an expression/selector. Simple CASE expression selects a result and returns it. Simple CASE expressions compare only one value and cannot contain any comparison operators. Searched CASE controls work using comparisons. The WHEN clause is used to perform the comparisons. Searched CASE statements do not have a selector defined. It evaluates a list of Boolean expressions. Always specify the ELSE part explicitly when you use a searched CASE statement. Searched CASE expression does not use a selector. Nor does the searched CASE expression have a test expression. Instead, the WHEN clause contains an expressin that returns a Boolean value. Loops in PL/SQL three main types: 1. basic loops like do while loop. Execute at least once. LOOP statement1 .... EXIT [WHEN condition] END LOOP; 2. WHILE loop loop based on condition. WHILE condition LOOP statement1; statement2; ..... END LOOP; 3. FOR loops loops based on a count. You must specify a range of numbers that a counter value must step through.

Writing FOR loops in PL/SQL: If you have one or more statements you want to execute repeatedly for a set number of iterations, you can use a FOR loop. Syntax: FOR <counter> IN <lower_bound> .. <upper_bound> LOOP statement1; statement2; ..... END LOOP; lower bound and upper bound are included in the loop range. Lower bound must always be lower than the upper bound. Ex: FOR i IN 3..6 LOOP statement1; END LOOP; In the above, the counter variable i, doesn't need to be declared earliers, as it is declared implicitly. Counter variable should only be referenced within the loop, it is undefined outside the loop. When specifying a label for a loop, the name must be included in label delimiters, like below: <<outer_loop>>, <<inner_loop>> If you have labeled your loop, you can optionally include the label names after the END LOOP; statements.

Вам также может понравиться