DBMS LAB MANUAL.pdf

March 27, 2018 | Author: Karthikeyan Ramajayam | Category: Pl/Sql, Sql, Control Flow, Subroutine, Parameter (Computer Programming)


Comments



Description

DBMS LAB MANUALDEPARTMENT OF INFORMATION TECHNOLOGY Padmasri Dr. B V Raju Institute of Technology, Vishnupur, Narsapur-502 313 Dist Medak(A.P.) LABORATORY MANUAL II B.Tech. II SEM DATABASE MANAGEMENT SYSTEMS LAB Prepared By Vijaykumar Mantri, M.Tech.(CSE) Asso. Prof. in IT Dept. Dept of IT, BVRIT, Narsapur DBMS LAB MANUAL DBMS Lab - I Creation, altering and dropping of tables and inserting rows into a table (Use constraints while creating tables) examples using SELECT command. Following tables (Relations) are considered for the lab purpose. • • • SAILORS (SID:INTEGER, SNAME:STRING, RATING:INTEGER, AGE:REAL) BOATS (BID:INTEGER, BNAME:STRING, COLOR:STRING) RESERVES (SID:INTEGER, BID:INTEGER, DAY:DATE) Creating Tables :The CREATE TABLE command is used to create the table (relation) in SQL. CREATE TABLE TABLENAME (ATT_NAME1 DATATYPE, ATT_NAME2 DATATYPE, ATT_NAME3 DATATYPE, …..); SQL> CREATE TABLE SAILORS (SID NUMBER (5), SNAME VARCHAR2(30), RATING NUMBER(5), AGE NUMBER(4,2)); Data Types :- Oracle supports following types of data types. • CHAR (SIZE) :- Fixed length character data of length SIZE bytes. The maximum length is 255 bytes in Oracle 7 and 2000 bytes in Oracle 8 onwards. Default and minimum size is 1 byte. • VARCHAR2(SIZE) :- Variable length character string having maximum length SIZE bytes. The maximum length 2000 bytes in Oracle 7 and 4000 bytes in Oracle 8 onwards. The minimum size is 1 • • NUMBER(L) :- Numeric data with number of digits L. NUMBER(L, D) :- Numeric data with total number of digits L and number of digits D after decimal point. • DATE :- Valid date range. The date ranges from January 1, 4712 BC to December 31, 9999 AD. • LONG :- Character data of variable length which stores upto 2 Gigabytes of data. (A bigger version the VARCHAR2 datatype). • INTEGER :- Integer type of Data. It is actually a synonym for NUMBER(38) Dept of IT, BVRIT, Narsapur DBMS LAB MANUAL • FLOAT :- Floating point type of Data. Very similar to NUMBER it stores zero, positive, and negative floating-point numbers. Along with these types of data types, Oracle supports other types of data types like TIMESTAMP, RAW, ROWID, CLOB, NCLOB, BLOB, XMLType, etc. Primary Key & Foreign Key :- Consider the Sailors relation and the constraint that no two sailors have the same SID. This type of constraint can be defined using Primary Key, which gives uniqueness for the value of attribute defined (Eg. SID). Similarly, a sailor can’t reserve a boat unless he/she is a valid sailor i.e. the SID of Reserves relation must available in the Sailors relation. This type of constraint can be defined using Foreign Key, which gives the existence of the value of attribute in one relation is depends on value in another relation. We can use Primary Key or/and Foreign Key constraint while creating table. Creating tables with Primary Key CREATE TABLE TABLENAME (ATT_NAME1 DATATYPE, ATT_NAME2 DATATYPE, ATT_NAME3 DATATYPE ….., PRIMARY KEY(ATT_NAMES) ); SQL> CREATE TABLE SAILORS ( SID NUMBER(5), SNAME VARCHAR2(30), RATING NUMBER(5), AGE NUMBER(4,2), , PRIMARY KEY(SID) ); Creating tables with Foreign Key CREATE TABLE TABLENAME (ATT_NAME1 DATATYPE, ATT_NAME2 DATATYPE, ATT_NAME3 DATATYPE ….., FOREIGN KEY (ATT_NAME) REFERENCES TABLENAME2)); SQL> CREATE TABLE RESERVES (SID NUMBER(5), BID NUMBER(5), DAY DATE, FOREIGN KEY (SID) REFERENCES (SAILORS) ); The following example gives the complete definition to create Reserves table (Defines Primary Key as well as Foreign Keys). SQL> CREATE TABLE RESERVES (SID NUMBER(5), BID NUMBER(5), DAY DATE, PRIMARY KEY (SID, BID, DAY), FOREIGN KEY (SID) REFERENCES (SAILORS) , FOREIGN KEY (BID) REFERENCES (BOATS) ); Similar way we can create Sailors as well as Boats table using Primary Key constraint. Dept of IT, BVRIT, Narsapur DBMS LAB MANUAL Creating table with some Constraint :- Suppose we want to add rule for rating of the sailors - “Rating should be between 1 to 10” while creating table then we can use following command. SQL> CREATE TABLE SAILORS ( SID NUMBER(5), SNAME VARCHAR2(30), RATING NUMBER(5), AGE NUMBER(4,2), , PRIMARY KEY(SID), CHECK ( RATING >=1 AND RATING <=10) ); Deleting Table :- The table along with its definition & data can be deleted using following command. DROP TABLE <TABLENAME>; SQL> DROP TABLE SAILORS; Adding & Deleting the Attributes and Constraints to the Table :To add the attribute to a existing relation we can use ALTER TABLE Command. ALTER TABLE <TABLENAME> ADD COLUMN ATT_NAME DATATYPE; SQL> ALTER TABLE SAILORS ADD COLUMN SALARY NUMBER(7,2); To remove the attribute from an existing relation we can use following Command. ALTER TABLE <TABLENAME> DROP COLUMN ATT_NAME; SQL> ALTER TABLE SAILORS DROP COLUMN SALARY; To add the constraint to existing relation we can use ALTER TABLE Command. ALTER TABLE <TABLENAME> ADD CONSTRAINT <CON_NAME> <CON_DEFINITION>; SQL> ALTER TABLE SAILORS ADD CONSTRAINT RATE CHECK (RATING >= 1 AND RATING <=10); Similarly we can add primary key or foreign key constraint. To delete the constraint to existing relation we can use following Command. DROP CONSTRAINT <CON_NAME>; SQL> DROP CONSTRAINT RATE; Similarly we can drop primary key or foreign key constraint. Dept of IT, BVRIT, Narsapur …. ATT_NAME3. 30). 1. we can use DELETE FROM command as follows. VALUE2. To delete the record(s) :. BVRIT. UPDATE <TABLENAME> SET ATT_NAME = NEW_VALUE WHERE CONDITION. …. 10). To delete all records from the table DELETE FROM <TABLENAME>. By using one of these methods we can add records or data to Sailors. SQL> DELETE FROM SAILORS WHERE SNAME = ‘Rajesh’. Narsapur . VALUE3..To delete all records from table or a single/multiple records which matches the given condition. ATT_NAME2. SQL> DELETE FROM SAILORS. But sometimes while adding data we may not remember the exact order or sometimes we want to insert few values then we can use following format to add data to a table. Boats as well as Reserves Table.We can modify the column values in an existing row using the UPDATE command. To change particular value :. VALUE2. 10. AGE. SELECT * FROM <TABLENAME> SQL> SELECT * FROM SAILORS.. DELETE FROM <TABLENAME> WHERE <CONDITION>.). SID. …..To view all records present in the table. RATING) VALUES (‘Rajesh’. To see the records :.We can add data to table by using INSERT INTO command.DBMS LAB MANUAL Adding data to the Table :. The syntax is as follows. Dept of IT. While adding the data to the table we must remember the order of attributes as well as their data types as defined while creating table. SQL> INSERT INTO SAILORS (SNAME.). 30.) VALUES (VALUE1. VALUE3. INSERT INTO <TABLENAME> VALUES (VALUE1. ‘Rajesh’. SQL> INSERT INTO SAILORS VALUES (1. SQL> UPDATE SAILORS SET RATING = 9 WHERE SID = 1. INSERT INTO <TABLENAME> (ATT_NAME1. 3) Find names of the sailors who have reserved at least one boat. SQL> SELECT SNAME FROM SAILORS S. 2) Display all the names & colors of the boats. BVRIT. Write queries for 1) Find SIDs of sailors who have reserved Pink Boat. Dept of IT.The basic form of an SQL query is: SELECT <SELECT_LIST>FROM <TABLE_LIST> WHERE <CONDITION>. SQL> UPDATE SAILORS SET RATING = RATING + 1. Queries on multiple tables Q2) Find the names of sailors who have reserved boat number 123. Q1) Display names & ages of all sailors.SID = R. AGE FROM SAILORS.SID AND R. 3) Find all the boats with Red color. Narsapur . Simple Queries on the Tables :. RESERVES R WHERE S. Write queries for 1) Find all sailors with a rating above 7.DBMS LAB MANUAL To update all records without any condition. SQL> SELECT SNMAE. 2) Find the color of the boats reserved by Rajesh.BID = 123. RESERVES R. NOTEXISTS.SID = R. EXISTS.SNAME FROM SAILORS S. UNION.SID AND R. Since the answer to a query is a multiset of rows.DBMS LAB MANUAL DBMS Lab – II Queries (along with sub Queries) using ANY. Constraints. SQL> SELECT DISTINCT S. If two or more sailors have the same name and age.Find the names of sailors who have reserved a red or a green boat.COLOR = 'RED' OR B. INTERSECT.SID = R. and difference.SID = R2. have the same number of columns and the columns. EXCEPT (MINUS) :. UNION :.The DISTINCT keyword eliminates the duplicate tuples from the result records set. DISTINCT Keyword :.SID AND R.COLOR = 'RED' UNION SELECT S2. SQL> SELECT S.AGE FROM SAILORS S.COLOR = 'GREEN').It is a set operator used as alternative to OR query.BID = B. ALL. INTERSECT and MINUS.COLOR = 'GREEN'. IN. age).SNAME FROM SAILORS S2. SQL> SELECT S. BOATS B2. The answer is a set of rows.SNAME. Same query can be written using UNION as follows.SNAME FROM SAILORS S. intersection. BVRIT.SID AND R2.Find the Names and Ages of all sailors. Narsapur . BOATS B WHERE S. that is. Note that UNION. Ex:. RESERVES R2 WHERE S2.BID AND B.BID = B2. INTERSET.BID AND B2. Dept of IT.BID AND (B. This query says that we want the union of the set of sailors who have reserved red boats and the set of sailors who have reserved green boats. taken in order. each of which is a pair (sname. the answer still contains just one pair with that name and age.BID = B. have the same types. Ex:. SQL supports these operations under the names UNION. and MINUS can be used on any two tables that are unioncompatible. BOATS B WHERE S. RESERVES R. it is natural to consider the use of operations such as union. UNION. Here is an example of Query using OR. S.SQL provides three set-manipulation constructs that extend the basic query form. INTERSECT. SID AND R1.SID AND R2.It is a set operator used as set-difference. NESTED QUERIES:.COLOR = 'GREEN’. there is no need to look at the Sailors relation.BID AND B. Dept of IT.SID = R2.SID AND R. BOATS B1.DBMS LAB MANUAL INTERSECT :.SID = R. RESERVES R1.SID = R2. These queries extract the data from one or more tables. One of the most powerful features of SQL is nested queries.It is a set operator used as alternative to AND query. BOATS B WHERE S. RESERVES R2.SNAME FROM SAILORS S2.SID FROM BOATS B2.BID = B. SQL> SELECT S. Here we are going to see some complex & powerful queries that enables us to retrieve the data in desired manner. BVRIT.BID AND B1. BOATS B2 WHERE S.BID = B. Ex:. RESERVES R.SID = R.BID = B2.COLOR = 'RED' MINUS SELECT R2.SNAME FROM SAILORS S.SID FROM BOATS B.BID AND B. Same query can be written as follows.BID = B2. RESERVES R2 WHERE R2.Find the sids of all sailor's who have reserved red boats but not green boats.BID = B1. RESERVES R.BID = B2.COLOR = 'RED' MINUS SELECT S2.COLOR = ‘GREEN’. Ex:. and we can use the following simpler query SQL> SELECT R. RESERVES R2. Narsapur .BID AND B2.SID = R2.BID AND S.BID = B. Here is an example of Query using AND.Find the names of sailor's who have reserved both a red and a green boat. SQL> SELECT S.COLOR = 'GREEN'. the embedded query is called a subquery.BID AND B2. SQL> SELECT S. Our next query illustrates the set-difference operation. BOATS B2 WHERE S2.COLOR='RED' AND B2.SID FROM SAILORS S. BOATS B WHERE S.SID FROM SAILORS S2.BID AND B. EXCEPT (MINUS) :.SID AND R2. A nested query is a query that has another query embedded within it. RESERVES R2 WHERE S2. Same query can be written using INTERSECT as follows.SID AND R2. RESERVES R WHERE R.SID = R1.SNAME FROM SAILORS S.COLOR = ‘RED’ INTERSECT SELECT S2.For retrieving data from the tables we have seen the simple & basic queries.COLOR = 'GREEN'.SID AND R.BID AND B2. Since the Reserves relation contains sid information.BID = B2. BOATS B2. DBMS LAB MANUAL IN Operator :.SID = S. SQL> SELECT S.SID ).SNAME FROM SAILORS S WHERE S.Find the names of sailors who have reserved boat number 103. IN along with their negated versions.SID NOT IN ( SELECT R.It is a comparison operator. SQL also supports op ANY and op ALL.This is a Correlated Nested Queries operator. Ex:.BID = 103 ).BID = 103 AND R.BID = 103 ).SID IN (SELECT R. Ex:.The NOT EXISTS is used in a opposite manner to EXISTS. op ANY Operator :. Ex:.RATING FROM SAILORS S2 WHERE S2.Find sailors whose rating is better than some sailor called Rajesh. where op is one of the arithmetic comparison operators {<.SID = S.SNAME FROM SAILORS S WHERE S. Ex:.Find the names of sailors who have reserved boat 103.The NOT IN is used in a opposite manner to IN. EXISTS Operator :. It allows us to test whether a set is nonempty. Dept of IT. NOT EXISTS Operator :. BVRIT.Find the names of sailors who have not reserved boat number 103. >=. SQL> SELECT S. =.Find the names of sailors who have not reserved boat 103. <>. Ex:. Following are the example which illustrates the use of these Set-Comparison Operators. SQL> SELECT S. SQL> SELECT S.SID FROM SAILORS S WHERE S.SNAME FROM SAILORS S WHERE EXISTS (SELECT * FROM RESERVES R WHERE R.SNAME = ' RAJESH ' ). Narsapur .SID FROM RESERVES R WHERE R. such as IN. SQL> SELECT S. It is used to compare a value with any of element in a given set.The IN operator allows us to test whether a value is in a given set of elements.RATING > ANY (SELECT S2. <=. Set-Comparison Operators:.SNAME FROM SAILORS S WHERE NOT EXISTS ( SELECT * FROM RESERVES R WHERE R.SID ). NOT IN Operator :. The EXISTS operator is another set comparison operator. an SQL query is used to generate the set to be tested.SID FROM RESERVES R WHERE R.BID = 103 AND R.We have already seen the set-comparison operators EXISTS. >}. an implicit comparison with the empty set. RATING >= ALL ( SELECT S2.RATING FROM SAILORS S2 ) Dept of IT.DBMS LAB MANUAL Note that IN and NOT IN are equivalent to = ANY and <> ALL. It is used to compare a value with all the elements in a given set.It is a comparison operator. respectively.SID FROM SAILORS S WHERE S. SQL> SELECT S. Ex:. BVRIT.Find the sailor's with the highest rating using ALL. op ALL Operator :. Narsapur . Ex:. SQL> SELECT COUNT (DISTINCT BID) FROM RESERVES.1) To find sum of rating from Sailors SQL> SELECT SUM (RATING) FROM SAILORS.The number of values in the A column. AVG. BVRIT. SQL> SELECT AVG (AGE) FROM SAILORS. HAVING and Creation and dropping of Views. COUNT (A) :.III Queries using Aggregate functions (COUNT. Or COUNT (DISTINCT A): The number of unique values in the A column. 3) To count number of Boats in Boats table. Or AVG (DISTINCT A): The average of all unique values in the A column. SUM. 3.1) To count number SIDs of sailors in Sailors table SQL> SELECT COUNT (SID) FROM SAILORS. AVG (A) :. Dept of IT. SQL> SELECT AVG (DISTINCT AGE) FROM SAILORS. MAX and MIN). Or SUM (DISTINCT A): The sum of all unique values in the A column. we often want to perform some computation or summarization. which can be applied on any column. These features represent a significant extension of relational algebra. Ex:. of a relation: 1. SQL> SELECT SUM (DISTINCT AGE) FROM SAILORS. AGGREGATE Functions :. Ex:. 2. Narsapur . SQL supports five aggregate operations.In addition to simply retrieving data. SUM (A) :.The sum of all values in the A column. SQL> SELECT COUNT (*) FROM BOATS. GROUP BY. say A. 2) To count numbers of boats booked in Reserves table. We now consider a powerful class of constructs for computing aggregate values such as MIN and SUM. 2) To find average of distinct age of Sailors (Duplicate ages are eliminated). 2) To find sum of distinct age of Sailors (Duplicate ages are eliminated).DBMS LAB MANUAL DBMS LAB .1) To display average age of Sailors.The average of all values in the A column. we can use the DESC keyword. SQL> SELECT MAX (AGE) FROM SAILORS. BVRIT.DBMS LAB MANUAL 4. 4) Count the number of Sailors. ORDER BY Clause :. 5. Note that it does not make sense to specify DISTINCT in conjunction with MIN or MAX (although SQL does not preclude this). Ex:. Ex:. 2) Count the number of different sailor names. SQL> SELECT MIN (AGE) FROM SAILORS. AGE. Dept of IT. 3) Find the name and age of the oldest sailor. 3) Displays all the sailors according to rating. if rating is same then sort according to age. SQL> SELECT * FROM SAILORS ORDER BY AGE. The ORDER BY keyword sorts the records in ascending order by default (we can even use ASC keyword).To find age of Oldest Sailor.1) Display all the sailors according to their ages. 5) Find the names of sailors who are older than the oldest sailor with a rating of 10. Write the query 1) To display names of sailors according to alphabetical order. 1) Find the average age of sailors with a rating of 10. 2) Display all the sailors according to their ratings (topper first). SQL> SELECT * FROM SAILORS ORDER BY RATING DESC. The general syntax is SELECT ATT_LIST FROM TABLE_LIST ORDER BY ATT_NAMES [ASC | DESC]. If we want to sort the records in a descending order.To find age of Youngest Sailor. Ex:. MIN (A) :.The minimum value in the A column.The maximum value in the A column. Write the following queries using Aggregate Functions. MAX (A) :.The ORDER BY keyword is used to sort the result-set by a specified column. SQL> SELECT * FROM SAILORS ORDER BY RATING. Narsapur . RATING. The general syntax is SELECT [DISTINCT] ATT_LIST FROM TABLE_LIST WHERE CONDITION GROUP BY GROUPING_LIST HAVING GROUP_CONDITIION. 3) Displays all the sailors according to rating (Topper First). if rating is same then sort according to age (Younger First). For this purpose we can use Group by clause. Dept of IT. where the number of groups depends on the relation instances.The extension of GROUP BY is HAVING clause which can be used to specify the qualification over group.RATING. Write following queries in SQL.Find the age of youngest sailor with age >= 18 for each rating with at least 2 such sailors. MIN (S. we have applied aggregate operations to all (qualifying) rows in a relation. GROUP BY and HAVING Clauses :.Find the age of the youngest sailor for each rating level.Group by is used to make each a number of groups of rows in a relation. find the number of reservations for this boat. The general syntax is SELECT [DISTINCT] ATT_LIST FROM TABLE_LIST WHERE CONDITION GROUP BY GROUPING_LIST.RATING HAVING COUNT (*) > 1.AGE >= 18 GROUP BY S. SQL> SELECT S. BVRIT. Often we want to apply aggregate operations to each of a number of groups of rows in a relation. if rating is same then sort according to age (Older First).AGE) FROM SAILORS S GROUP BY S.Thus far. 2) Find the average age of sailors for each rating level that has at least two sailors. where the number of groups depends on the relation instance.RATING.AGE) AS MINAGE FROM SAILORS S WHERE S. 1) For each red boat. if rating is same then sort according to age (Younger First). HAVING :. Ex:.DBMS LAB MANUAL 2) Displays all the sailors according to rating (Topper First). Narsapur . MIN (S. GROUP BY:. 3) Find those ratings for which the average age of sailors is the minimum over all ratings. 4) Displays all the sailors according to rating (Lower Rating First). Ex :. SQL> SELECT S. Write the following queries on Expert Sailor View. SNAME. 4) Find the sum of rating of Sailors. Eg:.A view is a table whose rows are not explicitly stored in the database but are computed as needed from a view definition.Create a view for Expert Sailors ( A sailor is a Expert Sailor if his rating is more than 7). Now on this view we can use normal SQL statements as we are using on Base tables. 3) Find the number of Sailors at each rating level ( 8. Dept of IT. Narsapur . BVRIT.e. 1) Find the Sailors with age > 25 and rating equal to 10. 9. If we decide that we no longer need a view and want to destroy it (i.Find average age of Expert sailors. SQL> SELECT AVG (AGE) FROM EXPERTSAILOR. 2) Find the total number of Sailors in Expert Sailor view. The views are created using CREATE VIEW command. 10). SQL> CREATE VIEW EXPERTSAILOR AS SELECT SID. SQL> DROP VIEW EXPERTSAILOR. RATING FROM SAILORS WHERE RATING > 7. A view can be dropped using the DROP VIEW command.DBMS LAB MANUAL VIEWS :. To drop the ExpertSailor view. Ex :. 5) Find the age of Oldest as well as Youngest Expert Sailor. removing the definition of view) we can drop the view. rtrim. greatest. upper.FMT]) :. to_number and to_date. 2) TO_NUMBER(CHAR) :. substr and instr.IV Queries using Conversion functions :. length. round.to_char. ‘DD-MM-YYYY’). SQL> SELECT TO_CHAR(SYSDATE. 1) TO_CHAR (N [.45’) FROM DUAL. Example 1) Convert 12345 to string. ‘Mon-DD-YYYY’) FROM DUAL. Date functions :.This conversion function is used to convert string to number data type. initcap. rpad. SQL> SELECT TO_CHAR(SYSDATE) FROM DUAL. SQL> SELECT TO_NUMBER(‘123. months_between. Ex:. to_date. Dept of IT.Sysdate. String functions :. lpad.DBMS LAB MANUAL DBMS Lab . BVRIT.(‘DDD-MM-YY’) FROM DUAL. to_char. lower. SQL> SELECT TO_CHAR(TO_DATE(’09-02-2010’. trunc. 2) Display system date after converting to varchar2 data type. last_day.These functions are used to convert the value from one type to another type. next_day.Concatenation. Narsapur . add_months. Ex :. 3) Display system date in ‘Mon-DD-YYYY’ format after converting to varchar2 data type.Converts character data type data to date type data. Formats we can use for Date :.Display ’09-02-2010’ converted to DDD-MM-YY format using to_char & to_date functions. 3) TO_DATE :.Following formats can be used with any function related to dates. Conversion Functions :.Converts ‘N’ of numeric data type to Varchar2 datatype using optional number format FMT. ltrim.Convert string ‘123. SQL> SELECT TO_CHAR(12345) FROM DUAL. least.45’ to number data type. 2) Concat bid & bname of Boats & display along with color. Narsapur . BVRIT. COLOR FROM BOATS. Month in formatted with three characters. Hours in 12 Hrs or 24 Hrs format. The default value of CHAR2 is a single blank space. String Functions :1) Concatenation :. Day of the Month. Last two digits in the year.DBMS LAB MANUAL • • • • • • • • • • • • • • Y YY Last digit in the year. N. CHAR2) EX 1) Concate the string ‘Rajesh’ with ‘Raghu’ SQL> SELECT CONCAT (‘Rajesh’. Year in four digits. CANCAT (CHAR1. Day name. Seconds. ‘Raghu’) FROM DUAL. Month in characters. SQL> SELECT CONCAT(BID. BNAME). 2) Lpad the string bname to length 20 with ‘-*’ set of characters and string color by ‘/’. Year in characters. Dept of IT. CHAR2) :. 3) RPAD (CHAR1.Returns CHAR1 left padded to length ‘N’ with sequence of characters in CHAR2. The default value of CHAR2 is a single blank space. YYYY YEAR MM MONTH MON D DD DDD DAY Day of Week.Concatenates two stings from a given list. N.Returns CHAR1 right padded to length ‘N’ with sequence of characters in CHAR2. CHAR2) :. 30. Ex 1) Lpad the string ‘Rajesh’ to length 30 with the set of characters in string ‘-*-’ SQL> SELECT LPAD(‘Rajesh’. ‘-*-’) FROM DUAL. 2) LPAD (CHAR1. Day of the Year. Month in digits. HH or HH12 or HH24 MI SS Minutes. Ex:.Returns characters from the right of CHAR by deleting all rightmost characters that appear in set. ‘*#’) FROM DUAL.’R’) FROM SAILORS.Converts all characters to uppercase characters in a sting CHAR. Ex:-1) Display all Sailors information by showing their names in Capitalizing first char. 6) LOWER(CHAR) :.Display all Sailors information by showing their names in Upper case. Narsapur . RTRIM(SNAME. SQL> SELECT BID. SET) :. 30.Converts first character of each word in a sting CHAR to uppercase. RATING FROM SAILORS.Converts all characters to lowercase characters in a sting CHAR. COLOR FROM BOATS.Returns the length of the string CHAR i. LOWER(BNAME).Display all sailors information by removing characters of sname if starts with ‘R’.Display all Boats information by showing their names in lower case. SQL> SELECT SID.Returns characters from the left of CHAR by deleting all leftmost characters that appear in set. 5) RTRIM (CHAR. 7) UPPER(CHAR) :. LTRIM(SNAME. SQL> SELECT SID. Ex:. number of characters present in the given string. 4) LTRIM (CHAR. Ex:-1) Find the number of characters in the string ‘Information Technology’ Dept of IT. BVRIT. Ex:. RATING FROM SAILORS. 2) Rpad the string sname to length 20 with ‘-*’ set of characters and remaining attributes in normal way. SQL> SELECT SID.Display all sailors information by removing characters of sname if ends with ‘i’. 8) INITCAP(CHAR) :. 2) Capatilize first letter of each word in ‘rajesh raghu’ SQL> SELECT INITCAP(‘rajesh raghu’) FROM DUAL. AGE. Ex:.e. AGE. SQL> SELECT SID.DBMS LAB MANUAL Ex 1) Rpad the string ‘Rajesh’ to length 30 with the set of characters in string ‘*#’ SQL> SELECT RPAD(‘Rajesh’. UPPER(SNAME). SET) :.’i’) FROM SAILORS. INITCAP(SNAME). 9) LENGTH (CHAR) :. DBMS LAB MANUAL SQL> SELECT LENGTH (‘Information Technology’) FROM DUAL. 10) SUBSTR(CHAR. SNAME. Narsapur . if any. BVRIT. The default value of M & N is 1. If R is not given or NULL. 11) INSTR(CHAR1. CHAR2. If N is negative value. 3. TRANSLATE(SNAME. 4). ‘da’. 3) FROM DUAL.Displays the system date for a system. SNAME from Sailors along with their values. SQL> SELECT REPLACE (BNAME. M. Date Functions :1) SYSDATE :. 13) REPLACE(CHAR. 2) Display Sailors information by replacing ‘a’ with ‘i’ from SNAME. FROM. SQL> SELECT SID. SQL> SELECT BID. ‘ma’) FROM BOATS.’a’. SUBSTR(BNAME. LENGTH(SID). Ex : Display boats information by starting their names with 3rd character & show only 4 characters. 12) TRANSLATE(CHAR.’i’ ) FROM SAILORS. Ex :1) Replace ‘a’ with ‘d’ in the given string ‘abcdabcdababab’. all occurrences of S are removed or deleted.’ab’. SQL> SELECT INSTR (‘abcdabcdababab’. 2) Display length of string SID.It returns characters with all occurrences of each character in FROM replaced by its corresponding character in TO.It returns characters with every occurrences of S replaced with R. COLOR FROM BOATS. SQL> SELECT TRANSLATE (‘abcdabcdababab’.It searches CHAR1 beginning with Mth character for Nth occurrence of CHAR2 and returns the position after character in CHAR1. Dept of IT. S. N) :. SQL> SELECT SID. 2.It returns substring from CHAR string starting with index M & gives N characters. Ex : Display the index of string ‘ab’ after 2nd character & 3rd occurrence in the given string ‘abcdabcdababab’.’a’. then it searches backwards from the end of CHAR1. LENGTH(SNAME) FROM SAILORS.’b’) FROM DUAL. N) :. TO) :. Ex :1) Display BNAME by replacing ‘da’ with ‘ma’. M. R) :. 5) MONTHS_BETWEEN (D1. 3) ADD_MONTHS (D. 20) FROM RESERVES. Day of Reservation by adding 20 months to given day. 'DD-MON-YYYY HH:MI:SS') FROM dual. DAY) FROM RESERVES. ‘THU’) FROM DUAL. DAY) :. MONTHS_BETWEEN (SYSDATE. SQL> SELECT SID.Returns the date corresponding to last day of the month.SNAME.DBMS LAB MANUAL SQL> SELECT SYSDATE FROM DUAL. Narsapur .Returns number of months between given two dates D1 & D2. BVRIT.Displays next date on DAY after date D. 2010. DAY. DAY. SQL> SELECT S. LAST_DAY (DAY) FROM SAILORS S. 4) LAST_DAY(D) :.SID = R. D2) :. SQL> SELECT NEXT_DAY (’20-FEB-2010’.Returns a date after adding a specified day D with specified number of months N. ADD_MONTHS (DAY.SID. SQL> SELECT SID. N) :. RESERVES R WHERE S. Day of Reservation and months between System Date & day of reservation. Day of Reservation and date corresponding to last date of the month. Ex: Display SID. Dept of IT. DAY. SQL> SELECT TO_CHAR (SYSDATE. Ex: Display SID. 2) NEXT_DAY (D. Ex: Display date on Thu after 20th Feb. Ex: Display Sname. before Starting writing anything type (Only Once per session) SQL> SET SERVEROUTPUT ON To write program. Dept of IT. Basic Syntax of PL/SQL DECLARE /* Variables can be declared here */ BEGIN /* Executable statements can be written here */ EXCEPTION /* Error handlers can be written here. SQL> ED ProName Type the program Save & Exit. C INTEGER.PL/SQL to find addition of two numbers DECLARE A INTEGER := &A. B INTEGER := &B. use Notepad through Oracle using ED command. BEGIN C := A + B. Narsapur . Steps to Write & Execute PL/SQL As we want output of PL/SQL Program on screen. To Run the program SQL> @ProName Ex :. BVRIT. */ END.DBMS LAB MANUAL PL/SQL PROGRAMMING Procedural Language/Structured Query Language (PL/SQL) is an extension of SQL. Ex:. 1) DECLARE A NUMBER := &A.DBMS LAB MANUAL DBMS_OUTPUT. This program can be written in number of ways. For Nested IF—ELSE Statement we can use IF--ELSIF—ELSE as follows IF(TEST_CONDITION) THEN SET OF STATEMENTS ELSIF (CONDITION) SET OF STATEMENTS END IF. / Decision making with IF statement :. C NUMBER := &C. BIG NUMBER. Narsapur . here are the two different ways to write the program.Largest of three numbers. END.PUT_LINE('THE SUM IS '||C). BVRIT.The general syntax for the using IF--ELSE statement is IF(TEST_CONDITION) THEN SET OF STATEMENTS ELSE SET OF STATEMENTS END IF. B NUMBER := &B. BEGIN IF (A > B) THEN Dept of IT. END. END. END IF.PUT_LINE('BIGGEST OF A. FOR. Here is the syntax of these all the types of looping statements. END IF. ELSIF (B > C) THEN DBMS_OUTPUT. / LOOPING STATEMENTS:. Dept of IT.PUT_LINE('BIGGEST OF A.PUT_LINE('BIGGEST IS ' || B). IF(BIG < C ) THEN DBMS_OUTPUT. The oracle supports number of looping statements like GOTO. END IF.PUT_LINE('BIGGEST IS ' || C). Narsapur . B NUMBER := &B. C NUMBER := &C. B AND C IS ' || BIG).For executing the set of statements repeatedly we can use loops.DBMS LAB MANUAL BIG := A. ELSE BIG := B. BEGIN IF (A > B AND A > C) THEN DBMS_OUTPUT. ELSE DBMS_OUTPUT. / 2) DECLARE A NUMBER := &A. WHILE & LOOP.PUT_LINE('BIGGEST IS ' || A). BVRIT. B AND C IS ' || C). ELSE DBMS_OUTPUT. BVRIT.. • FOR LOOP FOR <VAR> IN [REVERSE] <INI_VALUE>.Here are the example for all these types of looping statement where each program prints numbers 1 to 10. While using LOOP statement. • LOOP STATEMENT LOOP SET OF STATEMENTS IF (CONDITION) THEN EXIT SET OF STATEMENTS END LOOP. we have take care of EXIT condition. Narsapur .<END_VALUE> SET OF STATEMENTS END LOOP.DBMS LAB MANUAL • GOTO STATEMENTS <<LABEL>> SET OF STATEMENTS GOTO LABEL. • WHILE LOOP WHILE (CONDITION) LOOP SET OF STATEMENTS END LOOP. GOTO EXAMPLE DECLARE Dept of IT. otherwise it may go into infinite loop. Example :. END LOOP. IF I<=10 THEN GOTO OUTPUT.PUT_LINE(I).PUT_LINE(I). I := I + 1. / FOR LOOP EXAMPLE BEGIN FOR I IN 1. / WHILE EXAMPLE DECLARE I INTEGER := 1.PUT_LINE(I)..DBMS LAB MANUAL I INTEGER := 1. BEGIN WHILE(I<=10) LOOP DBMS_OUTPUT. END. BEGIN <<OUTPUT>> DBMS_OUTPUT. / LOOP EXAMPLE Dept of IT. END IF. END LOOP. Narsapur . BVRIT.10 LOOP DBMS_OUTPUT. END. END. I := I + 1. Eg:.DBMS LAB MANUAL DECLARE I INTEGER := 1.%rowtype is used to provide record datatype to a variable. • Single line comment :. BEGIN LOOP DBMS_OUTPUT. INTEGER. The database column can be used as id Sailors.e Single Line & Multiline comments.Comment here Dept of IT. BVRIT. • %TYPE :. etc. Now let’s see few more data types that are useful for writing PL/SQL programs in Oracle. NUMBER. VARCHAR2. EXIT WHEN I=11. I := I + 1.itemcode Number(10).In Oracle we can have two types of comments i. Narsapur .It starts with --. The variable can store row of the table or row fetched from the cursor. DATE. -. BOOLEAN. icode itemcode%Type.sid%type • %ROWTYPE :. Eg:. END LOOP.If we want to store a row of table Sailors then we can declare variable as Sailors %Rowtype • Comments :. / DATA TYPES Already we know following data types.PUT_LINE(I).%TYPE is used to give data type of predefined variable or database column. END. Here is the example for inserting the values into a database through PL/SQL Program. AGE NUMBER(4. DBMS_OUTPUT.or can be defined SID Sailors. Remember that we have to follow all the rules of SQL like Primary Key Constraints. Narsapur . BEGIN INSERT INTO SAILORS VALUES(SID. / Dept of IT.DBMS LAB MANUAL • Multiline comment is same as C/C++/JAVA comments where comments are present in the pair of /* & */. RATING NUMBER(5):=&RATING. Foreign Key Constraints. etc. RATING. SNAME VARCHAR2(30):='&SNAME'. BEGIN SELECT SID. END. SNAME. END. AGE).Insert the record into Sailors table by reading the values from the Keyboard. -. Ex:. AGE NUMBER(4.2):=&AGE. SNAME. BVRIT. / Reading from table DECLARE SID VARCHAR2(10). Check Constraints. AGE INTO SID.PUT_LINE(SID || ' '|| SNAME || ' '|| RATING ||' '|| AGE ).2). RATING. /* Comment here */ Inserting values to table :. RATING.SID%Type SNAME VARCHAR2(30). RATING NUMBER(5). DECLARE SID NUMBER (5):=&SID. AGE FROM SAILORS WHERE SID='&SID'. SNAME. BVRIT. We have two types of exception. If no row is selected then exception NO_DATA_FOUND is raised. / Program with Pre-Defined Exception DECLARE SID VARCHAR2(10). END. END IF..2)=0 THEN RAISE A..INTO We have to ensure that the SELECT….').DBMS LAB MANUAL Some Points regarding SELECT --. To handle the situation where no rows selected or so many rows selected we can use Exceptions.. WHEN B THEN DBMS_OUTPUT.. User-Defined and Pre-Defined Exceptions. Dept of IT. If more than one row is selected then exception TOO_MANY_ROWS is raised. Program with User-Defined Exception DECLARE N INTEGER:=&N.INTO statement should return one & only one row.. BEGIN IF MOD(N. B EXCEPTION. EXCEPTION WHEN A THEN DBMS_OUTPUT. ELSE RAISE B.PUT_LINE('THE INPUT IS EVEN....'). Narsapur . A EXCEPTION.PUT_LINE('THE INPUT IS ODD. WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT. Generally while using cursors we have to Open the cursor then extract one row (record) from the cursor using Fetch operation. After completing the work Close the cursor. Cursors are defined as CURSOR C1 IS SELECT SID. which can hold row. The FOR loop opens the Cursor. do the necessary operations on the Record. Dept of IT. Narsapur .DBMS LAB MANUAL BEGIN SELECT SID INTO SID FROM SAILORS WHERE SNAME='&SNAME'.PUT_LINE(‘More than one Sailors with same name found’). returned from cursor. fetches rows and closes the cursor after all rows are processed. SNAME. END. But if we want to do automatic opening & closing to cursor then we can use FOR loop in cursor. FOR loop in Cursor The cursor FOR loop gives easy way to handle the Cursor. For Eg: FOR Z IN C1 LOOP ------END LOOP. RATING. OR CURSOR C1 IS SELECT * FROM SAILORS.PUT_LINE(‘No Sailors with given SID found’). The cursor FOR loop declares Z as record. DBMS_OUTPUT. EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT. BVRIT. AGE FROM SAILORS. / Cursors Oracle uses temporary work area cursor for storing output of an SQL statement.PUT_LINE(SID). / Same example using While DECLARE CURSOR C1 IS SELECT * FROM SAILORS. END.SID || ' ' || Z. FETCH C1 INTO Z. BEGIN FOR Z IN C1 LOOP DBMS_OUTPUT. WHILE (C1%FOUND) LOOP DBMS_OUTPUT.PUT_LINE (Z.SNAME). CLOSE C1. END LOOP. END LOOP.SID || ' ' || Z. BVRIT.PUT_LINE(Z. FETCH C1 INTO Z.SNAME). BEGIN OPEN C1.DBMS LAB MANUAL Example using Cursor DECLARE CURSOR C1 IS SELECT * FROM SAILORS. END. Z C1%ROWTYPE. Narsapur . / Dept of IT. PUT_LINE(Z. BEGIN IF(INPUT=’SAILORS) THEN DBMS_OUTPUT. END.COLOR). END LOOP.PUT_LINE(‘BOATS INFORMATION:’). END LOOP.SNAME||‘ ’||Z. CURSOR C3 IS SELECT * FROM RESERVES. Ex:.BNAME||‘ ’||X. etc) then we can write program as follows. BEGIN WHILE(I<=10)LOOP DBMS_OUTPUT.PUT_LINE(Z. FOR Z IN C1 LOOP IF(Z. ELSIF(INPUT=‘BOATS’)THEN DBMS_OUTPUT.PUT_LINE(‘SAILORS INFORMATION:’).SID||‘ ’||Z. DECLARE I INTEGER:=1. CURSOR C1 IS SELECT * FROM SAILORS. END IF. END LOOP.DBMS LAB MANUAL Suppose we want to display all sailors’ information according to their rating with proper heading. reserves according to users choice.PUT_LINE(‘SAILORS WITH RATING’||I).PUT_LINE(‘RESERVES INFORMATION:’). boats.We can use multiple cursors in a program. END LOOP.Display records according to rating with proper heading.RATING).RATING). Narsapur .SID||‘ ’||Z. BVRIT.BID||‘ ’||X. ELSIF(INPUT=‘RESERVES’)THEN DBMS_OUTPUT.AGE||‘ ’||Z.SNAME||‘ ’||Z.To display details of particular table sailors. FOR Z IN C1 LOOP DBMS_OUTPUT.RATING=I)THEN DBMS_OUTPUT. (eg: ‘Sailors with rating 1’…. Ex:. I:=I+1. Z C1%ROWTYPE.PUT_LINE(X.AGE||‘ ’||Z. / Multiple cursors in a program :. CURSOR C2 IS SELECT * FROM BOATS. CURSOR C1 IS SELECT * FROM SAILORS ORDER BY RATING. DECLARE INPUT VARCHAR2(30):= ‘&INPUT’.. Dept of IT. FOR X IN C2 LOOP DBMS_OUTPUT. / Deleting the Records :. Ex:.PUT_LINE(‘NO SUCH TABLE EXISTS’).DAY).Similar to inserting and updating the values as well as selecting the values we can use the PL/SQL programming for deleting the records from the given table. END. Ex:.SID||‘ ’||Y. / Passing parameters to Cursor We can pass parameters to cursor.Write a program to delete records from sailors table by reading SID from Keyboard. Z C1%ROWTYPE. END. BEGIN FOR Z IN C1 LOOP IF (Z. / Updating the Records :. When you open cursor the value is passed to cursor and processing can be done there in cursor definition.RATING>5 AND Z.BID||‘ ’||Y. END LOOP.RATING). END IF.SID||‘ ’||Z. END.SID. by 1 if rating is >5 and doesn’t change the rating if it is equal to 10.PUT_LINE (Z. Dept of IT. ELSE DBMS_OUTPUT. END IF. END LOOP.RATING<5) THEN UPDATE SAILORS SET RATING=RATING+2 WHERE SID=Z.RATING<10) THEN UPDATE SAILORS SET RATING=RATING+1 WHERE SID=Z.SID.Similar to inserting the values as well as selecting the values we can use the PL/SQL programming for updating the records in the given table. ELSIF (Z.DBMS LAB MANUAL FOR Y IN C3 LOOP DBMS_OUTPUT. Narsapur .PUT_LINE(Y.To update rating of sailors by 2 if rating is less than 5. FOR Z IN C1 LOOP DBMS_OUTPUT. DECLARE BEGIN DELETE FROM SAILORS WHERE SID=‘&SID’. END LOOP. BVRIT. DECLARE CURSOR C1 IS SELECT * FROM SAILORS. I INTEGER. BEGIN FOR I IN 1.. Already we have seen same program with parameters to the cursor. Narsapur . END LOOP. --Assume file name Cur_Par DECLARE CURSOR C1(R NUMBER) IS SELECT * FROM SAILORS WHERE RATING=R.10 LOOP DBMS_OUTPUT.suppose we want to display all sailors information according to their rating with proper heading. END LOOP.. BVRIT.AGE).PUT_LINE('SAILORS WITH RATING '|| I || ' ARE'). FOR Z IN C1(I) LOOP /* Its not compulsory to define variable using rowtype for simple cursor as well as for update cursor */ DBMS_OUTPUT. / Output SQL> @Cur_Par SAILORS WITH RATING 1 ARE 4 Hemant 18 1 SAILORS WITH RATING 2 ARE 5 Rajendra 30 2 SAILORS WITH RATING 3 ARE 6 Satish 20 3 SAILORS WITH RATING 4 ARE 7 Shrikant 21 4 SAILORS WITH RATING 5 ARE 8 Shabaz 19 5 10 Kaushal 20 5 SAILORS WITH RATING 6 ARE 12 RAJ 19 6 SAILORS WITH RATING 7 ARE 1 aravind 19 7 SAILORS WITH RATING 8 ARE 9 Guru 36 8 SAILORS WITH RATING 9 ARE 3 Vijay 32 9 SAILORS WITH RATING 10 ARE 2 Amar 87 10 11 SUNNY 20 10 Dept of IT. Following program illustrates how we can pass parameters to the cursor.SID ||' ' ||Z. etc).DBMS LAB MANUAL Ex:.PUT_LINE(Z. END. (eg: ‘Sailors with rating 1’….PUT_LINE('SID NAME AGE'). DBMS_OUTPUT.SNAME ||' '||Z. The valid Error_Code is in range from –20000 to –20999.RATING>5 AND Z.RATING<10) UPDATE SAILORS SET RATING= RATING+1 WHERE CURRENT OF C1. DECLARE CURSOR C1 IS SELECT * FROM SAILORS FOR UPDATE. END.'DIVISION BY ZERO'). Error_Message [. The optional third parameter TRUE indicates that error message is put in stack. Narsapur . Example to illustrate RAISE_APPLICATION_ERROR -. BEGIN IF(B=0)THEN RAISE_APPLICATION_ERROR(-20001. ELSE Dept of IT. END IF.DBMS LAB MANUAL PL/SQL procedure successfully completed. The Error_Message length is maximum 2048 bytes. Use of Cursor for Update (FOR UPDATE CURSOR. C INTEGER. B INTEGER:=&B. If FALSE is mentioned then error replaces all previous errors. WHERE CURRENT of clause and CURSOR variable is used). We can use update cursors for update operation only. ELSIF(Z. / Error Handling using RAISE_APPLICATION_ERROR Procedure RAISE_APPLICATION_ERROR is used to generate user-defined errors in the PL/SQL. The general syntax is RAISE_APPLICATION_ERROR(ErrorCode. The following example shows change of rating (Already we have written this program without using Update Cursor) using Update Cursor.Assume file name Raise_Application_Error DECLARE A INTEGER:=&A. BVRIT. END LOOP. TRUE/FALSE]). BEGIN FOR Z IN C1 LOOP /* Its not compulsory to define variable using rowtype for update cursor as well as for simple cursors */ IF(Z.RATING <=5) THEN UPDATE SAILORS SET RATING= RATING+2 WHERE CURRENT OF C1. 'HEMANT'.DBMS LAB MANUAL C:=A/B. Delete or Update) operations for Savepoint & Rollback.e.10. ENTER VALUE FOR B: 2 OLD 3: B INTEGER:=&B. SQL> @Raise_Application_Error ENTER VALUE FOR A: 15 OLD 2: A INTEGER:=&A. ENTER VALUE FOR B: 0 OLD 3: B INTEGER:=&B. UPDATE SAILORS SET SNAME='RAJENDRA' WHERE SID='10'. Savepoint & Rollback in PL/SQL We can use these commands in PL/SQL. The following program inserts a record into Sailors table then updates a record before we Commit a Savepoint is defined and we can use Rollback to undo the operations we have done after the Savepoint (i. We can use any (Insert. END IF. DELETE FROM SAILORS WHERE SID='11'. BEGIN INSERT INTO SAILORS VALUES('32'.PUT_LINE('RESULT IS :'||C). END. DECLARE * ERROR at line 1: ORA-20001: DIVISION BY ZERO ORA-06512: at line 8 Use of Commit. / Output SQL> @Raise_Application_Error ENTER VALUE FOR A: 12 OLD 2: A INTEGER:=&A. NEW 3: B INTEGER:=0. Narsapur . We can define number of Savepoint statements in a program and Rollback to any point. RESULT IS :6 PL/SQL procedure successfully completed. SAVEPOINT S1. NEW 2: A INTEGER:=12. NEW 2: A INTEGER:=15. NEW 3: B INTEGER:=2. DBMS_OUTPUT. Dept of IT. 30). deleting a Sailors record is undone). BVRIT. Dept of IT. To create Procedure (before calling from other program. END.) IS (Or we can write AS) Local declarations.) SQL> @File_Name To use/call procedure. Narsapur . EXCEPTION Exception Handlers. ……. BVRIT. The general syntax of procedure is CREATE OR REPLACE PROCEDURE <Pro_Name> (Par_Name1 [IN/OUT/ IN OUT] Par_Type1. IN acts as a constant and any attempt to change its value causes compilation error. Inside the procedure/function.IN mode is used to pass a value to Procedure/Function. …. Or you can execute from SQL Prompt as SQL>execute Pro_Name(Par_List) For dropping Procedure/Function (Function described next) SQL>DROP PROCEDURE Pro_Name. • • • • For writing Procedures we can directly type at SQL prompt or create a file. SQL> ed File_Name Type & save procedure. BEGIN PL/SQL Executable statements. 3) IN OUT Mode : IN OUT parameter is used to pass a value to a subprogram and for getting the updated value from the subprogram.DBMS LAB MANUAL ROLLBACK TO S1. / (You can even read these values from Keyboard) Procedure in PL/SQL Procedures are written for doing specific tasks. END <Pro_Name>. write a PL/SQL code and include call in the code using Pro_Name(Par_List). Mode of parameters 1) IN Mode :. 2) OUT Mode : The OUT parameter is used to return value to the calling routine. COMMIT. Examples 1) Simple program to illustrate Procedure. SQL>DROP FUNCTION Fun_Name. Any attempt to refer to the value of this parameter results in null value. PUT_LINE('X:'||X). BEGIN X:=10. DBMS_OUTPUT. END P1. END.PUT_LINE('A:'||A). / -. 2) Program to illustrate Procedure with IN mode parameter. BVRIT. / Now write PL/SQL code to use procedure in separate file.PUT_LINE('A:'||A). -.Assume file name P2 CREATE OR REPLACE PROCEDURE P2(A IN NUMBER) AS BEGIN DBMS_OUTPUT. SQL>@testP1 A:100 PL/SQL procedure successfully completed. Narsapur . P2(X). DBMS_OUTPUT. -.Assume file name testP1 DECLARE BEGIN P1(100). / Output SQL> @P1 Procedure created.PUT_LINE('X:'||X).Assume file name testP2 DECLARE X NUMBER.DBMS LAB MANUAL -.Assume file name P1 CREATE OR REPLACE PROCEDURE P1(A NUMBER) AS BEGIN DBMS_OUTPUT. / Output SQL> @P2 Procedure created. END. END P2. SQL>@testP2 X:10 A:10 Dept of IT. P3(X). BEGIN X:=10. 4) Program to illustrate Procedure with OUT mode parameter. DBMS_OUTPUT. BVRIT. / -. DBMS_OUTPUT.Assume file name testP3 DECLARE X NUMBER.Assume file name P4 CREATE OR REPLACE PROCEDURE P4(A OUT NUMBER) AS BEGIN DBMS_OUTPUT. END P4.PUT_LINE('A:'|| A).PUT_LINE('A:'||A).Assume file name testP4 DECLARE X NUMBER. SQL>@testP3 X:50 A:100 X:100 PL/SQL procedure successfully completed. BEGIN X:=50.PUT_LINE('X:'||X). 3) Program to illustrate Procedure with OUT mode parameter. END. END P3.PUT_LINE('X:'||X).DBMS LAB MANUAL X:10 PL/SQL procedure successfully completed.Assume file name P3 CREATE OR REPLACE PROCEDURE P3(A OUT NUMBER) AS BEGIN A:=100. -. / -. -. Dept of IT. / Output SQL> @P3 Procedure created. DBMS_OUTPUT. Narsapur . DBMS_OUTPUT.PUT_LINE('X:'||X). BVRIT. Dept of IT. DBMS_OUTPUT.Assume file name testP5 DECLARE X NUMBER. END. SQL>@testP5 X:10 A:10 X:10 PL/SQL procedure successfully completed.PUT_LINE('X:'|| X). 5) Program to illustrate Procedure with IN OUT mode parameter. BEGIN X:=10.PUT_LINE('X:'||X). SQL>@testP4 X:10 A: X: PL/SQL procedure successfully completed. / Output SQL> @P5 Procedure created.PUT_LINE('A:' || A). --Assume file name P5 CREATE OR REPLACE PROCEDURE P5(A IN OUT NUMBER) AS BEGIN DBMS_OUTPUT. / Output SQL> @P4 Procedure created. P5(X).PUT_LINE('X:'|| X). END P5. DBMS_OUTPUT. Narsapur . DBMS_OUTPUT. END.DBMS LAB MANUAL P4(X). / -. The syntax of function is CREATE OR REPLACE FUNCTION <Fun_Name> (Par_Name1 [IN/OUT/ IN OUT] Par_Type1. / Output SQL> @Fun Dept of IT. 1) Write a PL/SQL code and include call in the code using x=Fun_Name(Par_List).DBMS LAB MANUAL Functions in PL/SQL Similar to Procedure we can create Functions which can return one value to the calling program. END <Fun_Name>.) SQL> @File_Name • To use/call Function we have two ways. 2) You can execute from SQL Prompt as a select query SQL>Select Fun_Name(Par_List) from Dual.Assume file name testFun DECLARE X NUMBER:=&X.Program to illustrate Function. (Finding Square of a number) -. / -. SQL> ed File_Name • Type & save Function. ….PUT_LINE('SQUARE OF A NUMBER'|| S). EXCEPTION Exception Handlers. Ex :. END. ……. BVRIT. S NUMBER. BEGIN PL/SQL Executable statements. Narsapur . • To create Function (before calling from other program. DBMS_OUTPUT.) RETURN return_datatype IS Local declarations.Assume file name Fun CREATE OR REPLACE FUNCTION FUN(A NUMBER) RETURN NUMBER IS BEGIN RETURN (A*A). • For writing Function we can directly type at SQL prompt or create a file. END FUN. BEGIN S:=FUN(X). Dept of IT. SQUARE OF A NUMBER100 PL/SQL procedure successfully completed.DBMS LAB MANUAL Function created. Narsapur . BVRIT. NEW 2: X NUMBER:=10. SQL> @testFun ENTER VALUE FOR X: 10 OLD 2: X NUMBER:=&X.
Copyright © 2022 DOKUMEN.SITE Inc.