DBMS Manual-1
DBMS Manual-1
15 EX 3. BUILT-IN FUNCTIONS.......................................................................16 EX 4. JOINS, SET OPERATORS, NESTED QUERIES.............................17 PL/SQL - INTRODUCTION..........................................................................18 CURSORS.........................................................................................................22 TRIGGERS.......................................................................................................24 PROCEDURES AND FUNCTIONS..............................................................26 EX 5. SIMPLE PL/SQL PROGRAMS..........................................................29 EX 6. PL/SQL PROGRAMS - CURSORS....................................................30 EX 7. PL/SQL PROGRAMS - TRIGGERS..................................................31 EX 8. PROCEDURES AND FUNCTIONS...................................................32 MINI PROJECT..............................................................................................33 EX 9. DCL COMMANDS...............................................................................39 ...........................................................................................................................39 1. Create a new user......................................................................................39
DBMS INTRODUCTION
A data base management system is a collection of programs that enables users to create and maintain a database. DBMS is a general purpose software system that facilitates the process of defining, constructing, manipulating databases for various applications. Functions of DBMS Database Definition Database Creation Data Retrieval Updating how data is to be stored and organized storing data in a defined database Querying and reporting changing the contents of the data base
Programming user facilities for system development. Database revision and restructuring Database integrity control. Performance monitoring. RDBMS RDBMS is a database management system where all data visible to the user is organized strictly as tables of data values and all database operations work on these tables. SQL A standard query language that is commonly used with all relational databases for data manipulation and definition. Based on the type of action that each command performs, SQL commands can be broadly classified as follows:
Classifications DDL(Data definition language) DML(Data manipulation language) DCL(Data control language) TCL(Transaction control language) Queries
Description Used to define the structure of a table, or modify the structure. Used to manipulate with the data. Used to restrict or grant access to tables Used to complete fully or undo the transactions Used to select records from the tables or other objects.
Data Types Character Date Raw Long Long Raw Lob Default format DD-MON-YY Char(n) Varchar2(n)
Numeric Number(p,s)
1. To create a table Create table <table name>(columnname1 data type(size), Columnname N data type(size));
3. To insert data a. Adding a row to the table Insert into <table name> values (value1 for column1,value2 for column2,.Value n for column n); b. Inserting records through user interaction Insert into <table name>values(&column name1,& column name2,& column name3,. ..,& column name4); ..column n) value n for c. Insert a partially filled record into a table Insert into <table name>(column1,column3, values(value1 for column1,value3 for column3,. column n); 4. To view the entire table Select * from <table name>; 5. To view selective columns of the corresponding table Select column name1, column name2 from <table name>; 6. To view existing tables of the user Select * from tab; 7. To modify table structure a. Adding a new column Alter table <table name> add (new column name datatype(size)); b. Modifying existing columns datatype or size Alter table <table name> modify(existing column name data type(size));
8. To edit data Update <tablename> set <column name1> = <value1>,<column name2> = <value2>, . [where <condition>]; 9. To delete a record Delete <table name> [where <condition>]; 10. To create a duplicate table Create table <new table name> as <Select statement> 11. To delete a table Drop table <table name> 12. To display Virtual or calculated column Columns with values that are calculated from the values of the existing column are known as virtual columns. Select column name1,column name4, [calculation on existing columns] <alias name of virtual column> from <table name>; 13. Conditional retrieval of data We can retrieve data that satisfies certain conditions.These conditions are framed by using the relational operators and logical operators.Besides these Oracle8 has its own operators such as Like, NULL, IN etc. classified as OTHERS which can be used in conditional retrieval of data. Relational operators - = , <> , < , <= , > , >= = <> operator is used to compare two values for equality operator is used for inequality comparison
Others - in , between and , like% , like _ , is NULL in - operator is used to retrieve data which matches a specific list of values between and - operator is used when data needs to be retrieved for a specific
range of values Like Using simple = comparison test we are able to retrieve rows where the contents of a text column match some particular text. Suppose we may not be able to remember the entire pattern, if it is a lengthy one, Like operator can be used to retrieve rows which will match a specified pattern. The pattern is a string that may include one or more wildcard characters % or _ . Like % When data needs to be retrieved which matches any sequence of zero or more characters, wildcard % is used. Like _ To match a single character in a pattern, wild card _ is used. Is NULL Null value is an indicator that tells that the data is inapplicable, unknown or missing. Logical operators - and , or , not Used to produce a single result by combining two separate conditions. And When you want the rows to be retrieved should satisfy both the conditions then AND operator can be used. Or When you want the rows to be retrieved to satisfy either of the conditions then OR operator can be used. Not Sometimes you need to negate a condition . For this NOT operator can be used. Not can be used with all the operators discussed so far, such as IS NOT NULL,NOT BETWEEN . And, NOT LIKE.
Ordering data Data that is displayed using SELECT statement can be arranged in a particular Columns order i.e. ascending or descending .By default columns are ordered in ascending order . To change the order of display in reverse direction (descending) Desc keyword is used in the order by. Select <column list> from <table name> order by <column name> asc/desc The Syntax for a simple query is Select <column list> from <table name> [where <condition>] [group by <column name>] [having <condition>] [order by <expression>]; 14. To create constraints on the table Constraints can be defined at two levels- Column or table. Column constraints Create table <table name>(column name1 data type(size) constraint <constraint name> primary key, column name2 data type(size) constraint <constraint name> references referenced table name [(primary column name of referenced table)], column name3 data type(size) constraint <constraint name> check(<condition>), column name data type(size) NOT NULL); Table constraints Those constraints which refer other columns of the table should be defined at the table level. Create table <table name> (column name1 data type(size), . Column name N data type(size), Constraint <constraint name> primary key((column name1),
Constraint <constraint name> foreign key(foreign column name) references referenced table name[(primary column name of referenced table)], constraint <constraint name> check (<condition>));
BUILT-IN FUNCTIONS
Introduction Built-in functions are predefined functions that perform a specific task.Built-in functions based on the values that they take to perform a task, can be classified into two types. They are 1. Scalar or single row function 2. Aggregate or group function Scalar functions Number functions Character functions Date functions Conversion functions Other functions Number functions ABS(n) FLOOR(n) CEIL(n) EXP(n) LN(n) LOG(n) MOD(n) POWER(m,n) ROUND(n[,m]) SIGN(n) SQRT(n) TRUNC(n[,m])
Character Functions a. returning number values ASCII(char) INSTR(char1,char2[,n[,m]]) INSTRB(char1,char2[,n[,m]]) LENGTH(char) LENGTHB(char)
b. returning char value CHR(n) CONCAT(char1,char2) INITCAP(char) LPAD(char1,n[,char2]) LTRIM(char[,set]) REPLACE(char,search-string[,replacement-string]) RPAD(char1,n[,char2]) RTRIM(char[,set]) SOUNDEX(char) SUBSTR(char,m[,n]) SUBSTRB(char,m[,n]) TRANSLATE(char,from,to) UPPER(char) LOWER(char)
ROUND(d[,fmt]) TRUNC(d[,fmt])
Date format elements Element Meaning YYYY 4 digit year YY Last 2 digits of year MM Month(01-12 ; Jan=01) MONTH Name of month, MON Abbreviated name of month DDD Day of year(1-366) DD Day of month(1-31) D Day of week(1-7) DAY Name of day DY Abbreviated name of day HH or HH12 Hour of day(1-12) HH24 Hour of day(0-23) MI Minute(0-59) SS Second(0-59) Conversion Functions TO_CHAR(d[,fmt]) TO_CHAR(n[,fmt]) TO_DATE(char[,fmt]) TO_NUMBER(char[,fmt[,'nlsparams']])
10
11
Non-Equi join Non-equi joins specify the relationship between the tables not in terms of columns but in the terms of relational operators or any comparison operators used. SET OPERATORS SET operators combine the results of two component queries into a single result. Queries containing set operators are called Compound queries.The set operators are Union Union all Intersect Minus Union Union operation performed on two tables yields records from both the tables without the values being repeated. Union All Union operation performed on two tables yields records from both the tables with duplication. Intersect Intersect operation performed on two tables yields records that are common and distinct.
Minus All the distinct rows selected by the first query but which are not in the second query are listed.
SUB QUERIES 12
A sub query is a query that can contain multiple query statements each nested within another. It is also called as a nested query. Statement containing a sub query is called the parent statement and the query inside is called the child query. Parent statement uses the rows returned by the child query. If the inner query returns only one value the outer query can process and display values that match the condition. If more than one value is selected, Oracle8 requires an operator that can check and display the values. To do this operation the following operators are used. Any All Some Exists
13
EX 1. DDL COMMANDS
1. Create a table Department with the following structure (Column level constraints) Depno Depname Deplocation Empno Empname Designation Date_of_join Salary Depno Coursecode Coursename Rollno Name Coursecode Mark1 Mark2 Number(2) Varchar2(15) Varchar2(10) Number(5) Varchar2(20) Varchar2(10) Date Number(9,2) Number(2) Number(2) Varchar2(15) Number(5) Varchar2(15) Number(2) Number(3) Number(3) Foreign key(Reference Course table) Check constraint value between 0&100 Check constraint value between 0&100 Primary key Foreign key(Reference Department table) Primary key NOT NULL Primary key Primary key
5.Display the structure of the tables Employee, Department, Course, Student 6. Add the column Phoneno Number(10) , Grade Varchar2(1) in the Employee table 7. Change the column size of Deplocation column in the Department table from 10 to 15. 8.Change the data type of the column Rollno from numeric to character. 9. Drop the column Mark2 in Student table. 10. Display the names of the table created by the current user 11. Delete the contents of the table Student. 12. Delete the table Student 13. Rename the table Employee as Emp.
14
EX 2. DML COMMANDS
1. Insert into the table Department the following values Depno 01 02 03 04 05 06 Depname SALES PURCHASE PRODUCTION MARKETING ACCOUNTS SOFTWARE Deplocation blocka blockd blockb blocka blockc blocke
2. Insert into the table Employee the following values Empno 1 2 3 4 5 6 7 8 9 10 Empname Siva Mani Raju Babu Ram Velu Ravi Balan Mahesh Kumar Designation Manager Salesman Clerk Clerk Salesman programmer accountant Manager Officer Analyst Date_of_join 05-Oct-1987 12-Apr-1987 30-Nov-1989 04-Jan-1995 08-Dec-2000 24-Feb-2002 12-Sep-1991 07-Jun-1993 18-Mar-1997 15-Jan-1995 Salary 15000.00 5000.75 7000.00 5000.50 3000.25 10000.50 8000.25 12000.75 10000.50 14500.00 Depno 05 01 02 03 01 06 05 03 02 06 Grade A F E E F D G A B C
3. Display all the columns of the table Employee, Department 4. Insert values for the column Phoneno in the Employee table and Display empname , Phoneno for all the employees.(Use Update command) 5. Create a duplicate employee table called Emp 6. Display Empname, Designation, Years-of-service(Virtual column or calculated column) for all the employees. Calculate Years-of-service by subtracting date-of-join from current date. 7. Create a view with the fields Empname , Designation, Depname 8. List the employees whose salary is equal to Rs.10,000.50(Use = operator) 9. List the employees whose depno is not equal to 01(Use <> operator) 10. List the employees who have joined after 04-Apr-1995 (Use > operator) 11. List the employees who belongs to the department 2, 3, 5(Use IN operator)
15
12. List the employees who have joined after 01-Jan-1988 and before 01-Jan-1998(Use Between and operator) 13. List the employees whose name starts with the letter R(Use LIKE operator) 14. List the employees whose name second letter should be a(Use LIKE operator) 15. List the employees who dont have phone numbers(Use IS NULL operator) 16. List the employees who belong to department 01 .Also salary equal to 5000.75(Use AND operator) 17. List the employees either belongs to department 01 or salary equal to 5000.50(Use OR operator) 18. List the employees whose designation is other than Manager, Officer(Use NOT operator) 19. List the department details in the descending order of department name. 20. Delete the records of the employees who have joined before 01-Jan-1989
EX 3. BUILT-IN FUNCTIONS
String Functions 1. Find the length of the column Designation 2. Display the first three characters of Department name 3. Change all BlockA in Deplocation column as BlockF 4. Remove the 0 s in the strings ABC0000, 000ABC
16
5. Display the distinct Designations in title case 6. Display the Depname in lower case 7. Display the Deplocation in upper case 8. Translate Grade to the corresponding designation Numeric Functions 9. Find the total number of employees. 10. Find the employee with maximum salary, minimum salary in each department in the ascending order of depno. 11. Find the total salary paid to the employees. 12. Find the average salary paid to the employees. 13. Display the rounded value of the salary column in Employee table. 14. Display the salary such that it contains no decimal places. Date Functions 15.Display the system date in the format mentioned below 27th October 1996. 16.Display 20th September 1996 in the date format. 17.Display the date two months after the date-of-join for all the employees. 18.Display the last date of the month in the date-of-join for all the employees. 19.Display the months between the current date and the date-of-join. 20.Display the next occurrence of Friday to the current date. 21.Display the first day of the year 2000. * Use Employee and Department tables .
17
(Use Non-Equi join) * Use Employee and Department tables . Set Operators 1. List the products available in both the tables without duplication. 2. List the products available in both the tables with duplication. 3. List the products common to both the tables . 4. List the products available in Product 1 table but not available in Product 2 table. * Use the following tables Product 1 Item code Item name Sub Queries 1. Find the employee with the maximum salary. 2. List the employees having salary greater than the lowest of the average salary of departments.(Use ANY operator) 3. List the employees having salary lower than the greatest of the average salary of all departments.(Use ALL operator). 4. List the departments where there are employees functioning. (Use EXISTS operator) 5. List the details of the employees belonging to Software department. Varchar2(5) Varchar2(10) Product 2 Item code Item name Varchar2(5) Varchar2(10)
PL/SQL - INTRODUCTION
Oracle's PL/SQL is a procedural language extension of SQL.PL/SQL is a block-structured language. The basic unit of PL/SQL is called a BLOCK, which contains declarative statements and error handling statements. These blocks can be nested into one or more blocks. ADVANTAGES OF PL/SQL Sql support
18
Better performance Support for object oriented programming Portability Higher productivity Integration with oracle
DATA TYPES Every constants and variable has a datatype that specifies a storage format and valid range of values. Apart from the data types that are available in SQL,PL/SQL has its own set of datatypes that can be used in PL/SQL blocks. Numbered datatypes For numeric data and to represent quantities, calculations can be performed on this datatype . Binary_integer For storing signed integers, its magnitute ranges from -2147483647 to 2147483647.It has various subtypes: NATURAL NATURALN POSITIVE POSITIVEN SIGNTYPE
Collection datatypes A collection is an ordered group of elements ,all of the same type. Each element has a unique subscript that determines the position of the collection. Boolean datatypes Logical values TRUE, FALSE or NULL can be stored using BOOLEAN datatypes. The datatype has no parameters. Exception datatypes
19
This is a datatype that is used to define exception or error handlers, which is defined by the user. A Simple Program DECLARE X NUMBER; BEGIN X:=26; DBMS_OUTPUT.PUT_LINE(X); END; The above program displays the value 26 which is stored in the variable X. Using the SELECT statement inside the PL/SQL The SELECT statement selects a set of records from the database. To display a condition based record, the SELECT statements requires an INTO clause. A SELECT statement must hold an INTO clause where the output of the query is assigned to the variable given in the INTO clause. DECLARE s NUMBER; BEGIN SELECT sal INTO s FROM emp WHERE empno=7369; DBMS_OUTPUT.PUT_LINE(!the salary is !||s); END; The variable s is assigned the salary of the employee number 7369 and the result would be displayed. DECLARING VARIABLES Variables can be declared in various ways.They are:
20
1)Using DEFAULT: DECLARE s NUMBER DEFAULT 10; BEGIN DBMS_OUTPUT.PUT_LINE(s); END; This program displays the default value of s i.e 10 is printed. 2)Using CONSTANT: Pi CONSTANT REAL:=3.14; 3)Using NOTNULL: s VARCHAR(10) NOTNULL:='RADIANT'; CONTROL STRUCTURE There are three forms of IF statements: IF...THEN IF...THEN...ELSE IF...THEN...ELSEIF ITERATIVE CONTROL Iterative statements are the statements that are performed a number of times depending o the value in the LOOP statement. There are three various forms of LOOP statements: 1)LOOP Sequence_of_statements; EndLOOP 2)While condition loop
21
Sequence_of_statements; ENDLOOP; 3)FOR counter IN [REVERSE] lower_ bound.. higher_ bound LOOP sequence_ of_ statements; ENDLOOP; 4)BEGIN .... EXIT WHEN<CONDITION>; In the LOOP statement, each loop can be given different names: <<label_ name>> LOOP Sequence_ of_ statements; ENDLOOP;
CURSORS
Oracle uses work areas to execute SQL statements and store processing results. A PL/SQL construct called Cursor allows a work area to be named, to store and access its information. They are typically used in areas where the query inside the PL/SQL block retrieves more than one record. A cursor is a pointer to handle the context area or the memory area or work area. The result set of information is called Result Set. When a query inside a PL/SQL block returns more than one record or one set of data, Oracle requires a placeholder to place the values. The variables provided in the INTO clause can contain only one value at a time. In order to process multiple records, CURSORS are used. Types of Cursors PL/SQL implicitly declares a cursor for all SQL data manipulation statements, including
22
queries that return only one row. Cursors can be of 2 types. Explicit Cursors Explicit cursor manipulation is performed using four commands. DECLARE OPEN FETCH CLOSE Implicit Cursors Explicit Cursors
Declaring a Cursor Syntax: CURSOR <cursor name> IS <query> Example CURSOR C1 is SELECT ename, job FROM emp ; Opening a Cursor Syntax: OPEN <cursor name> Example OPEN C1; Fetching Records from the cursor Syntax: FETCH <cursor name> INTO <variable list> Example FETCH C1 INTO x, y ; Closing a Cursor CLOSE statement releases the data within the cursor and closes it. The cursor is reopened to refresh its data. Example 23
This example is used to select all the employees names and their jobs from the table. DECLARE CURSOR c1 IS SELECT ename, job FROM emp; Mname VARCHAR2 (20) ; Mjob VARCHAR2 (20) ; BEGIN OPEN c1; LOOP FETCH c1 INTO mname, mjob; DBMS_OUTPUT.PUT_LINE(mname || ` is a ` || mjob); END LOOP; CLOSE c1; END; The output of this program is, KING is a PRESIDENT.
TRIGGERS
A database trigger is a stored PL/SQL block that is associated with a table. Triggers are automatically executed when a specified SQL statement is issued against the table. Triggers are mainly used for the following purposes: To automatically generate values. To provide auditing. To prevent invalid transaction. To check for complex integrity constraints that cannot be given in constraints. To maintain replicate tables. Trigger contain PL/SQL constructs and they can be fired only for DML statements like INSERT, UPDATE and DELETE. Triggers are event based. Parts Of Trigger 24
A Trigger contains three parts: Types Of Trigger Triggers are classified into different types depending on when the trigger is to be fired. They are: Creating Triggers Triggers are created using CREATE TRGGER statement. The name of the trigger must be unique with respect to other triggers in the same schema. The syntax for creating the trigger is: Syntax: CREATE OR REPLACE TRIGGER <trigger name> [BEFORE/AFTER] [INSERT/UPDATE/DELETE] ON <table name> [FOR EACH ROW][WHEN <condition>] Example: CREATE OR REPLACE TRIGGER instremp BEFORE INSERT ON emp BEGIN DBMS_OUTPUT.PUT_LINE(`inserting record`); END; The trigger gets created. When an insert statement is issued,the output will look like: INSERT INTO emp (empno, ename) VALUES (1,RAM); This would display, Inserting Record. 1 row created. 25 BEFORE AFTER INSTEAD OF Triggering event or statement Trigger restriction Trigger action
Control indirect access to objects from non privileged users with security privileges. Ensure that related actions are performed together, or not at all, by funneling actions for related tables through a single path.
2. Improved performance.
o o o
Avoid reparsing for multiple users by exploiting shared SQL. Avoid PL/SQL parsing at run time by parsing at compile time. Reduce the number of calls to the database and decrease network traffic by bundling commands.
3. Improved maintenance.
o o o
Modify routines online without interfering with other users. Modify one routine to affect multiple applications. Modify one routine to eliminate duplicate testing.
Procedures are simply a named PL/SQL block, they are created by a particular schema and like other database objects are then owned by that schema. Rights to the procedure are granted /
26
revoked just like any other object except that you grant / revoke the EXECUTE right and not SELECT, UPDATE etc. An example of an unnamed block is given below :DECLARE TEMP_COST NUMBER(10,2); BEGIN SELECT COST INTO TEMP_COST FROM BOOK WHERE ISBN = 21; IF TEMP_COST > 0 THEN UPDATE BOOK SET COST = (TEMP_COST*1.175) WHERE ISBN = 21; ELSE UPDATE BOOK SET COST = 21.32 WHERE ISBN = 21; END IF; COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN INSERT INTO ERRORS (CODE, MESSAGE) VALUES(99, ISBN 21 NOT FOUND); END;
This block could be saved to a command file and executed from there but it would be parsed each and every time it was called. To save this block to the database we need to name it.
CREATE OR REPLACE PROCEDURE MYPROC1 (TEMP_COST NUMBER(10,2)) IS BEGIN SELECT COST INTO TEMP_COST FROM BOOK WHERE ISBN = 21; IF TEMP_COST > 0 THEN UPDATE BOOK SET COST = (TEMP_COST*1.175) WHERE ISBN = 21; ELSE UPDATE BOOK SET COST = 21.32 WHERE ISBN = 21; END IF; COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN INSERT INTO ERRORS (CODE, MESSAGE) VALUES(99, ISBN 21 NOT FOUND); END MYPROC1;
The procedure (named MYPROC1) is defined in the first line. CREATE OR REPLACE asks Oracle to create a new procedure or if a procedure with this name already exists in this schema to replace it (you may leave out the OR REPLACE if you don't want this to happen). The DECLARE section is now implicitly the section between the procedure definition and the IS BEGIN statement - it is not explicitly named but is enclosed within brackets. The END statement now ends a named block rather than an unnamed block. Nothing else is required for a procedure to run. To execute the stored procedure simply call it by name. 27
To get values into and out of the procedure, we can define variables in the implicit declare section as IN, OUT or IN OUT.
CREATE OR REPLACE PROCEDURE MYPROC1 (REQISBN IN NUMBER, MYVAR1 IN OUT CHAR, TCOST OUT NUMBER) TEMP_COST NUMBER(10,2)) IS BEGIN SELECT COST INTO TEMP_COST FROM BOOK WHERE ISBN = REQISBN; IF TEMP_COST > 0 THEN UPDATE BOOK SET COST = (TEMP_COST*1.175) WHERE ISBN = REQISBN; ELSE UPDATE BOOK SET COST = 21.32 WHERE ISBN = REQISBN; END IF; TCOST := TEMP_COST; COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN INSERT INTO ERRORS (CODE, MESSAGE) VALUES(99, ISBN NOT FOUND); END MYPROC1;
EXECUTE MYPROC1 (21, :PCOST) - will execute the procedure in SQL *PLUS (PCOST is the name of a SQL *PLUS bind variable). 21 will be passed into the procedure, the value of TCOST will be passed out of the procedure and stored in :PCOST. An IN OUT variable can pass values both in and out of a procedure. A procedure can read in a list of values but won't directly return any value (it may indirectly return values). A function can also read in a list of values but will explicitly return a single result which is normally assigned to a variable or used in a program control structure condition test (IF statements etc). The function below demonstrates the syntax of a PL/SQL function block, note that as with a procedure the OR REPLACE clause can be left out if you don't want the replacement of an existing function with the same name. Function definitions vary from procedure definitions in that you must explicitly name a variable to return and you must return a value in the variable via the RETURN statement.
CREATE OR REPLACE FUNCTION MYFUNC1 RETURN NUMBER IS RCOST NUMBER(10,2); BEGIN
28
SELECT COST INTO RCOST FROM BOOK WHERE ISBN = 21; RETURN (RCOST); END MYFUNC1;
EXECUTE :PCOST := MYFUNC1 - will execute the procedure in SQL *PLUS (PCOST is the name of a SQL *PLUS bind variable). The purchase value of book 21 will be passed out of the function and stored in :PCOST.
1. Write a PL/SQL block to find the factorial of a given number. 2. Write a PL/SQL block to find the sum of Odd Numbers using for loop. 3. Write a PL/SQL block to generate the Fibonacci series.
29
4. Write a PL/SQL block to find out whether the given number is a prime number or not. 5. Write a PL/SQL block to find the GCD of Two Numbers Using While Loop. 6. Write a PL/SQL block to find the Biggest of Three Numbers Using NESTED IF.
Do It Yourself
1. Write a PL/SQL block to find whether the given number is odd or even 2. Write a PL/SQL block to find the sum of N natural numbers 3. Write a PL/SQL block to find whether a year is leap year or not 4. Write a PL/SQL block to display a particular item details. Display appropriate message if the item is not found. 5. Write a PL/SQL block to find whether the given number is Even or Odd using Case Expression
Write a PL/SQL block using cursor to display empname, designation and department name
30
2 3 4 5 6 7
Write a PL/SQL block using cursor to display empname, designation and department location (Use for loop) Write a PL/SQL block using cursor to display empname, designation and salary(Use %rowtype) Write a PL/SQL block using cursor to update the employee table. Increment salary of manager by 1000 and salary of clerk by 300. Write a PL/SQL block using cursor to display the total number of records, first, second, last, last but previous records and delete a record. Write a PL/SQL block using cursor to display the contents of various tables based on the options(Using Constrained variables) Write a PL/SQL block using cursor to display the contents of various tables based on the options(Using UnConstrained variables)
Do It Yourself 1 2 Write a PL/SQL block using cursor to display the order details Write a PL/SQL block using cursor to update the order status as p if the order date is less than the delivery date
31
3 4 5
Write a database trigger to display the total number of records after inserting a record into the table Write a database trigger to check for the availability of department number in the department table, before inserting or updating a record in the employee table. Write a database trigger to check for the job equal to manager and the corresponding salary between 4000 and 6000 after inserting into the table with allowing the record to be inserted. Write a database trigger to check for the job equal to manager and the corresponding salary between 4000 and 6000 after inserting into the table without allowing the record to be inserted. Deactivate a trigger and then activate it again. Delete a trigger. Disable all triggers in a particular table and then enable them again.
7 8 9
Do It Yourself 1. Create two tables named voters_master and voters_passed with appropriate data types to illustrate the functioning of the triggers. Insert the required values in the voters_master table. Write a database trigger to delete the details of the voters from voters_master whenever a row is inserted in the table voters_passed. 2. Create necessary Library relation and insert values. Create the structure of Summary table. Write a database trigger to find the number of copies of books with respective to book number and insert values into Summary table.
32
3 4 5 6 7
Write a PL/SQL procedure which accepts item code as input and displays the item name and item rate as output. Write a PL/SQL procedure which accepts depno as input and increase the salary of the corresponding department employees by 10% in the employee table. Write a PL/SQL function which accepts depno as input and return the department name as output. Write a PL/SQL function to calculate the total salary for a given department. Write a PL/SQL function to display the Fibonacci series.
Do It Yourself 1 2 3 4 5 Write a PL/SQL function to find the factorial of a given number. Write a PL/SQL procedure using cursor to display the employee name, salary, depno for a given depno. Write a PL/SQL procedure to update the total field by adding the 3 marks. Write a PL/SQL procedure to display the details of the employees from employee table whose designation is manager. Write a PL/SQL procedure to find the grade of the employees according to their salary Salary > 20,000 Salary > 15,000 Salary > 10,000 Salary < 10,000 6 7 Grade A Grade B Grade C Grade D
Write a PL/SQL function to count the number of employees in a particular department. Write a PL/SQL function which accepts empno as input and return the salary as output.
MINI PROJECT
Back End : Back end is used to store the data. The following are the examples of Back ends : 1. Oracle8 2. Ms Access 33
3. SQL Server Front End : Front end provide user friendly interface to accept input commands and data and to display the results in the required Format. The following are the examples of Front ends : 1. Power Builder 2. Visual Basic6.0 3. Developer 2000 VISUAL BASIC6.0 Visual Basic6.0 is a front end tool that allows you to develop Windows (Graphical User Interface - GUI) applications. Visual Basic6.0 is event-driven, means that code remains idle until called upon to respond to some event (button pressing, menu selection, ...). Visual Basic6.0 is governed by an event processor. Nothing happens until an event is detected. Once an event is detected, the code corresponding to that event (event procedure) is executed. Program control is then returned to the event processor. ODBC : (Open DataBase Connectivity) ODBC Interface allows front end applications to access the data from the backend. Data Access Features: Visual Basic6.0 provides a rich set of data access features such as Data control Data Access object(DAO) Remote Data Control(RDC) Remote Data Object(RDO) ActiveX Data Object Data Control(ADODC) ActiveX Data Object(ADO) Data control : A data control binds data aware to Microsoft access or to other ODBC data sources, enabling to move from record to record and to display and manipulate data from the 34
records in bound controls.A bound control is a control that is assigned to a field in a database. Most data access operations can be performed with a data control without writing any code. If a database and a record source a table, a view, a SQL statement is set to a data control, then it is automatically populated with data from that has the data control, is activated. Data Access object(DAO): Data Access objects communicate with Microsoft access and other complaint data sources through the jet engine. They provide properties and methods that allow to perform all the operations necessary to manage such a system. When to use DAO : DAO is the only data access technology that supports 16 - bit operations. If an application must run within a 16 bit environment, the DAO is the only choice. If the application must access both native Microsoft Jet and ODBC resources, DAO provides a consistent programming model. Remote Data Control(RDC) The Remote Data Control is another way for accessing remote data in Visual Basic6.0 applications. The user can interact data through the user interface controls like browsing the data, performing updates and adding records. Remote Data Control binds data aware controls to an ODBC remote database, and the remote data object. The Remote data control is similar to data control except that it creates and manipulates RDO objects. Remote Data Object(RDO): Remote data objects and collections provide a framework for using code to create and manipulate components of a remote ODBC database system. When to use RDO:
35
To access any 32 bit level ODBC data source. To Virtually access remote databases such as SQL Server and Oracle8. ActiveX Data Object Data Control(ADODC): The ADODC uses Microsoft ActiveX Data Objects to quickly create connection between data bound controls and data providers(Any controls that feature a DataSource property).Data providers can be any source written to the OLE DB specification. ActiveX Data Object (ADO): ADO is not a database connector like DAO or ODBC, rather it is an extensible set of data access objects that is a programming model. These objects are based on OLE DB, which operates at the basic API(Application Programming Interface) level. ADO wraps this functionality into an easy to use flexible package that will be the basis of all of Microsofts future data access developments.
List of Projects
1. Library Management System 2. Bank Management System 3. Inventory System 4. Software for a Game 5. Text Editor 6. Railway Reservation System 7. Student Information System 8. Payroll Processing System
36
DCL COMMANDS
Data Control Language (DCL) allows the user to perform the operation like granting and revoking the privileges using grant and revoke command. CREATE a new user: -To create a new user. Syntax: create user <user name> identified by <password>; Example: create user maran identified by dbms; Grant command:Description:By using the grant command, you can grant any system the privileges or role to another role. The WITH ADMIN OPTION clause permits the grantee to after the privilege or role on other users or roles. The grantor can also revoke a role from users as well. We can also specify ALL to grant all the privileges. Syntax:Grant privileges ON <object-name> TO <user-name>; Example:SQL> grant select, insert, delete on college to maran; Revoke command:Description:Privileges granted can be taken away by the REVOKE command. This command is almost similar to that of the grant command in its format. Syntax:Revoke privileges ON <object-name> FROM <user-name>; Example:SQL> revoke insert, delete on college from maran;
TCL COMMANDS
Transaction Control Language (TCL) manages the changes made by the DML commands. Commands are commit, rollback, and savepoint. Commit command:-
37
Description:The commit statement explicitly makes permanent any changes that to the database during the current transaction. A commit also makes those changes visible to other users. So the commit statement ends the current transaction. Syntax:Commit; Example:SQL> commit; Savepoint command:Description:Savepoint names and marks the current point in the processing of a transaction. Using savepoint with rollback, we can undo a part of a transaction instead of the whole transaction. The maximum number of savepoint per transaction is 5. Syntax:SAVEPOINT savepoint-name; Example:SQL> savepoint s1; Rollback command:Description:The rollback statement does exactly opposite to the commit. It ends the current transaction and discards any changes made during that transaction after the commit or savepoint. Syntax:Rollback [to [SAVEPOINT] savepoint-name]; Example:SQL> rollback to s1; SAVEPOINT is optional and is used to rollback a partial transaction at the specified savepoint.
38
EX 9. DCL COMMANDS
1. Create a new user. 2. Grant permission for various operations (create session, resource) to be performed by the user. 3. Create a table with in the new user. 4. Grant all permissions on a table of one user to another user. 5. Revoke permissions from the new user.
39