Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
23 views
62 pages
DBMS (Lovish)
Dbms
Uploaded by
roughwork012
AI-enhanced title
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
Download
Save
Save DBMS (lovish) For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
23 views
62 pages
DBMS (Lovish)
Dbms
Uploaded by
roughwork012
AI-enhanced title
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
Carousel Previous
Carousel Next
Download
Save
Save DBMS (lovish) For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save DBMS (lovish) For Later
You are on page 1
/ 62
Search
Fullscreen
University Institute of Engineering and Technology MAHARSHI DAYANAND UNIVERSITY DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING DATABASE MANAGEMENT SYSTEM SUBMITTED BY:- LOVISH KUMAR ROLL NO:- 2314137 CLASS:- CSE-‘B’ (3RD SEMESTER) SUBMITTED TO:- DR. RAJKUMAR YADAVS.No. Name of Program 1. Creation of a database and writing SQL queries to retrieve information from the database. 2. Processing various queries. Creation of Views, Synonyms, Sequence, Indexes, Save point 3.Creating an Employee database to set various constraints 4. Creating relationship between the databases 5. Study of PL/SQL block 6. Write a PL/SQL block to satisfy some conditions by accepting input from the user. 7. Write a PL/SQL block that handles all types of exceptions. 8. Creation of Procedures 9. Creation of database triggers & functions. Page No. Remarks 1-2 14-17 18-21 21-31 32-39 39-40 41-42Program-1 Aim: To create a database and writing SQL queries to retrieve information from the database. Description: SOL is a database query language used for storing and managing data in Relational DBMS. SQL was the first commercial language introduced for E.F Codad's Relational model of database. SQL is used to perform all types of data operations in RDBMS. Creation of database: “Create Database” statement is used to create a database Syntax: Create Database {Database Name}; “Show Databases” statement is used to show all the databases in SOL Server. Syntax: Show Databases; “Use” statement is used to select a database Syntax: Use {Database Name}; Creation of Table: Constraints can be specified when the table is created with the “Create Table” statement, or afier the table is created with the “Alter Table” statement. The following constraints are commonly used in SQL: Not Null: Ensures that a column cannot have a null value. Unique: Ensures that all values ina column are different.Primary Key: Uniquely identifies each row ina table. Foreign Key: Uniquely identifies a row/record in another table. Check: Ensures that all values in a column satisfies a specific condition. Default: Sets a default value for a column when no value is specified. Index: Used to create and retrieve data from the database very quickly. Syntax: Create Table {Table Name }( Column_l datatype constraint, Column_2 datatype constraint, Column_3 datatype constraint, wh Example: create table student4 ( S_id int, S_name varchar(255), s_marks int, s_city varchar(255) ); StudentID Name Age Grade 1 Alice 4 A 2 Bob 16 8 3 Charlie 13 AProgram 2 Aim: To Insert, View, Delete, Alter, Modify and Update records based on conditions. Description: Inserting Values into table: “Insert into” Statement is used to insert values in a table. The values which are inserted in table are specified with the help of “Values” Statement. Syntax: Insert into{table_name}(column_1, column_2, column_3...) Values(value_1, Value_2, Value_3....); Example: insert into student4 values(1,'ronit',56,'faridabad'); insert into student4 values(1,'sahil',93,'hue'); insert into student4 values(3,'mahir',78,'ambala’); insert into student4 values(5, 'manik',56,'sonipat'); insert into student4 values(6,'babu',79, ind’); View records from a table: “Select” and “from” used to specify condit satisfying that condition. “*” is used in case we want to see all the column instead of only specifying all the columns individually. is used to view records from a table. “where” is ons if we want to see only a particular information Syntax: Select {Column_Names} From {Table_Name} where {condition}; Example:Select * from Code: sal GB) Copy code INSERT INTO Students (StudentID, Name, Age, Grade) VALUES (4, ‘David', 16, 'C'); Update Data UPDATE Students SET Grade = 'B' WHERE StudentID = DELETE FROM Students WHERE StudentID = 4; - Select Da SELECT + FROM Students; Expected Output: ‘StudentiD Name Age Grade + Alice 14 A Zz Bob 5 B 3 Charlie + 13 A student4;Deleting a record from table: “Delete From” is for delete a record. It is used with “where” which is used to specify the conditon where we want to delete the record. Syntax: Delete from {table name} where {condition}; Example: DELETE FROM STUDENT_4 WHERE S_ID=2; SELECT * FROM STUDENT_4; Syntax: sql DELETE FROM {table_name} WHERE {condition}; Altering a Table: Unlike other command up until now this command do not affect records but it affects the table itself. “Alter” is used to change the structure of the table. + Adding anew column: Used to add a new column in an existing table. 8 copy «Syntax: Alter Table {table name} Add column {column_name datatype}; Example: alter table student4 add e_dob int; select * from student4; * Deleting an existing column: Used to delete a column in an existing table. Syntax: Alter table {Table name} Drop column {column_name}; Example: alter table student4 drop column e_dob; Updating a record: “Update” and “set” statement are used to update records along with the “where” statement. Syntax:Update {table_name} set {column} = {new value} where {condition}; Example: Update column_name Set column1=value1,column2=value. Where condition; For example- Update student4 Set s_name="rasool’ Where s_id=2; ‘StudentID. Name Age 1 Alice 14 2 Bob 15 3 Charlie 1B GradeProgram 3 Aim: To create Views, Synonyms, Sequence, Indexes, Save point. Description: Vie View is an object which gives the user a logical view of data from an underlying table. We can restrict what users can view by allowing them to see only a few columns from a table When a view is created from more than one table, the user can view data from the view without using join conditions and complex conditions Views also hide the names of the underlying tables View is stored as a “ Dictionary View contains no data of its own Any updation of rows in the table will automatically reflect in the views A query fired on a view will run slower than a query fired on a base table. elect” statement in the Data Creation of a view: Create view {view_name} as select fcolumn_1}, {column_2}... from {table_name} where {condition}; This query help in creatinf a view (i.e., a virtual table based on result set of SQL statement it contains rows & columns just like a table) of a table. Deletion of a view: Drop view {view_name}; This query is used to delete a view of a table. To add or remove fields in a vie" create or replace view {view_name} asre select {column_l}, {column_2} {table_name} where {condition}; This query is used to modify the structure of view i.e., to add or remove from 22:13:42. INSERT INTO cse (Roll Number, Full Name Phone Num. Trow(s) affectes 0.572 sec fields in a view. Inserting a row in a view: insert into {view_name} (column_1, column_2 values(value_I, value_2....); This and also in all other views of that table. query is used to insert a new record in that view and in original table Deleteing a row from a view: Delete from {view_name} where {condition}; This query is used to delete the record that satisfy the given condition & that record is deleted from other views also & also from original table. Updating Views Update {view_name} set {column_name} = {new vaue} where {condition}; There are certain conditions needed to be satisfied to update a view. If any one of these conditions is not met, then we will not be allowed to update the view. * The select statement which is usd to create the view should not include group by clause or order by clause. * The select statement should not have the distinct keyword. * The view should have all not null values. * The view should not be created using nested quesries or complex queries.SrA O row(s) affected The view should be created from single table. If the view is created using multiple tables than we will not be allowed to update the view. Synonyms: Synonyms are used to create alternate names for tables, views, sequences, ete. Creating a synonym: Create synonym {syn_name} for {object_name}; This query creates a synonym for any object ie., any table, view, etc. View the details of a user synonyms: Select {syn_name}, {table_name}, {table_owner} from user_synonyms; This query is used to view the deatils of the synonyms. Droping a synonym: Drop synonym {syn_name}; This query is used to delete a synonym. Sequence: Sequence is used to generate a sequence of numbers. The value generated can have a maximum of 38 digits. The minimum information required to generate numbers using a sequence are: * The starting number {s} * The maximum number {m} * The increment value {n} Creating a sequence: Create sequence {seq_name} increment by {n} Start with {s} maxvalue {m} {cache/ nocache}; This query creates a sequence which increment by value n and starts with s with maximum value of m.Orow(s) affected Catt 4 Currval :Gives the current value in sequence. Nextval: Gives the next value in sequence. Select sqn_name.currval from dual; Select sqn_name.nextval form dual; Modifying a Sequence: Modification of a sequence does not allow us to change the “start with” option. Similarly, the maximum value cannot be set to a number less than the current number. Alter sequence {seq_name} increment by {n} Start with {s] maxvalue {m} {cache/ nocache}; Drop a Sequence: A sequence can dropped: Drop sequence {sqn_name}; Index: Index is used for faster retrieval of rows from a table. It can be used implicitly or explicitly. Creating a Index: Create index {in_name} on {table_name}(column_1, column_2. query is used to create index on one or more columns. Rebuilding an index:Alter index {in_name} Rebuild; When a table goes through changes, it is advisable to rebuild indexes based on the table. Savepoint: Savepoint isa command in SQL that is used with the rollback command. It is a command in Transaction Control Language that is used to mark the transaction in a table.If you made a transaction in a table, you could mark the transaction as a certain name, and later on, if you want to roll back to that point, you can do it easily by using the transaction's name. Creating a savepoint: To create a savepoint we first have to start our transaction with begin/start. Start Transaction; Savepoint {sp_name}: starttransaction Orow(s) affected Cores 11:26:23 savepointcse _Orow(s) affected Cree Rolling back to savepoint: rollbacktocse — Orow(s) affect Cire To roll back to a savepoint we use “Rollback to”. Rollback to {sp_name}; Deleting a savepoint: There is no syntax to delete a savepoint. A savepoint gets automatically deleted when we commit or rollback the trasaction.Create the Employee Table: sal CREATE TABLE Employee ( e_id INT PRIMARY KEY, f_name VARCHAR(5@) NOT NULL, m_name VARCHAR(5@) DEFAULT 'N/A', name VARCHAR(5@) NOT NULL, age INT CHECK (age > 22), d_code INT, salary_pm DECIMAL(1@, 2) NOT NULL, FOREIGN KEY (d_code) REFERENCES Department (d_code) i Create the Department Table: sql CREATE TABLE Department ( d_code INT PRIMARY KEY, project_code VARCHAR(1@) UNIQUE, ‘team_members INT CHECK (team_members O: Copy code Copy codeProgram-4 Aim: Creating an Employee database to set various constraints. Description: Constraints are the rules that we can apply on the type of data in a table. That is, we can specify the limit on the type of data that can be stored ina particular column in a table using constraints. The available constraints in SQL are: NOT NULL: This constraint tells that we cannot store a null value in a column. That is, if a column is specified as NOT NULL then we will not be able to store null in this particular column any more. UNIQUE: This constraint when specified with a column, tells that all the values in the column must be unique. That is, the values in any row of a column must not be repeated. PRIMARY KEY: A primary key is afield which can uniquely identify each row ina table. And this constraint is used to specify a field in a table as primary key. FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in a another table. And this constraint is used to specify a field as Foreign key. CHECK: This constraint helps to validate the values of a column to meet a particular condition. That is, it helps to ensure that the value stored in a column meets a specific condition. DEFAULT: This constraint specifies a default value for the column when no value is specified by the user. Create table employee with various constraints: Create table employee ( e_id integer (9) primary key, fname varchar (20) not null, m_name varchar (20) default “n/a”, —l_name varchar (20) notnull, age integer not nullcheck(age>22), d_code integer (5), foreign key (d_code) references department(d_code), salary_pm integer create tabl Create table department: Create table department( d_code integer (5) primary key, _ project_code varchar(10) unique, team_members integer check (team_members <= 10) )Program —5 Aim: Creating relationship between the databases. Description: In sql, we can create a relationsip by creating a foreign key constraint. More, specifically we have a parent table and a child table. The parent contains the primary key and the child table contains the foreign key that references to the primary key of the parent table. When we use SQL to create a relationship, we can create the relationship at the time we create the table, or we can create it later by altering the table. Create a Relationship When Creating the Table: Here’s an example of creating a relationship within your “Create Table” statement at the time you create the table. Syntax: Create table Parent_Table( P_column_1 datatype primary key, P_column_2 datatype P_column_3 datatype ) Create table Child_Table( C_Column_I datatype primary key, C_Column_2 datatype C_column_3 datatype constraint Parent_Child foreign key (C_Column_3) References Parent_Table (P_Column_1) de Here we created two tables; one called “Parent_Table” and the other called “Child Table”. Add a Relationship to an Existing Table:You can also add a relationship to an existing table, simply by using the “Alter Table” statement. For Example, let say we didn’t create a foreign key in the table in previous example of Parent_child relationship and we want to create a relationship now, after we have created the tables. Syntax: Alter Table Child_Table Add Constraint Parent_Child Foreign Key(C_Column_3) References Parent_Table(P_Column_1); Note: SQLite Doesn't support adding foreign keys with the Alter Table Statement. Example: Create table employee (___e_id integer (9) primary key, fname varchar (20) not null, m_name varchar (20) default “n/a”, name varchar (20) not null, age integer not null check(age>22), d_code integer (5), foreign key (d_code) references department(d_code), salary_pm integer Create table department: Create table department( d_code integer (5) primary key, _ project_code varchar(I0) unique, team_members integer check (team_members <= 10) ): ras 1.46 cated and will be removed in a future release Add a Foreign ket to an existing table in SQLite:By default, SOL Server relationships are created using “on delete no action” and “on update no action”. Therefore, the previous examples were created using this setting. However, different DBMSs may use other default settings. Either we you can explicitl specify this in your code. So we can modify the previous example to look like this: Syntax: Alter Table Child_Table Add Constraint Parent_Child Foreign Key (C_Column_3) References Parent_Table (P_Column_1) On delete no action On update no action; What this actually means record in the “Primary Key”, would be rolled back. This is SOL Server's way of preventing any changes that could break the referential integrity of your system. that, if someone was to try to delete or update a an error would occur and the change Basically, the reason you create a relationship in the first place is to enforce referential integrity. However, you do have some options with how you want SQL Server to deal with these situations. Specifically, you can use any of the following values: + No Action: An error is raised and the delete/update action on the row in the parent table is rolled back. Cascade: Corresponding rows are deleted from/ updated in the referencing table if that row is deleted from/updated in the parent table.Set Null: All the values that make up the foreign key are set to “Null” if the corresponding row in the parent table is deleted or updated. This requires that the foreign key columns are nullable. Set Default: All the values that make up the foreign key are set to their default values if the corresponding row in the parent table is deleted or updated. For this constraint to execute, all foreign key columns must have default definitions. If a column is nullable, and there is no explicit default value set, “Null” becomes the implicit default value of the column.Program-6 Aim: Study of PL/SQL block. Description: PL/SQL: PL/SQL stands for Procedural Language extension of SOL. PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation in the early 90s to enhance the capabilities of SOL. A Simple PL/SQL Block: Each PL/SQL program consists of SOL and PL/SQL statements which froma PL/SQL block. PL/SQL Block consists of three sections: * The Declaration section (optional). * The Execution section (mandatory). * The Exception (or Error) Handling section (optional). Declaration Section: The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This section is optional and is used to declare any placeholders like variables, constants, records and cursors, which are used to manipulate data in the execution section. Placeholders may be any of Variables, Constants and Records, which stores data temporarily. Cursors are also declared in this section. Execution Section:The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends with END. This is a mandatory section and is the section where the program logic is written to perform any task. The programmatic constructs like loops, conditional statement and SQL statements from the part of execution section. Exception Section The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This section is optional. Any errors in the program can be handled in this section, so that the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abruptly with errors. Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks can be nested within other PL/SQL blocks. Comments can be used to document code. A Sample PL/SQL Block Looks like: DECLARE Variable declaration BEGIN Program Execution EXCEPTION Exception handling END; PL/SQL Block Structure: DECLARE v_variable VARCHAR2(5); BEGIN SELECT column_name INTO v_variable FROM table_name;EXCEPTION WHEN exception_name THEN END; Block Types 1. Anonymous [DECLARE] BEGIN --statements [EXCEPTION] END; 2, Procedure PROCEDURE name IS BEGIN --statements [EXCEPTION] END; 3. Function PROCEDURE name FUNCTION name RETURN datatype IS BEGIN --statementsRETURN value; [EXCEPTION] END; Thus the PL/SQL blocks are studied. CarersProgram-7 Aim: write a PL/SQL block to satisfy some conditions by accepting input from the user. Description: PL/SQL Control Structure provides conditional tests, loops, flow control and branches that let to produce well-structured programs. Syntax: DECLARE Variable declaration BEGIN Program Execution EXCEPTION Exception handling END; PL/SQL General Syntax: SQL> declare
;begin
; end; PL/SQL General Syntax for if Condition: SQL> declare
; begin if(condition) then
; end; PL/SQL General Syntax for If and Else Condition: SQL> declare
; begin if (test condition) then
; else
; end if; end; PL/SQL General Syntax for Nested if Condition: SQL> declare
; begin if (test condition) then
; else if (test condition) then
; else
; end if: end PL/SQL General syntax for Looping statement: SQL> declare
; begin loop
; end loop;
; end; PL/ SQL General Syntax For Looping Statement: SQL> declare
; begin while
loop
; end loop;
; end; PL/SQL Coding for addition of two numbers: PROCEDURE: Step 1: Start Step 2: Initialize the necessary variables. Step 3: Develop the set of statements with the essential operational parameters. Step 4: Specify the Individual operation to be carried out. Step 5: Execute the statements. Step 6: Stop. PROGRAM: SQL> set serveroutput on SQL> declare a number; b number; c number; begin a: c: =atb; dbms_output.put_line (‘sum of |/a/{ ‘and '{[b/|' is Ic); end; - Input:Emer value for a: 23 old: a:=&a; new: a:=23; Enter value for b: 12 old: b:=&b; new: b:=12; PL/SQL Program for if Condition: ( Write a PL/SQL Program to find out the maximum value using if condition) Procedure: Step 1: Start Step 2: Initialize the necessary variables. Step 3: invoke the if condition. Step 4: Execute the statements. Step 5: Stop. Program: SQL> set serveroutput on SQL> declare b number; c number; BEGIN if(C>B) THEN dbms_output.put_line('C is maximum’); end if:end; Output: anerraGs Oe Tay PL/SQL Program for If Else Condition: ( Write a PL/SQL Program to check whether the value is less than or greater than 5 using if else condition) Procedure: Step 1: Start Step 2: Initialize the necessary variables. Step 3: invoke the if else condition. Step 4: Execute the statements. Step 5: Stop. Program: SQL> set serveroutput on SQL> declare nnumber; begin dbms_output. put_line(‘enter a number‘); &number; ne ifn<5 then dbms_output.put_line(‘entered number is less than 5'); else dbms_output.put_line('entered number is greater than 5'); end end; /Input: Enter value for number: 2 old 5: n:=&number; new 5: n. Output: PL/SQL Program for If Else If Condition: ( Write a PLISQL Program to find the greatest of three numbers using if else if) Procedure: Step 1: Start Step 2: Initialize the necessary variables. Step 3: invoke the if else if condition. Step 4: Execute the statements. Step 5: Stop. Program: SQL> set server output on SQL> declare a number; b number; c number; begin a:=&a; b:=&b; cs&e; iffa>b)and(a>c) thendbms_output.put_line('A is maximum’); else if(b>a)and(b>c)then dbms_output.put_line('B is maximum’); else dbms_output.put_line('C is maximum’); end if: end; Input: Enter value for a: 21 old: a:=&a; new: a: Enter value for b: 12 old: &b; new: b:=12; Enter value for b: 45 old: c:=&b; new: Output: Pe Teas) PL/SQL Program for Looping Statement: ( Write a PL/SQL Program to find the summation of odd numbers using for loop) Procedure: Step 2: Initialize the necessary variables. Step 3: invoke the for loop condition. Step 4: Execute the statements. Step 5: Stop. Program: SOL> set server output onSQL> declare n nwnber; sum number default 0; end value number; begin end value:=&end value; forn in L.endvalue loop if mod(n,2)=1 then sum1:=sum1 +n; end if: end loop; dbms_output.put_line('sum ='|/sum1); end; / Input: Enter value for end value: 4 old : end value:=&end value; new : end value:=4; Output: PL/SQL Program for looping statement: (Write a PL/SQL Program to find the factorial of given number using for loop) Procedure: Step 1: StartStep 2: Initialize the necessary variables. Step 3: invoke the for loop condition. Step 4: Execute the statements. Step 5: Stop. Program: SQL> set server output on SQL> declare n number; i number; p number: begin ni=&n fori in L..n loop p=p*i ; end loop; dbms_output.put_line(n |/'! = 'I[p): end; Input: Enter value for n: Sold : n:=&n; new: n:=5; Output: Rua aeons Result: Thus a PL/SQL block to satisfy some conditions by accepting input from the user was created using oracle.Program-8 Aim: Write a PL/SQL block that handles all types of exceptions. Description: In PL/SQL, the user can catch certain runtime errors. Exceptions can be internally defined by Oracle or the user. Exceptions are used to handle errors that occur in your PL/SQL code. A PL/SQL block contains an EXCEPTION block to handle exception. There are three types of exceptions: 1. Predefined Oracle errors 2. Undefined Oracle errors 3. User-defined errors The different parts of the exception. 1. Declare the exception. 2. Raise an exception. 3. Handle the exception. An exception has four attributes: 1. Name provides a short description of the problem. 2. Type identifies the area of the error. 3. Exception Code gives a numeric representation of the exception. 4. Error message provides additional information about the exception. The predefined divide-by-zero exception has the following values for the attributes: 1. Name = ZERO_DIVIDE 2. Type = ORA (from the Oracle engine) 3. Exception Code = C01476Error message = divisor is equal to zero Exception Handling: PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as exception Handling. Using Exception Handling we can test the code and avoid it from exiting abruptly.When an exception occurs messages which explains its cause is received. PL/SQL Exception message consists of three parts. Type of Exception An Error Code A message Structure Of Exception Handling General Syntax For Coding The Exception Section DECLARE Declaration section BEGIN Exception section EXCEPTION WHEN ex_namel THEN -Error handling statements WHEN ex_name2 THEN -Error handling statements WHEN Others THEN -Error handling statements END; Types of Exceptions: There are 2 types of Exceptions. a) System Exceptions b) User-defined Exceptions a) System Exceptions System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule. There are some system exceptions which areraised frequently, so they are pre-defined and given a name in Oracle which are known as Named System Exceptions. For example: NO_LDATA_FOUND and ZERO_DIVIDE are called Named System exceptions. For Example: Suppose a NO_LDATA_FOUND exception is raised in a proc, we can write a code to handle the exception as given below. BEGIN Execution section EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line (‘A SELECT...INTO did not return any row.'); END; b) User-defined Exceptions PL/SQL allows us to define our own exceptions according to the need of our program. A user-defined exception must be declared and then raised explicitly, using a RAISE statement. To define an exception we use EXCEPTION keyword as below: EXCEPTION_NAME EXCEPTION; To raise exception that we've defined to use the RAISE statement as follows: RAISE EXCEPTION_NAME Raising Exceptions Exceptions are raised by the database server automatically whenever there is any internal database error, but exceptions can be raised explicitly by the programmer by using the command RAISE. Following is the simple syntax of raising an exception: DECLARE exception_name EXCEPTION; BEGIN IF condition THEN RAISE exception_name; END IF;EXCEPTION WHEN exception_name THEN statement; END; TYPES OF MORE COMMONLY USED EXCEPTIONS: NO_DATA_FOUND TOO_MANY_ROWS INVALID_CURSOR VALUE_ERROR INVALID_NUMBER ZERO_DIVIDE DUP_VAL_ON_INDEX CURSOR_ALREADY_OPEN NOT_LOGGED_ON Singleton Select statement returned no data. Singleton Select statement returned more than one row. Illegal cursor operation occured. Arithmetic, conversion, or truncation error occured. Conversion of a number to a character string failed. Attempted to divide by zero Attempted to insert a duplicate value into a column that has a unique index. Attempted to open a cursorthat was previously opened. A database call eas made without being logged in. TRANSACTION_BACKED_OUT Usually raised when a remote portion LOGIN_DENIED PROGRAM_ERROR STORAGE_ERROR TIMEOUT_ON_RESOURCE of a transaction is rolled back. Failed to login. If PL/SQL encounters an internal problem. If PL/SQL runs out of memory or if memory is corrupted. Timeout occured while PL/SQL was waiting for a resource.OTHERS For all of the rest. Program: ZERO_DIVIDE EXCEPTION SQL> BEGIN DBMS_OUTPUT.PUT_LINE(1 /0); END; 7 Output: Pera) aaa eer Pee ge ee Lad Ce ose ee a ed BEGIN DBMS_OUTPUT.PUT_LINE(1 /0); EXCEPTION WHEN ZERO_DIVIDE THEN DBMS_OQUTPUT.PUT_LINE{ Division by zero’); END; / Division by zero: INVALID_NUMBER EXCEPTION BEGIN INSERT INTO employees(DEPARTMENT_ID)VALUES(‘101x'); EXCEPTIONWHEN INVALID_NUMBER THEN DBMS_OUTPUT.PUT_LINE( ‘Conversion of string to number failed’); end; / Output: Conversion of string to number failed CW ee eae Pete eas) Other Exceptions BEGIN DBMS_OUTPUT.PUT_LINE(1 /0); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(‘An exception occurred’); END; ff Output: OS ata eee) War ett ees ea a First Create A Table Named Customerss Wth Attribute Id, Name, Address And Then Implement ‘The Following Code: SQL> declare cid customerss.id%type; c_name customerss.name%type; c_addr customerss.addressYtype; begin SELECT name,address INTO c_name,c_addrFROM customerss WHERE id=c_id; dbms_output.put_line('Name: '// c_name); dbms_output.put_line(‘Address: ' || c_addr); EXCEPTION WHEN no_data_found THEN dbms_output.put_line('No such customer!'); WHEN others THEN dbms_output.put_line('Error!'); Program: (The following example illustrates the programmer-defined exceptions. Get the salary of an employee and check it with the job’s salary range. If the salary is below the range, an exception BELOW_SALARY_RANGE is raised. If the salary is above the range, exception ABOVE_SALARY_RANGE is raised) SET SERVEROUTPUT ON SIZE 100000; DECLARE -- define exceptions BELOW_SALARY_RANGE EXCEPTION; ABOVE_SALARY_RANGE EXCEPTION; -- salary variables n_salary employees.salary%TYPE; salary%TYPE; n_max_salary employees.salary%TYPE; n_min_salary employee.-- input employee id n_emp_id employees.employee_id%TYPE := &emp_id; BEGIN SELECT salary, min_salary max_salary INTO n_salary, n_min_salary, n_max_salary FROM employees INNER JOIN jobs ON jobs,job_id = employees.job_id WHERE employee_id = n_emp_id; IF n_salary
n_max_salary THEN RAISE ABOVE_SALARY_RANGE; END IF; dbms_output.put_line('‘Employee ' || n_emp_id ||’ has salary $" |/ n_salary ); EXCEPTION WHEN BELOW_SALARY_RANGE THEN dbms_output.put_line('Employee ' |] n_emp_id || ' has salary below the salary range’); WHEN ABOVE_SALARY_RANGE THEN dbms_output.put_line('Employee ' |] n_emp_id || ' has salary above the salary range’); WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE(‘Employee ' |n_emp_id || ' not found’); END; / Result: Thus a PL/SQL block that handles all type of exceptions was written, executed and verified successfully.Program-9 Creation of Procedures. Description: PL/SQL Procedure The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or more specific tasks. It is just like procedures in other programming languages. The procedure contains a header and a body. Header: The header contains the name of the procedure and the parameters or variables passed to the procedure. Body: The body contains a declaration section, execution section and exception section similar to a general PL/SQL block. How to pass parameters in procedure: When you want to create a procedure or function, you have to define parameters .There is three ways to pass parameters in procedure: IN parameters: The IN parameter can be referenced by the procedure or function. The value of the parameter cannot be overwritten by the procedure or the function. OUT parameters: The OUT parameter cannot be referenced by the procedure or function, but the value of the parameter can be overwritten by the procedure or function. INOUT parameters: The INOUT parameter can be referenced by the procedure or function and the value of the parameter can be overwritten by the procedure or function. Creation of Procredure: Create for Replace} Procedure {procedure_name} (parameter, parameter...) IS{decalaration_section} BEGIN executable_section {EXCEPTION exception section} END {procedure_name}; y Example: Table: create table user(id integer(10) primary key,name varchar2(100)); Procedure: create procedure insert_user (id in number, name in varchar2) is begin insert into user values(id,name); end; / Create... Orow(s) affected REET Deleting a procedure: Drop procedure {procedure_name}; This syntax deletes the procedure. Example: Drop procedure insert_user; ER Ee eeProgram-10 Creation of database triggers and functions Description: Trigger: A trigger is a stored procedure in database which automatically invokes whenever a special event in the database occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when certain table columns are being updated. Syntax: create trigger [trigger_name} {before / after} {insert / update / delete} on {table_name} [for each row} {trigger_body} Explanation of syntax: 1. create trigger {trigger_name}: Creates or replaces an existing trigger with the trigger_name. 2. {before / after}: This specifies when the trigger will be executed. 3. finsert / update / delete}: This specifies the DML operation. 4. on {table_name}: This specifies the name of the table associated with the trigger. 5. ffor each row}: This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. 6. trigger_body}: This provides the operation to be performed as trigger is fired BEFORE and AFTER of Trigger:BEFORE triggers run the trigger action before the triggering statement is run. AFTER triggers run the trigger action after the triggering statement is run. Example: Given Student Report Database, in which student marks assessment is recorded. In such schema, create a trigger so that the total and percentage of specified marks is automatically inserted whenever a record is insert. Here, as trigger will invoke before record is inserted so, BEFORE Tag can be used. create trigger stud_marks before insert on Student for each row set Student.total tudent.subjl + Student.subj2 + Student.subj3, Student.per = Student.total * 60/100; Orow(s) affected, 2 warning(s): 12:00:06 Createt... 1681 Integer display width is deprecated and will be remo. 1681 Integer display width is deprecated and will be remo.Mini Project Hotel Room Management system Description: In this project we will be using Python — SQL connectivity to create a simple hotel room management system. We can add rooms, Display tables and Update data of the rooms through python and changes will be saved on our database. Syntax:easy conn=aysql «connector .connect (host= Ree aan a Reet hon nett et out at rat ou ot otCen print Pres} Constr global dictionary dictionary eet dictionary een Ciastciay Peer igprint( rs TDN ret Grete eum TC a input("Check-In (IFT print("chick in should ni input ("Check-In (SIFT initia) ormat (dd/mm/yyyy) oT TtaE DD) Seer STE TaD) fal) format (dd/mm,yr CE, oo 7 © ar a aD Ces eat Ne OT OT dictionary ue Pets ty ce ch cnn ots eure dictionary| dictionary|Petar Pug ay fe Crna) re) Peet Piste Gare Puan ast ‘onary['room'] = onary[ 'price’] = cst) EL sty PS em emer Ur st) Senne teae) amit) et Gae) et@atats Comet corn ees) Ge CZ i: ONC esta cic)Go to Line/Columneeaarsen print() ena home() exit() EO} erstas ea: emer Poo} = int (input ictionary[ ‘ci Pease ie Pata Pore Peta Piast Pause Nan ec Gn ace very PSG eres print(" 3 coff Pu eemeocn print( Geer) acne eer nr Penh ts Toa print(" 9 chee ee PSG Conant ie Pete Pane Puss Ta) Menu Card") ay 0.00 Sen Peo Pome eran! oan sen Teresaeironet Preah ees tta) e el GoenGe te ancl se) Eto} Payment () eeu G Ud penis print( mate print( print( print( aati aeeure home() exit() Record(): Steg Piste Petre print( Ke) Geena et ee cre SoCs print( Piste nput home () exit() home()Output: 1) Main menu ee Reece nso) ee Dest) CRC Gaia a) Room Service(Menu Card) (FY, FES) eC 5) Ce ene etc) fesse) Cr mens ta 2)Display Fucntion Cae ee eGn Rtas Cr Se Tere Address (J: Delhi Check-In (STFA a4) format (dd/mm/yyyy) : 10/11/2022 Cee erm Aca nC asap MREL IEEE. 7) your information has been stored <° Scam mg eee acne 2. Standard AC 3. 3-Bed Non-AC een Bs Ce Ro Rasta Canam: Lote! You have selected : Standard Non-AC Pore st ete et.) eee nn cree ccc aaas SRC Rts Beer Cree CN Cree cok co) Eee)3) Data Stored in the database Phone Number 54654546455, 7982323147 4545362156 13749472497241 4545452263 1245 7856321456 Address fast Debi Mahavirpark baspfasg 4545452263 asbdhdas HOstel number 4 309 ‘Cheden date 10/12/2022 2022-11-10 2022-11-12 2022-02-12 2022:02-10 2022-02-10 2021-05-01 Checkout date 12/11/2022 2022-11-12 2022-12-13, 2022-02-13 2022-02-12 2022-02-12 2022-05-02 314 315 Bgsteeecct
You might also like
Form 1a
PDF
No ratings yet
Form 1a
18 pages
SQL Cheat Sheet
PDF
No ratings yet
SQL Cheat Sheet
15 pages
Sem1 Statistics1
PDF
No ratings yet
Sem1 Statistics1
9 pages
Best DBMS
PDF
No ratings yet
Best DBMS
177 pages
Unit 4 Bcomcardbms 2024
PDF
No ratings yet
Unit 4 Bcomcardbms 2024
34 pages
GCAF25C1-IN-YRT-6JR (24 May)
PDF
No ratings yet
GCAF25C1-IN-YRT-6JR (24 May)
114 pages
DBMS M Iv
PDF
No ratings yet
DBMS M Iv
97 pages
SQL - Unit III
PDF
No ratings yet
SQL - Unit III
122 pages
SQL - Unit III - Removed
PDF
No ratings yet
SQL - Unit III - Removed
113 pages
(M7-MAIN) - Data Manipulation Language (DML)
PDF
No ratings yet
(M7-MAIN) - Data Manipulation Language (DML)
50 pages
DBMS Lab-1
PDF
No ratings yet
DBMS Lab-1
78 pages
Dbms Manual II Cse
PDF
No ratings yet
Dbms Manual II Cse
74 pages
Unit 3 - DBMS
PDF
No ratings yet
Unit 3 - DBMS
108 pages
SQL PLSQL Beginners 1.1
PDF
No ratings yet
SQL PLSQL Beginners 1.1
91 pages
Dbms Exp 2 Theory
PDF
No ratings yet
Dbms Exp 2 Theory
10 pages
Module4 Partial
PDF
No ratings yet
Module4 Partial
71 pages
Dbms Lab Manual
PDF
No ratings yet
Dbms Lab Manual
72 pages
Chapter 1
PDF
No ratings yet
Chapter 1
36 pages
DBMSFile SWAYAM
PDF
No ratings yet
DBMSFile SWAYAM
39 pages
Database Management Lab Manual
PDF
No ratings yet
Database Management Lab Manual
53 pages
DBMS Module 3
PDF
No ratings yet
DBMS Module 3
53 pages
CH 5. Structured Query Language (SQL) PDF
PDF
No ratings yet
CH 5. Structured Query Language (SQL) PDF
41 pages
Relational Database Rdbms Non-Relational Nosql
PDF
No ratings yet
Relational Database Rdbms Non-Relational Nosql
47 pages
DBMS SQL
PDF
No ratings yet
DBMS SQL
43 pages
Beautified SQL Guide
PDF
No ratings yet
Beautified SQL Guide
13 pages
Unit 2 SQL
PDF
No ratings yet
Unit 2 SQL
17 pages
What Is A Database (DB) ?
PDF
No ratings yet
What Is A Database (DB) ?
22 pages
Student Record
PDF
No ratings yet
Student Record
32 pages
SQL Notes
PDF
No ratings yet
SQL Notes
17 pages
Sem2 Maths2
PDF
No ratings yet
Sem2 Maths2
21 pages
SQL Queries
PDF
No ratings yet
SQL Queries
62 pages
Sem1 Statistics1
PDF
No ratings yet
Sem1 Statistics1
15 pages
Dbms Notes
PDF
No ratings yet
Dbms Notes
61 pages
Fatima Code
PDF
No ratings yet
Fatima Code
24 pages
DP Note Sss2 Second Term 2024-25
PDF
No ratings yet
DP Note Sss2 Second Term 2024-25
19 pages
Micro Project
PDF
No ratings yet
Micro Project
15 pages
FDB Lecture05
PDF
No ratings yet
FDB Lecture05
52 pages
SQL Notes
PDF
No ratings yet
SQL Notes
24 pages
Dbms Practical Adivya 08
PDF
No ratings yet
Dbms Practical Adivya 08
20 pages
Elasticity of Demand EE 5th
PDF
No ratings yet
Elasticity of Demand EE 5th
10 pages
Sem1 Statistics1
PDF
No ratings yet
Sem1 Statistics1
11 pages
1
PDF
No ratings yet
1
9 pages
SQL - Xii IP
PDF
No ratings yet
SQL - Xii IP
28 pages
What Is A Query in DBMS: ID Name Marks
PDF
No ratings yet
What Is A Query in DBMS: ID Name Marks
12 pages
Practical 2 1 PDF
PDF
No ratings yet
Practical 2 1 PDF
10 pages
SQL
PDF
No ratings yet
SQL
15 pages
Chapter - 5 MySQL SQL Revision Tour
PDF
No ratings yet
Chapter - 5 MySQL SQL Revision Tour
12 pages
SQL Language - DML and DDL
PDF
No ratings yet
SQL Language - DML and DDL
53 pages
M-2 (2) RDBMS
PDF
No ratings yet
M-2 (2) RDBMS
7 pages
FDB Lecture05
PDF
No ratings yet
FDB Lecture05
43 pages
SQL Notes
PDF
No ratings yet
SQL Notes
5 pages
A641048165 24930 21 2019 SQL
PDF
No ratings yet
A641048165 24930 21 2019 SQL
8 pages
Database Lab Session
PDF
No ratings yet
Database Lab Session
18 pages
Database Systems Scse
PDF
No ratings yet
Database Systems Scse
80 pages
Cs 6312
PDF
No ratings yet
Cs 6312
56 pages
DDLObjects
PDF
No ratings yet
DDLObjects
18 pages
Cheat Sheet
PDF
No ratings yet
Cheat Sheet
29 pages
Wa0001 PDF
PDF
No ratings yet
Wa0001 PDF
16 pages
SQL Is Structured Query Language PDF
PDF
No ratings yet
SQL Is Structured Query Language PDF
14 pages
Lab Full Slides Short Note Except 7&8
PDF
No ratings yet
Lab Full Slides Short Note Except 7&8
4 pages
SQL Commands
PDF
No ratings yet
SQL Commands
10 pages
Chapter-13 14 MySQL Class 12
PDF
No ratings yet
Chapter-13 14 MySQL Class 12
33 pages
ISM-AYUSH BANSAL Practical file-BBA 212
PDF
No ratings yet
ISM-AYUSH BANSAL Practical file-BBA 212
20 pages
Structured Query Language (SQL) : Advant
PDF
No ratings yet
Structured Query Language (SQL) : Advant
19 pages
Structured Query Language (SQL)
PDF
No ratings yet
Structured Query Language (SQL)
9 pages
Assignment#3
PDF
No ratings yet
Assignment#3
6 pages