my blogger site

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Tuesday, 17 March 2015

The string in PL/SQL is actually a sequence of characters with an optional size specification. The characters could be numeric, letters, blank, special characters or a combination of all. PL/SQL offers three kinds of strings:
  • Fixed-length strings: In such strings, programmers specify the length while declaring the string. The string is right-padded with spaces to the length so specified.
  • Variable-length strings: In such strings, a maximum length up to 32,767, for the string is specified and no padding takes place.
  • Character large objects (CLOBs): These are variable-length strings that can be up to 128 terabytes.
PL/SQL strings could be either variables or literals. A string literal is enclosed within quotation marks. For example,
'This is a string literal.' Or 'hello world'
To include a single quote inside a string literal, you need to type two single quotes next to one another, like:
'this isn''t what it looks like'

Declaring String Variables

Oracle database provides numerous string datatypes , like, CHAR, NCHAR, VARCHAR2, NVARCHAR2, CLOB, and NCLOB. The datatypes prefixed with an 'N' are 'national character set' datatypes, that store Unicode character data.
If you need to declare a variable-length string, you must provide the maximum length of that string. For example, the VARCHAR2 data type. The following example illustrates declaring and using some string variables:
DECLARE
   name varchar2(20);
   company varchar2(30);
   introduction clob;
   choice char(1);
BEGIN
   name := 'John Smith';
   company := 'Infotech';
   introduction := ' Hello! I''m John Smith from Infotech.';
   choice := 'y';
   IF choice = 'y' THEN
      dbms_output.put_line(name);
      dbms_output.put_line(company);
      dbms_output.put_line(introduction);
   END IF;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
John Smith
Infotech Corporation
Hello! I'm John Smith from Infotech.

PL/SQL procedure successfully completed
To declare a fixed-length string, use the CHAR datatype. Here you do not have to specify a maximum length for a fixed-length variable. If you leave off the length constraint, Oracle Database automatically uses a maximum length required. So following two declarations below are identical:
 red_flag CHAR(1) := 'Y';
 red_flag CHAR    := 'Y';

PL/SQL String Functions and Operators

PL/SQL offers the concatenation operator (||) for joining two strings. The following table provides the string functions provided by PL/SQL:
S.N.Function & Purpose
1ASCII(x);
Returns the ASCII value of the character x.
2CHR(x);
Returns the character with the ASCII value of x.
3CONCAT(x, y);
Concatenates the strings x and y and return the appended string.
4INITCAP(x);
Converts the initial letter of each word in x to uppercase and returns that string.
5INSTR(x, find_string [, start] [, occurrence]);
Searches for find_string in x and returns the position at which it occurs.
6INSTRB(x); 
Returns the location of a string within another string, but returns the value in bytes.
7LENGTH(x); 
Returns the number of characters in x.
8LENGTHB(x); 
Returns the length of a character string in bytes for single byte character set.
9LOWER(x); 
Converts the letters in x to lowercase and returns that string.
10LPAD(x, width [, pad_string]) ; 
Pads x with spaces to left, to bring the total length of the string up to width characters.
11LTRIM(x [, trim_string]); 
Trims characters from the left of x.
12NANVL(x, value); 
Returns value if x matches the NaN special value (not a number), otherwise x is returned.
13NLS_INITCAP(x); 
Same as the INITCAP function except that it can use a different sort method as specified by NLSSORT.
14NLS_LOWER(x) ; 
Same as the LOWER function except that it can use a different sort method as specified by NLSSORT.
15NLS_UPPER(x); 
Same as the UPPER function except that it can use a different sort method as specified by NLSSORT.
16NLSSORT(x); 
Changes the method of sorting the characters. Must be specified before any NLS function; otherwise, the default sort will be used.
17NVL(x, value); 
Returns value if x is null; otherwise, x is returned.
18NVL2(x, value1, value2); 
Returns value1 if x is not null; if x is null, value2 is returned.
19REPLACE(x, search_string, replace_string); 
Searches x for search_string and replaces it with replace_string.
20RPAD(x, width [, pad_string]); 
Pads x to the right.
21RTRIM(x [, trim_string]); 
Trims x from the right.
22SOUNDEX(x) ; 
Returns a string containing the phonetic representation of x.
23SUBSTR(x, start [, length]); 
Returns a substring of x that begins at the position specified by start. An optional length for the substring may be supplied.
24SUBSTRB(x); 
Same as SUBSTR except the parameters are expressed in bytes instead of characters for the single-byte character systems.
25TRIM([trim_char FROM) x); 
Trims characters from the left and right of x.
26UPPER(x); 
Converts the letters in x to uppercase and returns that string.
The following examples illustrate some of the above-mentioned functions and their use:

Example 1

DECLARE
   greetings varchar2(11) := 'hello world';
BEGIN
   dbms_output.put_line(UPPER(greetings));
   
   dbms_output.put_line(LOWER(greetings));
   
   dbms_output.put_line(INITCAP(greetings));
   
   /* retrieve the first character in the string */
   dbms_output.put_line ( SUBSTR (greetings, 1, 1));
   
   /* retrieve the last character in the string */
   dbms_output.put_line ( SUBSTR (greetings, -1, 1));
   
   /* retrieve five characters, 
      starting from the seventh position. */
   dbms_output.put_line ( SUBSTR (greetings, 7, 5));
   
   /* retrieve the remainder of the string,
      starting from the second position. */
   dbms_output.put_line ( SUBSTR (greetings, 2));
   
   /* find the location of the first "e" */
   dbms_output.put_line ( INSTR (greetings, 'e'));
END;
/
When the above code is executed at SQL prompt, it produces the following result:
HELLO WORLD
hello world
Hello World
h
d
World
ello World
2

PL/SQL procedure successfully completed.

Example 2

DECLARE
   greetings varchar2(30) := '......Hello World.....';
BEGIN
   dbms_output.put_line(RTRIM(greetings,'.'));
   dbms_output.put_line(LTRIM(greetings, '.'));
   dbms_output.put_line(TRIM( '.' from greetings));
END;
/
When the above code is executed at SQL prompt, it produces the following result:
......Hello World 
Hello World.....
Hello World

PL/SQL procedure successfully completed.
There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:
Loop Architecture
PL/SQL provides the following types of loop to handle the looping requirements. Click the following links to check their detail.
Loop TypeDescription
PL/SQL Basic LOOPIn this loop structure, sequence of statements is enclosed between the LOOP and END LOOP statements. At each iteration, the sequence of statements is executed and then control resumes at the top of the loop.
PL/SQL WHILE LOOPRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
PL/SQL FOR LOOPExecute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Nested loops in PL/SQLYou can use one or more loop inside any another basic loop, while or for loop.

Labeling a PL/SQL Loop

PL/SQL loops can be labeled. The label should be enclosed by double angle brackets (<< and >>) and appear at the beginning of the LOOP statement. The label name can also appear at the end of the LOOP statement. You may use the label in the EXIT statement to exit from the loop.
The following program illustrates the concept:
DECLARE
   i number(1);
   j number(1);
BEGIN
   << outer_loop >>
   FOR i IN 1..3 LOOP
      << inner_loop >>
      FOR j IN 1..3 LOOP
         dbms_output.put_line('i is: '|| i || ' and j is: ' || j);
      END loop inner_loop;
   END loop outer_loop;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
i is: 1 and j is: 1
i is: 1 and j is: 2
i is: 1 and j is: 3
i is: 2 and j is: 1
i is: 2 and j is: 2
i is: 2 and j is: 3
i is: 3 and j is: 1
i is: 3 and j is: 2
i is: 3 and j is: 3

PL/SQL procedure successfully completed. 

The Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
PL/SQL supports the following control statements. Labeling loops also helps in taking the control outside a loop. Click the following links to check their details.
Control StatementDescription
EXIT statementThe Exit statement completes the loop and control passes to the statement immediately after END LOOP
CONTINUE statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
GOTO statementTransfers control to the labeled statement. Though it is not advised to use GOTO statement in your program.
Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general from of a typical conditional (i.e., decision making) structure found in most of the programming languages:
Decision making statements in PL/SQL
PL/SQL programming language provides following types of decision-making statements. Click the following links to check their detail.
StatementDescription
IF - THEN statementThe IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF. If the condition is true, the statements get executed and if the condition is false or NULL then the IF statement does nothing.
IF-THEN-ELSE statementIF statement adds the keyword ELSE followed by an alternative sequence of statement. If the condition is false or NULL , then only the alternative sequence of statements get executed. It ensures that either of the sequence of statements is executed.
IF-THEN-ELSIF statementIt allows you to choose between several alternatives.
Case statementLike the IF statement, the CASE statement selects one sequence of statements to execute. However, to select the sequence, the CASE statement uses a selector rather than multiple Boolean expressions. A selector is an expression whose value is used to select one of several alternatives.
Searched CASE statementThe searched CASE statement has no selector, and it's WHEN clauses contain search conditions that yield Boolean values.
nested IF-THEN-ELSEYou can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or IF-THEN-ELSIF statement(s).


Advertisements
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in PL/SQL has a specific data type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory and the set of operations that can be applied to the variable.
The name of a PL/SQL variable consists of a letter optionally followed by more letters, numerals, dollar signs, underscores, and number signs and should not exceed 30 characters. By default, variable names are not case-sensitive. You cannot use a reserved PL/SQL keyword as a variable name.
PL/SQL programming language allows to define various types of variables, which we will cover in subsequent chapters like date time data types, records, collections, etc. For this chapter, let us study only basic variable types.

Variable Declaration in PL/SQL

PL/SQL variables must be declared in the declaration section or in a package as a global variable. When you declare a variable, PL/SQL allocates memory for the variable's value and the storage location is identified by the variable name.
The syntax for declaring a variable is:
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
Where, variable_name is a valid identifier in PL/SQL, datatype must be a valid PL/SQL data type or any user defined data type which we already have discussed in last chapter. Some valid variable declarations along with their definition are shown below:
sales number(10, 2);
pi CONSTANT double precision := 3.1415;
name varchar2(25);
address varchar2(100);
When you provide a size, scale or precision limit with the data type, it is called a constrained declaration. Constrained declarations require less memory than unconstrained declarations. For example:
sales number(10, 2);
name varchar2(25);
address varchar2(100);

Initializing Variables in PL/SQL

Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If you want to initialize a variable with a value other than the NULL value, you can do so during the declaration, using either of the following:
  • The DEFAULT keyword
  • The assignment operator
For example:
counter binary_integer := 0;
greetings varchar2(20) DEFAULT 'Have a Good Day';
You can also specify that a variable should not have a NULL value using the NOT NULL constraint. If you use the NOT NULL constraint, you must explicitly assign an initial value for that variable.
It is a good programming practice to initialize variables properly otherwise, sometimes program would produce unexpected result. Try the following example which makes use of various types of variables:
DECLARE
   a integer := 10;
   b integer := 20;
   c integer;
   f real;
BEGIN
   c := a + b;
   dbms_output.put_line('Value of c: ' || c);
   f := 70.0/3.0;
   dbms_output.put_line('Value of f: ' || f);
END;
/
When the above code is executed, it produces the following result:
Value of c: 30
Value of f: 23.333333333333333333

PL/SQL procedure successfully completed.

Variable Scope in PL/SQL

PL/SQL allows the nesting of Blocks, i.e., each program block may contain another inner block. If a variable is declared within an inner block, it is not accessible to the outer block. However, if a variable is declared and accessible to an outer Block, it is also accessible to all nested inner Blocks. There are two types of variable scope:
  • Local variables - variables declared in an inner block and not accessible to outer blocks.
  • Global variables - variables declared in the outermost block or a package.
Following example shows the usage of Local and Global variables in its simple form:
DECLARE
   -- Global variables 
   num1 number := 95; 
   num2 number := 85; 
BEGIN 
   dbms_output.put_line('Outer Variable num1: ' || num1);
   dbms_output.put_line('Outer Variable num2: ' || num2);
   DECLARE 
      -- Local variables
      num1 number := 195; 
      num2 number := 185; 
   BEGIN 
      dbms_output.put_line('Inner Variable num1: ' || num1);
      dbms_output.put_line('Inner Variable num2: ' || num2);
   END; 
END;
/
When the above code is executed, it produces the following result:
Outer Variable num1: 95
Outer Variable num2: 85
Inner Variable num1: 195
Inner Variable num2: 185

PL/SQL procedure successfully completed.

Assigning SQL Query Results to PL/SQL Variables

You can use the SELECT INTO statement of SQL to assign values to PL/SQL variables. For each item in the SELECT list, there must be a corresponding, type-compatible variable in the INTO list. The following example illustrates the concept: Let us create a table named CUSTOMERS:
(For SQL statements please look at the SQL tutorial)
CREATE TABLE CUSTOMERS(
   ID   INT NOT NULL,
   NAME VARCHAR (20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR (25),
   SALARY   DECIMAL (18, 2),       
   PRIMARY KEY (ID)
);

Table Created
Next, let us insert some values in the table:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Komal', 22, 'MP', 4500.00 );
The following program assigns values from the above table to PL/SQL variables using the SELECT INTO clause of SQL:
DECLARE
   c_id customers.id%type := 1;
   c_name  customers.name%type;
   c_addr customers.address%type;
   c_sal  customers.salary%type;
BEGIN
   SELECT name, address, salary INTO c_name, c_addr, c_sal
   FROM customers
   WHERE id = c_id;

   dbms_output.put_line
   ('Customer ' ||c_name || ' from ' || c_addr || ' earns ' || c_sal);
END;
/
When the above code is executed, it produces the following result:
Customer Ramesh from Ahmedabad earns 2000

PL/SQL procedure completed successfully