0% found this document useful (0 votes)
8 views38 pages

DBMS Final

The document is a lab manual for a Database Management System course, detailing various experiments related to SQL and RDBMS installation and usage. It includes instructions for installing Oracle, MySQL, and PostgreSQL, creating users and databases, and executing SQL commands for data manipulation. Additionally, it covers topics such as SQL functions, joins, subqueries, views, cursors, and triggers.

Uploaded by

Rupesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
8 views38 pages

DBMS Final

The document is a lab manual for a Database Management System course, detailing various experiments related to SQL and RDBMS installation and usage. It includes instructions for installing Oracle, MySQL, and PostgreSQL, creating users and databases, and executing SQL commands for data manipulation. Additionally, it covers topics such as SQL functions, joins, subqueries, views, cursors, and triggers.

Uploaded by

Rupesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 38
SEMESTER - IV LAB MANUAL Database Management System Submitted by — Guided by — Prof. Vishnu Prasad Verma Branch — COMPUTER SCIENCE Sign- ae Roll No. — INDEX S.NO. NAME OF EXPERIMENT EXPERIMENT DATE PAGE NO. REMARK How to install Oracle/ MySQL/ PostgreSQL in Windows/ Linux platforms. Creating users and database objects, inserting rows in the database tables. Introduction to SQL, DDL, DDL, DCL queries and constraints. Populating and manipulating database tables using DML statements. Selecting data from tables : SELECT statement, where clause, having clause, group by, order by, selecting NULL values, use of IN and DISTINCT keywords. SQL functions : Study the use of SQL string, date, arithmetic and aggregate functions with examples. JOINS : study the use of joining tables using natural, inner, outer joins. Subqueries and set operations : Study the use of nested queries and how to apply them in database. Views : Study the use of inline and external views. Cursor : Study the use of cursor and exceptions. Functions and procedures : Study the use of functions and procedures in PL/ SQL programs. 10. Trigger : Study the use of triggers to enforce constraints. EXPERIMEN (0. :- O1 Name of Experiment :- Installation of Oracle / MySQL / PostgreSQL on Windows / Linux. Creating users and database objects, inserting rows into the database tables. Introductio About RDBMS Installation - In this experiment, we install a relational database management system (RDBMS) such as MySQL, PostgreSQL, or Oracle XE on either Windows or Linux. A database system allows us to store, manage and retrieve data efficiently using SQL commands. Installation Steps :- A) Installing MySQL On Windows ~ Download MySQL Installer from https://dev.mysql.com - Run the installer and select ‘Developer Default. - Set the root password and finish setup. On Linux: sudo apt update sudo apt install mysql-server sudo systemet! start mysql B) Installing PostgreSQL ‘On Windows: - Download from https://www.postgresql.org, EXPERIMEN (0. :- O1 = Install and set postgres password. ~ Use pgAdmind for GUI. On mux: sudo apt update sudo apt install postgresql postgresql-contriby ) Installing Oracle XE - Download from https://www.oracle.com/database/technologies/xe-downloads.html - Follow installation wizard and use SQL*Plus or SQL Developer. Creating User and Database :- In MySQL: CREATE USER ‘student’@ ‘localhost’ IDENTIFIED BY ‘pass123'; CREATE DATABASE labDB; GRANT ALL PRIVILEGES ON labDB.* TO ‘student’ @ localhost’; In PostgreSQL: CREATE USER student WITH PASSWORD 'pass123'; CREATE DATABASE labdb OWNER student; GRANT ALL PRIVILEGES ON DATABASE labdb TO student; In Oracle: CREATE USER student IDENTIFIED BY pass123; GRANT CONNECT, RESOURCE TO student; EXPERIMENT NO. : Creating Table and Inserting Rows :- CREATE TABLE employees ( emp_id INT PRIMARY KEY, name VARCHAR(S0), department VARCHAR(30) INSERT INTO employees VALUES (1, ‘Alice’, 'HR'); INSERT INTO employees VALUES (2, 'Bob’, IT’); INSERT INTO employees VALUES (3, ‘Charlie’, To check records: SELECT * FROM employees; Conclusion :- The RDBMS was successfully installed. A user and a database were created, and a table was populated using SQL queries. Cx pestiment “2 (®D him g— Trlroduction dy ¢@L y ppl DEL querriey anol comttrayndis. Poputating arrol maa putlah ng clatabage fobler wsing DML dete mend 5. ¥ Tndvoduckion ofe SQL +- SQUCStuduned Qu Langquayed AG! prog varnuning designed for manag ry, data fr nelahenal datakate” , Stl hes a Vvartety ot funchions shat alloca f}io uses + 4o read, maripatate “ard change dete Th sar is emmonly vcd by enyinerry tn “gottoare dabeldpment , Fs leo pals with lela anolyats 1 Also q nim — procectural language hid wer Sutro duced “by tM ‘in 1970's , algo called as sequerl or LL te (Oommen language Tukentace ), B) tab leaquege of SQLi- @ deta defination lyn OSL) g— TBs lanquage ee ane ited fo define , modify Be dre om cbjttbor database trom SG, senweh. ~ orn mad 5,— OLREATE — Creang anus datrhase om new table fn se seve Sys” CREATE TABLE Tal enane | tolumn 4 dotecty pe, cota 2 dokaty pe, Se Qas — cece Tate Uses os “eae Plane Verchar, a tat Nowe varshor, gmail 3d Vanshah, Be @ ALTER%- st is used ter atding and wrod tying alin- fates of te -bble- Syron- To add ot new column “WK He tebe ALTER TABLE 4uZlenane ABD coluun o c belamin deta qe | Sowaple ALTER TABLE og : vanctan (20d) 5 sty “DETAILS ADD mpDRESS ) ‘ © Drop- brogpiny a! dable dyom a dedabase pormanadiy. Sywac— Drop duble A Tahhe Nawe> 5 Emample - Drop table gductenrl 5 : @ Trmeate= deleting mows Prom the ables but rok studure duo talole + eyntarr— Truncate Avole 4 Veble Naure S 5 ables studot 5 ; Enanple— “wuncode deta mauiyulattion lawguroyt %o~ This lovgueye commands, wre 2 ’ “et wed an ave or waa pare data Yn database -lobbe. , ENSERT — Tasertiny a mew vee fubo atotle- ; Syntom. — Insert ito able nae (Clue 2, Column ben Nolues fvdluer, Nolet “05 | Ereumple- Trseur who chadeud (ED, S Wane) Volos e106, Rid) 5 ‘ ) g@ UPDATE ~ das IOS Tn a teble at a Hwee 7 Qrtebing call ces Te fn afable ,by Using ‘Twhese" condition. Sbyntan— Uplate FT 4 Column Mane Lye | L [where conditing ; c= & Hehae} Greample — Update Gmy Seb Gms B00 j Peeve - tele from fre }able of a Hee . gyutan < Delete from LTolake. Homey Tuhene 4 condition J) | Delete Prom omy | Srcamy le ~ OA dake Grbrol Langueye CBEL) GH DOL com ave used ‘to yrok and dake back , authority deren amy lator base Uber - eGvad— Fe Ys wed Jo gyve Wer access prvileges fo a datubase, Sydex— QgaNy PRIVILEGE ON objeck To uses J 4 Example — GRANT SELECT 1 VdDATE ON MY_ TABLE To sone _ USER, ANOTHER USER 5 eRevoket—- Tt Ts used to felee toack pewmissiens fron 4he Wwe, syuta- Revoke pavileye on obyel Feo User 4 Cxumple - KEVORE SELECT /OPDATE on MY_TRDLE ¥ ROM user: UsER 2; A Transaction (Centro{ language (TCL) 2— TCL js ased te mange trunsach jn a dutedyye ditobase ensuring Hoot mulkiple operates ont erie cuted Saitedy . ecommits— Commit Garmard fs used to save ol] fhe trarcachm ¢ to the database. sytenc- Coren! COMMITS Grauple- DELETE Riser FROM (OSTOM ERS WHERE RGE=28 COMMIT 5 ool baclkk- Tt's use to uudo tronsacdau Het have vot abeady bran saved $0 He datrbase, Syntare — ROLL BACK 5 Gmample - DELETE FROM COTOMERS WHERE ABE = 25) Rol eack +o ATER DELETES oS AVE MINT E- Thy used 4o well due fonesachen Leck do a certelw polwt Ul Hout vollivy toack tHe eubise Armatacd . Sq Wee - CAVE POINT Save pod mame), Grumple- DELETE FROM (COSTOMERS WHERE AGE er SAVE POINT &e’ atten jolete © yoda Query languoye CBRL) &- 5 feng g DOL fe used to fetch re data trom bh the oatab ase . o SELECT —Tt Ts wed to retrieve dea Hen one oc mere -fables In daka toast. Syvtere- select Columns, Column2.-~ PROM teble- narnre | WHERE Condit 4 Grample- select employee. id, nanre FAOM ouapleyees ust here Salaruy 75000 1 a iy er a a a a a Ce © Expodmet - 2 date from stables } SELECT Shtement , where Aime- Select : 7 rstlecha clage having clause + Group by NVUW velees ) use of TN aad DISTINCT Keyedords « Gounce cede s— -- Create the Madmbs table CREATE TABLE students C fd INT PRIMARY KEY, Name VARCHAR (50) 9 aye INT, department VARCHAR (10), marks ONT DE ~~ INSERT Sample date marks : went eens INSERT FNTO 80) Oe rT SELECT deport mort , COUNT UE) As shuderk, count For Student's GROUP Vy deportmants, Toe ESTE ECEECECEAEEAEL | ® td) --— HAVING cLaAUSE GELECT deportrmrent , WUNT (%) ks bhudent, wart FROM studods QKOUP by deparcten® HAVING COLNTLY) DL le)-- ELECTING NULL VALUES ELECT X PROM tude? WHERE marks TS NULLY ) -- verng ey SELECT * ROM C ese’ éce'); Ghudewts WHERE department TU @) —- DrstrNcT KEYWORD SELECT psst=NcT deprdnent f60M students 5 Audputs - e SELECT Chebement - _ rd | _ Nae Age Departmink Maks i 1 Aditi Bo es 88 Q. fad 19 Ete 6 3. Paiya al cee gt 4 Arian ao ME 6s E] gneha o. eLe 78 © WHERE t— I'd Ware Age | Beparchment= | Harles i Adthi Do Ose 88 a] paiya a es€ gl GROUP by :- fHaving Depatcinent | Shade Count coe 2 Eve Lh © CELECTING NULL VALUE §— fe Naw Age_|_ depart ment Maras o ING Ta | wet Age | Berartmrect | Masec Le} Adi 2 Ose Rf ks 8 ece >| ar CSE S| Sacha De ete * DISTINCT 3— y Crperiment — 4 . @w Aim s@r funchions 1 Skudy the We of ar shiny, date, axithmebic aud aucithematic aud sgyrayste functions with Caxample . founce Code g- —n Create a table CREATE ‘TABLE gctadeudis c \d INT, name vaRCHAR (SO), birthdate BATE , maxes ENT) 5 ~- Ensek gample date INSERT INT Studenbs Cid name, brrthdalt mas) VALUES CL, tAdit), (x004-05- eb", 88), C2, Cpoj 77 '2008- OB-IE?, HEI, Cnppr— tro? 1 SL) L C3, ‘Priva’, (2001-09-18) FB), (5) Usneha’ « ty, Acun's' aoou~ esol! 65); @ —- STRING FUNCTIONS - = GELECT Mme CsPPER Came) AS upperrune feo Stuctents; SELECT name , SBBSTRING (Name, £13) As thor nawue ROM gtudeutts + o) —-Date, Avthmedre 4 SELECT mame , blsthdacde, PSK PATE aLHA C CURDRTE US Wrtkdate) / 365) Ay ane PRIM Students 5 SELECT name, bicthdecte , DATE ADD (bicthdate , INTERVAL 20 DAS) As birth fu _sodays PROM studebis + WI — Anithmedic:— SELECT name Yrascks , wekket s As Bonus _vrachs ROM Stucerdss , “SELECT reame , marks, Pras /120-0}%] 60 As PEREENTAGE FROM STUDENT ; a @ dW -- Avaregote in SELECT COUNTL®) As totale Studerts 1ROM skudent's 5 SELECT AVG tmanks) As avg-marks #KOM Studeud s » Otctpute — la) sin g furchon $- Nawe up Pe Nowe Adi ADTTT Raj RAD Paya PRIYA frjun ARJUN Sneha SNEHA name Ghost newme Aditi Adi Ras Raj tiva Pei Agjan Ax ee sneha Sne Wb) dota Avithmetic s~ Nant | birthdate age Ady asel—os-6) 2) Raj Rooy—oOB-1S al rua | goon = t2-to a2 Axjun | 209 U- 06-25 20 gneha_| Bq04 — 09-18 23 nome| Gir thdede Tih plea AaMK 8084-056} 2004-05-31 Ras B00 3-08-[E fase 3-o9-14 Pr ya peer — [2-l0 aens-0l 29 Arjun | aoet— 06-25 | amunet-25] SreMa | s00|—-6Fal8 — facot-to-ts |/ a (0) Avith metic Funchonss— nace | meacke | honees- ert s Aditi | 88 a Aas We Wi fi ye 91 16 fadun ts +O gncha 48 83 hame. mexks | percentage Adi 88 88 600d taj 46 Hh, OGD Priva 3 91, 0B Adjun | 6s 65. 08BD Sneha 48 26.0000 GD flggwe gete- tunchon @— [Hebel chadens | g ————___] avi ares 49.6000 -_— s (cy) Lapeninen > SAI B= TOTNES RE SMecatey tte de ed Jotrbuy feblee tatveag methine 0 \ WMT Louter Jeng scadese= 2 = students toble CREATE CYABLE Sdudedts ¢ Sdudtadid a Nts ree VARCHAR CEOD, Cetnge od Ny »> —— Comsed fable CREATE TABLE courses C tome. id FNT, Caorse Lame bAREHA (SO) dD INSERT date inte Shades INSERT TNO Studeret's VAL thy tain roll) (x5 tka to2), (3, Coneha’, (0383) Cu, * Paiva DOLLIZ ee —— TNSERT deta nto Comnces INSERT FNTO couRsES VALUES ves Clon, ‘Mathys ? ), Lio 2, 'Physies') > Clo, ' Biotegy’) + . @) —- Natural Doin ELECT FFROM Haderts VPATURML SoTN Colrset) UW) —- INNER SOIN 1 C2COUREE Mare — FON ctedeetts og GELECT sane | | a ot ee ee ee ee, ee ee ee ee ee ee ee ee So IBNER gorN Counsed © oN 5S. Bounge-id ©) _- @vll TaN SELECT S.nawmt oN <.counse id= Course ce ae PMTON SELECT Snare , CPOUAIE-Nemat £ Cousees c on 5s. Courses th = KOukpute— @ votwrak Tein oo 6. Course—id 5 Ccounge, name FROM sttuderchs. $ LEAT JaIh Ceounse id BEESON fom stucleudts ¢ Right or course id} Cure nane | [exsetd [Shade ki [| nace ts) Vp adi Kats le 27 Raj physics Q tnnen Tin t- (ep) FULLLOVTER) Sint Kane | Cpurce_nane] Aditi ue had physics Sneha NULL priya poll NOLL Biol gy EXPERIMENT NO. :- 06 Name of Experiment :- Subqueries and set operations : Study the use of nested queries and how to apply them in database. Subquerie: A subquery, also known as a nested query or inner query, is a query nested within another query. It allows you to break down complex problems into smaller, more manageable parts. Subqueries can be used in various clauses like SELECT, FROM, WHERE, etc. Here's an example of a subquery in the WHERE clause: SELECT name FROM employees WHERE department_id = (SELECT department_id FROM departments WHERE name = ‘Sales'); In this example, the inner query (SELECT department_id FROM departments WHERE name = ‘Sales’) retrieves the department ID for the department named ‘Sales’. This result is then used in the outer query to find the names of employees who belong to the ‘Sales’ department. t Operation: Set operations in SQL (Structured Query Language) are used to combine the results of two or more SELECT queries. There are three main set operations: UNION, INTERSECT, and EXCEPT (or MINUS, depending on the SQL dialect). 1, UNION: It combines the results of two or more SELECT statements into a single result set. It removes duplicate rows by default, SELECT column! FROM table! UNION SELECT column! FROM table; 2. INTERSECT: It returns only the rows that appear in both result sets of two SELECT statements. SELECT column! FROM table! INTERSECT SELECT column! FROM table2; 3, EXCEPT (or MINUS): It returns only the rows that appear in the first result set but not in the second. SELECT column! FROM table! EXCEPT SELECT column! FROM table2; Example: Let’s say we have two tables, employees and managers. We want to find the names of all employees who are not managers. We can use the EXCEPT operator for this SELECT name FROM employees EXCEPT SELECT name FROM managers; This will give us the names of all employees who are not managers by subtracting the set of manager names from the set of all employee names. Example :- ~- Create employees table CREATE TABLE employees ( employee_id INT PRIMARY KEY, name VARCHAR(S0), department_id INT, salary DECIMAL(10, 2) \sert sample data into employees table INSERT INTO employees (employee id, name, department_id, salary) VALUES, (1, John Doe’, 1, 5000.00), (2, Jane Smith’, 2, 6000.00), (3, ‘Alice Johnson’, 1, 5000.00), (4, Bob Williams’, 2, 62000.00), (5, ‘Charlie Brown’, 3, 5200.00); ~ Create managers table CREATE TABLE managers ( manager_id INT PRIMARY KEY, name VARCHAR(S50), department salary DECIMAL(10, 2) ~- Insert sample data into managers table INSERT INTO managers (manager_id, name, department_id, salary) VALUES (01, "Michael Scott, 1, 7500.00), (102, ‘Leslie Knope’, 2, 78000.00), (103, 'Ron Swanson’, 3, 30000.00); ~-1. Subqueries: ~-a. Basic Subquery: Find the names of employees whose salaries are greater than the average salary. SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees); --b. Correlated Subquery: Find the names of employees who earn more than the average salary of their department. SELECT name FROM employees WHERE salary > ( SELECT AVG(salary) FROM employees WHERE department_id = e.department_id 2, Set Operations: ~-a. UNION: Combine the names of employees and managers into a single list. SELECT name FROM employees UNION SELECT name FROM managers; . INTERSECT: Find the names of employees who are also managers. SELECT name FROM employees INTERSECT SELECT name FROM managers; ~-c. EXCEPT: Find the names of employees who are not managers, SELECT name FROM employees EXCEPT SELECT name FROM managers; 1. Subqueri a. Basic Subquery: © Show at | Number orons: Al w | Fierro Sorby key: | None a cotees WES }.C0p) @ Delete Jane Sram WP Eat 32 C00 @ Deote Bob Witiams b. Correlated Subquery: esta cetons PEO F Cony @ Delete Alea Jomeor PES FE Copy @ Delete Bob Wa PEG HCO Set Operations: a. UNION: Sow at | Number trons; 25 | Fier rows: b. INTERSECT: name. John Doe: Jane Smith c. EXCEPT: 3-07 Name of Experiment :- Views : Study the use of inline and external views. VIEWS :- A view is often referred to as a virtual table. Views are created by using the CREATE VIEW statement. After the view has been created, you can use the following SQL commands to refer to that view: « SELECT * INSERT « INPUT * UPDATE * DELETE Views can be created using CREATE VIEW. ‘The syntax for the CREATE VIEW statement is Syntax: CREATE VIEW AS SELECT columnname, columnname FROM Where columnname = expression list; Group By grouping criteria Having predicate Note: The Order By clause cannot be used while creating a view. Selecting a data set from the view: Once a view has been created, it can be queried exactly like a base table. Syntax: Select columnname, columnname From viewname; Updating views : Views can also be used for data manipulation(i.e. the user can perform the Insert, Update and Delete operations). Views on which data manipulation can be done are called Updatable Views. When you give an updatable view name in the Update, Insert or Delete SQL statement, modifications to data will be passed to the underlying table. Views defined from single table © If the user want to Insert records with the help of a view, then the Primary Key columns and all the NOT NULL columns must be included in the view. © The user can Update, Delete records with the help of a view even if the Primary Key column and NOT NULL columns are excluded from the view definition. Views defined from multiple tables(Which have no Referencing clause) In this case even though the Primary Key column/s as well as NOT NULL. columns are included in the View definition the view’s behavior will be as follows: «The Insert, Update or Delete operation is not allowed. If attempted the Oracle displays an error message. Views defined from multiple tables(Which have been created with a Referencing clause) In this case even though the Primary Key and NOT NULL columns are included in the View definition the view’s behavior will be as follows: An Insert operation is not allowed. The Delete or Modify do not affect the Master Table. The view can be used to Modify the columns of the detail table included in the view. If a Delete operation is executed on the view, the corresponding records from the detail table will be deleted. Destroying a view: The drop view command is used to remove a view from the database. Syntax: Drop View viewname; Exampl CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Name VARCHAR(50), Department VARCHAR(S50), Salary DECIMAL(10, 2) ys INSERT INTO Employees (EmployeeID, Name, Department, Salary) VALUES (1, 'piyush’, IT’, 50000.00), (2, bonika’, 'HR', 45000.00), (3, 'prakash’, ‘Finance’, 60000.00); CREATE TABLE Departments ( DepartmentID INT PRIMARY KEY, DepartmentName VARCHAR(50) ); INSERT INTO Departments (DepartmentID, DepartmentName) VALUES (1, IT’), (2, "HR'), (3, Finance’); SELECT Name, Department FROM ( SELECT Name, Department FROM Employees WHERE Salary > 45000 ) AS HighEarners; CREATE VIEW HighSalaryEmployees AS SELECT Name, Department FROM Employees WHERE Salary > 45000; SELECT * FROM HighSalaryEmployees; Output show an Name Department piyusn + prakasn Finance Te ion Fows g Te Colton Sue veteat depuimes yD Bse {Shute Seach set Eon) Q Dap 3 nO ated ewe 16.0 8 C1 empless Horse }.Smave 4 Seach Heh npy Q Dap 3 HmOB onbl geal c 16. 8 1 bighsiyenlopes fy Bese Y{Shocwe Seach Hiset JE QO @ Ves Extra options ime ~~ Name Department Edit BéCopy © Delete piyush = 1T oP Eat %Copy @ Delete prakash Finance EXPERIME O08 Name of Experiment - Cursor : Study the use of cursor and exceptions. What are Cursors? A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set. ‘There are two types of cursors in SQL: Implicit cursors: These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed. Explicit cursors: They must be created when you are executing a SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row the current TOW position moves to next row. and explicit cursors have the same functionality, but they differ in the way General Syntax for using FOR LOOP: FOR record_name IN cusror_name LOOP process the row... END LOOP: Let’s use the above example to learn how to use for loops in cursors. 1> DECLARE 2>CURSORemp_cur IS 3>SELECTfirst_name, last_name, salary FROM emp_tbl; 4>emp_recemp_cur%rowtype; 5> BEGIN 6>FORemp_tec in sales_cur 7> LOOP 8>dbms_Output.put_line(emp_cur.first_name ||'" Jjemp_cur.last_name 9> ||" jemp_cur.salary); 10> END LOOP; 11>END; 12>/ (a) Create a cursor, which displays all employee numbers and names from the EMP table. CREATE TABLE employees ( ‘employee_id INTEGER PRIMARY KE! first_name VARCHAR(25), last_name VARCHAR@5), | VARCHAR(25), mber VARCHAR(IS), % INSERT INTO employees (employee id, first_name, last_name, email, phone_number, salary) VALU! (1, John’, ‘Doe’, 'john.doe @example.com’, '555-1234', 50000), (2, ‘Jane’, ‘Smith’, '[email protected]’, '555-5678', 60000), (3, ‘Alice’, Johnson’, ‘alice [email protected]’, '555-9012', 70000); DECLARE @id INT DECLARE @first_name VARCHAR(25) DECLARE @last_name VARCHAR(25) DECLARE cursor_name CURSOR FOR SELECT employee_id, first_name +'' + last_name AS name FROM employees OPEN cursor_name FETCH NEXT FROM cursor_name INTO @id, @name WHILE @ @FETCH_STATUS = 0 BEGIN PRINT "ID: ' + CAST(@id AS VARCHAR) +', Name: '+ @name FETCH NEXT FROM cursor_name INTO @id, @name END CLOSE cursor_name DEALLOCATE cursor_name Outpu (b) Create a cursor, which update the salaries of all employees as per the given data. SET serveroutput ON; DECLARE CURSOR cur_emp IS SELECT * FROM employees WHERE department_id = 40 OR department_id = 70; rec_emp cur_empY%rowtype; BEGIN OPEN cur_emp; LOOP FETCH cur_emp INTO rec_emp; EXIT WHEN cur_emp%NOTFOUND; DBMS_OUTPUT.PUT_LINE(‘Employee ID: ' | rec_emp.employee_id |)’, Name: "| rec_emp.first_name || ''|| rec_emp.last_name); END LOOP; CLOSE cur_emp; END Output : EXPERIMENT NO - 9 Name of Experiment - Functions and procedures : Study the use of functions and procedures in PL/SQL programs Stored Procedures What is a Stored Procedure? A stored procedure or in simple a proe is a named PL/SQL block which performs one or more specific task. How to execute a Stored Procedure? There are two ways to execute a procedure. 1) From the SQL prompt. EXECUTE [or EXEC] procedure_name; 2) Within another procedure — simply use the procedure name. procedure_name: NOTE: In the examples given above, we are using backward slash ‘/” at the end of the program. This indicates the oracle engine that the PL/SQL program has ended and it can begin processing the statements. (a) Find the greatest among three numbers. Declare a number; b number; c number; Begin dbms_output.put_line(Enter a: as&a; dbms_output.put_line(‘Enter b: b:=&b; dbms_output.put_line(Enter if (a>b) and (a>c) then dbms_output.put_line(A is GREATEST'|A): elsif (b>a) and (b>c) then dbms_output.put_line(B is GREATEST’): end if; End; (b) To check given number is Armstrong number or not. DECLARE n number(3); s number(3):=0; tnumber(3); BEGIN &n; while t>0 loop +power((t mod 10),3); t:=trunc(/10); end loop; if(s=n) then dbms_output.put_line(‘The Given Number ' || n || ' is an Armstrong Number’); else dbms_output.put_line(‘The Given Number ' || n ||‘ is Not an Armstrong Number’); end if; END: OUTPUT: NOTE: We used SQL Developer and Oracle XE to Execute this Program. The Given Number 153 is an Armstrong Number. EXPERIME! 10 Name of Experiment, - Trigger : Study the use of triggers to enforce constraints, Triggers Triggers are simply stored procedures that are ran automatically by the database whenever some event (usually a table update) happens. Triggers are basically PL/SQL procedures that are associated with tables, and are called whenever a certain modification (event) occurs. The modification statements may include INSERT, UPDATE, and DELETE. The general structure of triggers is: CREATE [OR REPLACE] TRIGGER [schema] trigger_name {BEFORE AFTER} { DELETE, INSERT OR UPDATE [OF COLUMN, ..] } ON [schema.] tablename [REFRENCING {OLD AS old, NEW AS new}] [FOR EACH ROW [WHEN (condition)]] DECLARE variable declarations; constantdecalarations; BEGIN PL/SQL subprogram body; EXCEPTION exception PL/SQL block; END; where: Example: Sample Table to be Triggered Thi document ovale eof care on § studocu Before we begin playing with triggers, let’s create a simple table with which we can experiment: CREATE TABLE PERSON ( ID INT, NAME VARCHAR(G30), DOB DATE, PRIMARY KEY(ID) The above creates a PERSON table with an ID, a NAME and a DOB columns (fields). Whatever triggers we define in these notes will relate to this table. Viewing Triggers You can see all your user defined triggers by doing a select statement on USER_TRIGGERS. For example: SELECT TRIGGER_NAME FROM USER_TRIGGERS: Which produces the names of all triggers. You can also select more columns to get more detailed trigger information. Dropping Triggers You can DROP triggers just like anything. The general format would be something like: DROP TRIGGER trigger_name; (a) Create a trigger before/after update on employee table for each row/statement SET serveroutput ON DECLARE CURSOR cur_emp 1S\ SELECT * FROM employees WHERE department_id = 40 OR department_id = 70; rec_empcur_emp%rowtype; BEGIN OPEN cur_emp; LOOP FETCH cur_emp INTO rec_emp: IF rec_emp.department_id = 40 THEN UPDATE employees SET salary = salary + (salary * 0.1) WHERE employee_id rec_emp.employee_id: elsifrec_emp.department_id = 70 THEN UPDATE employees SET salary = salary + (salary * 0.15) WHERE employee_id = rec_emp.employee_id; END IF; EXIT WHEN cur_emp%notfound; END LOOP: CLOSE cur_emp; END; / Output: (b) Create a trigger before/after delete on employee table for each row/statement creates a DML trigger that uses conditional predicates to determine which of its four possible triggering statements fired it. Example - Trigger that Uses Conditional Predicates to Detect Triggering Statement CREATE OR REPLACE TRIGGER t BEFORE INSERT OR UPDATE OF salary OR UPDATE OF department_id OR DELETE ON employees BEGIN CASE WHEN INSERTING THEN DBMS_OUTPUT.PUT_LINE( Inserting’); WHEN UPDATING(salary') THEN DBMS_OUTPUT.PUT_LINE(Updating salary’); WHEN UPDATING(‘department_id’) THEN DBMS_OUTPUT.PUT_LINE(‘Updating department ID’); WHEN DELETING THEN DBMS_OUTPUT.PUT_LINE(‘Deleting’); END CASE; END; Output: (c)Create a trigger before/after insert on employee table for each row/statement. CREATE TRIGGER {BEFORE | AFTER} ON [ REFERENCING | ::= INSERT | DELETE | UPDATE [ OF ] ::= [ {.} ... ] ... OLD [ ROW ] [ AS ] old values | NEW [ROW ] [AS ] new values | OLD TABLE [ AS ] | NEWTABLE [AS ] ::= ::= ::= [FOR EACH {ROW | STATEMENT} ] [ WHEN (search condition) ] ::= SQL statement | BEGIN ATOMIC {SQL statement; }... END creates a log table and a trigger that inserts a row in the log table after any UPDATE statement affects the SALARY column of the EMPLOYEES table, and then updates EMPLOYEES.SALARY and shows the log table. CREATE TABLE employees ( employee_id INTEGER PRIMARY KEY, first_name VARCHAR(25), last_name VARCHAR(25) ys CREATE TABLE salaries ( salary_id INTEGER PRIMARY KEY, employee_id INTEGER, salary_amount INTEGER, CONSTRAINT fk_employee FOREIGN KEY (employee_id) REFERENCES employees(employee_id) ds CREATE OR REPLACE TRIGGER check_employee_exists BEFORE INSERT ON salaries FOR EACH ROW DECLARE v_count INTEGER: BEGIN SELECT COUNT(*) INTO v_count FROM employees WHERE employee_id = :NEW.employee_id: IF v_count = 0 THEN RAISE_APPLICATION_ERROR(-20001, 'Employee does not exist’); END IF; END: / BEGIN, INSERT INTO salaries (salary_id, employee_id, salary_amount) VALUES (1, 1001, 50000); EXCEPTION WHEN OTHERS THEN, DBMS_OUTPUT.PUT_LINE( Error: ' || SQLERRM); Output :- Coal aeekig

You might also like