0% found this document useful (0 votes)
61 views30 pages

Cursors, Triggers

SQL aggregation functions are used to perform calculations on multiple rows of a single column in a table and return a single value. The document discusses several common aggregation functions - COUNT, SUM, AVG, MAX, and MIN - and provides syntax examples for each. Triggers in SQL Server are stored procedures that execute automatically in response to events like data modifications or logins. There are different types of triggers including DDL triggers for schema changes and DML triggers for data manipulation events like inserts, updates, and deletes. Triggers can be used to audit changes to tables or enforce business rules.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views30 pages

Cursors, Triggers

SQL aggregation functions are used to perform calculations on multiple rows of a single column in a table and return a single value. The document discusses several common aggregation functions - COUNT, SUM, AVG, MAX, and MIN - and provides syntax examples for each. Triggers in SQL Server are stored procedures that execute automatically in response to events like data modifications or logins. There are different types of triggers including DDL triggers for schema changes and DML triggers for data manipulation events like inserts, updates, and deletes. Triggers can be used to audit changes to tables or enforce business rules.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

SQL Aggregate Functions

o SQL aggregation function is used to perform the calculations on multiple rows of


a single column of a table. It returns a single value.
o It is also used to summarize the data.

Types of SQL Aggregation Function

1. COUNT FUNCTION

o COUNT function is used to Count the number of rows in a database table. It can
work on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.

Syntax

1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )
Sample table:

PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example: COUNT()

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;

Output:

10

Example: COUNT with WHERE

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;
Output:

Example: COUNT() with DISTINCT

1. SELECT COUNT(DISTINCT COMPANY)


2. FROM PRODUCT_MAST;

Output:

Example: COUNT() with GROUP BY

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;

Output:

Com1 5
Com2 3
Com3 2

Example: COUNT() with HAVING

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;

Output:

Com1 5
Com2 3

2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric
fields only.
Syntax

1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )

Example: SUM()

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;

Output:

670

Example: SUM() with WHERE

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;

Output:

320

Example: SUM() with GROUP BY

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;

Output:

Com1 150
Com2 170

Example: SUM() with HAVING

1. SELECT COMPANY, SUM(COST)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING SUM(COST)>=170;

Output:

Com1 335
Com3 170

3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.

Syntax

1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )

Example:

1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;

Output:

67.00

4. MAX Function
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.

Syntax

1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )

Example:
1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30

5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.

Syntax

1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )

Example:

1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;

Output:

10

Triggers in SQL Server


A trigger is a set of SQL statements that reside in system memory with unique names. It
is a specialized category of stored procedure that is called automatically when a database
server event occurs. Each trigger is always associated with a table.

A trigger is called a special procedure because it cannot be called directly like a stored
procedure. The key distinction between the trigger and procedure is that a trigger is called
automatically when a data modification event occurs against a table. A stored procedure,
on the other hand, must be invoked directly.

The following are the main characteristics that distinguish triggers from stored
procedures:

o We cannot manually execute/invoked triggers.


o Triggers have no chance of receiving parameters.
o A transaction cannot be committed or rolled back inside a trigger.

Syntax of Trigger
We can create a trigger in SQL Server by using the CREATE TRIGGER statement as
follows:

1. CREATE TRIGGER schema.trigger_name


2. ON table_name
3. AFTER {INSERT, UPDATE, DELETE}
4. [NOT FOR REPLICATION]
5. AS
6. {SQL_Statements}

The parameter descriptions of this syntax illustrate below:

schema: It is an optional parameter that defines which schema the new trigger belongs
to.

trigger_name: It is a required parameter that defines the name for the new trigger.

table_name: It is a required parameter that defines the table name to which the trigger
applies. Next to the table name, we need to write the AFTER clause where any events like
INSERT, UPDATE, or DELETE could be listed.

NOT FOR REPLICATION: This option tells that SQL Server does not execute the trigger
when data is modified as part of a replication process.

SQL_Statements: It contains one or more SQL statements that are used to perform
actions in response to an event that occurs.

When we use triggers?


Triggers will be helpful when we need to execute some events automatically on certain
desirable scenarios. For example, we have a constantly changing table and need to know
the occurrences of changes and when these changes happen. If the primary table made
any changes in such scenarios, we could create a trigger to insert the desired data into a
separate table.
Example of Trigger in SQL Server
Let us understand how we can work with triggers in the SQL Server. We can do this by
first creating a table named 'Employee' using the below statements:

1. CREATE TABLE Employee


2. (
3. Id INT PRIMARY KEY,
4. Name VARCHAR(45),
5. Salary INT,
6. Gender VARCHAR(12),
7. DepartmentId INT
8. )

Next, we will insert some record into this table as follows:

1. INSERT INTO Employee VALUES (1,'Steffan', 82000, 'Male', 3),


2. (2,'Amelie', 52000, 'Female', 2),
3. (3,'Antonio', 25000, 'male', 1),
4. (4,'Marco', 47000, 'Male', 2),
5. (5,'Eliana', 46000, 'Female', 3)

We can verify the insert operation by using the SELECT statement. We will get the below
output:

1. SELECT * FROM Employee;

We will also create another table named 'Employee_Audit_Test' to automatically store


transaction records of each operation, such as INSERT, UPDATE, or DELETE on the
Employee table:
1. CREATE TABLE Employee_Audit_Test
2. (
3. Id int IDENTITY,
4. Audit_Action text
5. )

Now, we will create a trigger that stores transaction records of each insert
operation on the Employee table into the Employee_Audit_Test table. Here we are going
to create the insert trigger using the below statement:

1. CREATE TRIGGER trInsertEmployee


2. ON Employee
3. FOR INSERT
4. AS
5. BEGIN
6. Declare @Id int
7. SELECT @Id = Id from inserted
8. INSERT INTO Employee_Audit_Test
9. VALUES ('New employee with Id = ' + CAST(@Id AS VARCHAR(10)) + ' is added at ' +
CAST(Getdate() AS VARCHAR(22)))
10. END

After creating a trigger, we will try to add the following record into the table:

1. INSERT INTO Employee VALUES (6,'Peter', 62000, 'Male', 3)

If no error is found, execute the SELECT statement to check the audit records. We will get
the output as follows:

We are going to create another trigger to store transaction records of each delete
operation on the Employee table into the Employee_Audit_Test table. We can create the
delete trigger using the below statement:

1. CREATE TRIGGER trDeleteEmployee


2. ON Employee
3. FOR DELETE
4. AS
5. BEGIN
6. Declare @Id int
7. SELECT @Id = Id from deleted
8. INSERT INTO Employee_Audit_Test
9. VALUES ('An existing employee with Id = ' + CAST(@Id AS VARCHAR(10)) + ' is delete
d at ' + CAST(Getdate() AS VARCHAR(22)))
10. END

After creating a trigger, we will delete a record from the Employee table:

1. DELETE FROM Employee WHERE Id = 2;

If no error is found, it gives the message as below:

Finally, execute the SELECT statement to check the audit records:

In both the triggers code, you will notice these lines:

1. SELECT @Id = Id from inserted


2. SELECT @Id = Id from deleted

Here inserted and deleted are special tables used by the SQL Server. The inserted table
keeps the copy of the row when you insert a new row into the actual table. And the deleted
table keeps the copy of the row you have just deleted from the actual table.

Types of SQL Server Triggers


We can categorize the triggers in SQL Server in mainly three types:

1. Data Definition Language (DDL) Triggers


2. Data Manipulation Language (DML) Triggers
3. Logon Triggers

DDL Triggers
DDL triggers are fired in response to the DDL events, such as CREATE, ALTER, and DROP
statements. We can create these triggers at the database level or server level, depending
on the type of DDL events. It can also be executed in response to certain system-defined
stored procedures that do DDL-like operations.

The DDL triggers are useful in the following scenario:

o When we need to prevent the database schema from changing


o When we need to audit changes made in the database schema
o When we need to respond to a change made in the database schema

DML Triggers
DML triggers are fired in response to DML events like INSERT, UPDATE, and DELETE
statements in the user's table or view. It can also be executed in response to DML-like
operations performed by system-defined stored procedures.

The DML triggers can be classified into two types:

o After Triggers
o Instead Of Triggers

After Triggers

After trigger fires, when SQL Server completes the triggering action successfully, that fired
it. Generally, this trigger is executed when a table completes an insert, update or delete
operations. It is not supported in views. Sometimes it is known as FOR triggers.

We can classify this trigger further into three types:

1. AFTER INSERT Trigger


2. AFTER UPDATE Trigger
3. AFTER DELETE Trigger

Example: When we insert data into a table, the trigger associated with the insert
operation on that table will not fire until the row has passed all constraints, such as the
primary key constraint. SQL Server cannot fire the AFTER trigger when the data insertion
failed.

The following is illustration of the After Triggers syntax in SQL Server:

1. CREATE TRIGGER schema_name.trigger_name


2. ON table_name
3. AFTER {INSERT | UPDATE | DELETE}
4. AS
5. BEGIN
6. -- Trigger Statements
7. -- Insert, Update, Or Delete Statements
8. END

Instead of Triggers
Instead of Trigger fires before SQL Server begins to execute the triggering operation that
triggered it. It means that no condition constraint check is needed before the trigger runs.
As a result, even if the constraint check fails, this trigger will fire. It is the opposite of the
AFTER trigger. We can create the INSTEAD OF triggers on a table that executes
successfully but doesn't contain the table's actual insert, update, or delete operations.

We can classify this trigger further into three types:

1. INSTEAD OF INSERT Trigger


2. INSTEAD OF UPDATE Trigger
3. INSTEAD OF DELETE Trigger

Example: When we insert data into a table, the trigger associated with the insert
operation on that table will fire before the data has passed all constraints, such as the
primary key constraint. SQL Server also fires the Instead of Trigger if the data insertion
fails.

The following is an illustration of the Instead of Triggers syntax in SQL Server:


1. CREATE TRIGGER schema_name.trigger_name
2. ON table_name
3. INSTEAD OF {INSERT | UPDATE | DELETE}
4. AS
5. BEGIN
6. -- trigger statements
7. -- Insert, Update, or Delete commands
8. END

Logon Triggers
Logon triggers are fires in response to a LOGON event. The LOGON event occurs when
a user session is generated with an SQL Server instance, which is made after the
authentication process of logging is completed but before establishing a user session. As
a result, the SQL Server error log will display all messages created by the trigger, including
error messages and the PRINT statement messages. If authentication fails, logon triggers
do not execute. These triggers may be used to audit and control server sessions, such as
tracking login activity or limiting the number of sessions for a particular login.

How to SHOW Triggers in SQL Server?


When we have many databases with multiple tables, the show or list trigger comes in
handy. When the table names in multiple databases are the same, this query is extremely
helpful. Using the following command, we can see a list of all the triggers available in SQL
Server:

1. SELECT name, is_instead_of_trigger


2. FROM sys.triggers
3. WHERE type = 'TR';

If we are using the SQL Server Management Studio, it is very easy to show or list all
triggers available in any specific table. We can do this using the following steps:

o Go to the Databases menu, select desired database, and then expand it.
o Select the Tables menu and expand it.
o Select any specific table and expand it.
We will get various options here. When we choose the Triggers option, it displays all the
triggers available in this table.

How to UPDATE Triggers in SQL Server?


The data stored in the table can be changed over a period of time. In that case, we also
need to make changes in the triggers. We can do this in two ways into the SQL Server.
The first one is to use the SQL Server Management Studio, and the second one is the
Transact-SQL Query.

Modify Triggers using SSMS


First, open the Management Studio to modify the trigger. Next, go to the database and
then the table where the trigger is stored. Now, right-click on the trigger that you are
going to change or update. It will open the context menu where you will
choose Modify option:
When you select the Modify option, you will see a new query window with automatically
generated ALTER TRIGGER code. We can change it according to our needs.
Modify Triggers using SQL Command
We can use the ALTER TRIGGER statement to modify the triggers in MS SQL. The
following statement allows us to do modifications to the triggers:

1. ALTER TRIGGER [dbo].[triggers_in_sql]


2. ON [dbo].[EmployeeTable]
3. AFTER INSERT
4. AS
5. BEGIN
6. -- Modify as per your needs
7. END

How to DELETE Triggers in SQL Server?


We can remove an existing trigger in SQL Server using the DROP TRIGGER statement.
We must be very careful while removing a trigger from the table. Because once we have
deleted the trigger, it cannot be recovered. If a trigger is not found, the DROP TRIGGER
statement throws an error.

The following syntax removes DML triggers:

1. DROP TRIGGER [IF EXISTS] schema_name.trigger_name;


If we want to remove more than one trigger at once, we must separate the trigger using
the comma operator:

1. DROP TRIGGER schema_name.trigger_name1, trigger_name2.....n;

We can use the DROP TRIGGER statement in the below format to delete one or more
LOGON triggers:

1. DROP TRIGGER [ IF EXISTS ] trigger_name1, trigger_name2.....n


2. ON { DATABASE | ALL SERVER };

We can use the DROP TRIGGER statement in the below format to delete one or more DDL
triggers:

1. DROP TRIGGER [ IF EXISTS ] trigger_name1, trigger_name2.....n


2. ON ALL SERVER;

If we are using the SQL Server Management Studio, it makes it very easy to delete triggers
from the table. We can do this using the following steps:

o Go to the Databases -> Tables menu and expand it.


o Select any specific table, expand it, and choose the Triggers option

This option displays all the available triggers in this table. Now, right-click on any specific
trigger that you want to remove and choose the Delete option from the drop-down
menu.
Advantages of Triggers
The following are the advantages of using triggers in SQL Server:

o Triggers set database object rules and roll back if any change does not satisfy those
rules. The trigger will inspect the data and make changes if necessary.
o Triggers help us to enforce data integrity.
o Triggers help us to validate data before inserted or updated.
o Triggers help us to keep a log of records.
o Triggers increase SQL queries' performance because they do not need to compile
each time they are executed.
o Triggers reduce the client-side code that saves time and effort.
o Triggers are easy to maintain.

Disadvantages of Triggers
The following are the disadvantages of using triggers in SQL Server:

o Triggers only allow using extended validations.


o Triggers are invoked automatically, and their execution is invisible to the user.
Therefore, it isn't easy to troubleshoot what happens in the database layer.
o Triggers may increase the overhead of the database server.
o We can define the same trigger action for multiple user actions such as INSERT and
UPDATE in the same CREATE TRIGGER statement.
o We can create a trigger in the current database only, but it can reference objects
outside the current database.

Cursor in SQL
In SQL, a cursor is a temporary workstation that is allocated by the database server during
the execution of a statement.

It is a database object that allows us to access data of one row at a time. This concept of
SQL is useful when the user wants to update the rows of the table one by one.

The cursor in SQL is the same as the looping technique of other programming languages.
The collection of tuples held by the cursor is known as the active set.

In SQL database systems, users define the cursor using DECLARE statement and take the
SELECT statement as the parameter, which helps in returning the set of rows.

In this SQL article, we will learn about the types of a cursor, the life cycle of a cursor, syntax
of a cursor, and the implementation of a cursor.

Types of Cursor in SQL


Following are the two types of Cursor in Structured Query Language:

1. Implicit Cursor
2. Explicit Cursor

Implicit Cursor
These types of cursors are generated and allocated by the SQL server when the system
performs INSERT, DELETE, and UPDATE operations on SQL queries.
This cursor is also referred to as the default cursor in SQL.

An implicit cursor is also created by the system when the SELECT query selects the single
row.

Explicit Cursor
These types of cursors are created by the user using the SELECT query.

An explicit cursor holds multiple records but processes a single row at a time. It uses the
pointer, which moves to another row after reading one row.

It is basically used for gaining extra control over the temporary workstation.

Life Cycle of Cursor


The life cycle of the cursor is described into the following five stages:

1. Declare a Cursor
2. Open Cursor
3. Fetch Data from Cursor
4. Close Cursor Connection
5. Deallocate cursor

Let's discuss each stage in brief:

1. Declare a Cursor
First, we have to declare the cursor by using the following SQL syntax:

1. DECLARE Cursor_Name CURSOR FOR Select_Statement;

In this syntax, we have to specify the name and data type of the cursor just after the
DECLARE keyword. After that, we have to write the SELECT statement, which defines the
result set for the cursor.

2. Open Cursor
It is the second stage that opens the cursor for storing the data retrieved from the result
set. We can open the cursor by using the following SQL syntax:

1. OPEN Cursor_Name;

3. Fetch Cursor
It is the third stage in the cursor life cycle that fetches the rows for performing the
insertion, deletion, and updation operations on the currently active tuple in the cursor.

Following are the six options that are used in syntax for fetching data from the cursor:

i. FIRST: This option allows the system to access only the first record from the cursor
table. The syntax for the FIRST option is given below:

1. FETCH FIRST FROM Cursor_Name;

ii. LAST: This option allows the system to access only the last record from the cursor table.
The syntax for the LAST option is as follows:

1. FETCH LAST FROM Cursor_Name;

iii. NEXT: This method allows the system to access the data in the forward direction from
the cursor table. It is the default option. The syntax of this method is as follows:

1. FETCH NEXT FROM Cursor_Name;

iv. PRIOR: This method allows the system to access the data in the backward direction
from the cursor table. The syntax of this option is as follows:

1. FETCH PRIOR FROM Cursor_Name;

v. ABSOLUTE n: This method allows the system to access the data of the exact nth row
from the cursor table. The syntax of this option is mentioned below:

1. FETCH ABSOLUTE n FROM Cursor_Name;

vi. RELATIVE n: This method allows the system to access the data in both incremental
and decremental processes. The syntax of this option is mentioned below:

1. FETCH RELATIVE n FROM Cursor_Name;


4. Close Cursor
It is the fourth stage in the process of the cursor. When we complete the work with the
cursor, we have to close the cursor in this stage. We can close the cursor in SQL by using
the following query:

CLOSE Cursor_Name;

5. Deallocate Cursor
It is the last and fifth stage of the cursor life cycle. In this part, we have to erase the
definition of the cursor and discharge all the system resources combined with the cursor.

Syntax of a Cursor in SQL


1. DECLARE @YourVariables nvarchar(50) //You have to declare all the required variables

2. DECLARE My_Cursor_Name CURSOR // You have to declare the Name of your Curso
r
3. [LOCAL | GLOBAL] // You have to specify the Scope of your Cursor
4. [FORWARD_ONLY | SCROLL] // You have to specify the movement direction of y
our Cursor
5. [ KEYSET | DYNAMIC |STATIC | FAST_FORWARD] // You have to specify the Basic type
of your Cursor
6. [ SCROLL_LOCKS | OPTIMISTIC |READ_ONLY ] // You have to specify the Locks for your
Cursor
7. OPEN My_Cursor_Name // You have to Open Your Cursor
8. FETCH NEXT FROM My_Cursor_Name // This line fetches the data from your Cursor
9. CLOSE My_Cursor_Name // Here, you have to close Your Cursor
10. DEALLOCATE My_Cursor_Name // Here, you have to deallocate the cursor memory.

Basic Type of Cursor


Following are the four basic types of cursor in Structured Query Language:

1. STATIC Cursor
2. Forward Only cursor
3. KEYSET Driven Cursor
4. Dynamic Cursor

STATIC Cursor
The static cursor can move in forward as well as backward direction. This type of cursor
populates the result set during the creation of a cursor. Compared to other cursors, it is
slow and uses more space in the memory.

By default, these types of cursors are scrollable. The static cursor does not allow the
database users to modify and delete data.

Forward Only Cursor


This type of cursor accesses and updates the data only in the forward direction through
the result set. So, it is the fastest cursor among all the four cursors.

The main disadvantage of this cursor is that it does not support backward scrolling.

Following are the three types of 'Forward only Cursor':

1. Forward_Only KEYSET,
2. Forward_Only KEYSET,
3. FAST_FORWARD

DYNAMIC Cursor
The dynamic cursor is just opposite to the static cursor. It allows us to execute the INSERT,
DELETE, and UPDATE operations while the cursor is open.

It checks all the modifications done on the rows and values in the result set.

KEYSET Driven Cursor


This type of cursor accesses the data from the first to the last row and last to the first row.
When the user opens the KEYSET cursor, it automatically creates the list of unique values
which uniquely identify each row in the entire result set.

Example of Cursor in SQL


Create a Student table in SQL using the following query:

1. CREATE TABLE Student


2. (
3. Student_RollNo INT PRIMARY KEY,
4. Student_Name nvarchar(60) NOT NULL,
5. Student_Course nvarchar(20) NOT NULL,
6. Student_Age INTNOT NULL,
7. Student_Marks INT NOT NULL
8. ) ;

Now, insert some values into the above Student table as shown in the following block:

1. INSERT INTO Student (Student_RollNo, Student_Name, Student_Course, Student_Age, S


tudent_Marks) VALUES ( 1, Amit, BCA, 19, 88),
2. ( 2, Rahul, MCA, 21, 98),
3. ( 3, Jones, B.tech, 20, 93),
4. ( 4, Riya, BCA, 19, 89),
5. ( 5, Aaniya, BBA, 21, 92),
6. ( 6, Saket, MCA, 19, 95),
7. ( 7, Shobhit, MBA, 20, 90),
8. ( 8, Ishika, BCA, 21, 89),
9. ( 9, Parul, B.tech, 19, 91),
10. ( 10, Yukti, BCA, 20, 96);

We can check the data of the Student table by using the following SELECT statement in
SQL:

1. SELECT * FROM Student;

This query shows the data of the Student table in the output:

Student_RollNo Student_Name Student_Course Student_Age Student_Marks

1 Amit BCA 19 88

2 Rahul MCA 21 98
3 Jones B.tech 20 93

4 Riya BCA 19 89

5 Aaniya BBA 21 92

6 Saket MCA 19 95

7 Shobhit MBA 20 90

8 Ishika BCA 21 89

9 Parul B.tech 19 91

10 Yukti BCA 20 96

Now, we will create the following cursor for displaying the record of students from the
Student table:

1. DECLARE @Student_RollNo INT, @Student_Name NVARCHAR(50), @Student_Course N


VARCHAR(50) /*Here, we declare the variables for holding data. */
2. /* Here, we declare and set counter */
3. DECLARE @Counter INT
4. SET @Counter = 1
5. PRINT '-------- Record of Students --------';
6. /* Declare the cursor*/
7. DECLARE Print_Student_Details CURSOR
8. FOR
9. SELECT Student_RollNo, Student_Name, Student_Course FROM customer
10. /* Open the cursor */
11. OPEN Print_Student_Details
12. /* Fetch the record from the cursor into the variables. */
13. FETCH NEXT FROM Print_Student_Details INTO
14. @Student_RollNo, @Student_Name, @Student_Course
15. /* LOOP UNTIL RECORDS ARE AVAILABLE. */
16. WHILE @@FETCH_STATUS = 0
17. BEGIN
18. IF @Counter = 1
19. BEGIN
20. PRINT 'Student_RollNo' + CHAR(9) + 'Student_Name' + CHAR(9) + CHAR(9) + 'Student
_Course'
21. PRINT '--------------------------'
22. END
23. /* This statement prints the current record */
24. PRINT CAST(@ Student_RollNo AS NVARCHAR(10)) + CHAR(9) + @Student_Name + C
HAR(9) + CHAR(9) + @Student_Course
25. /* This statement increments the counter variable */
26. SET @Counter = @Counter + 1
27. /* This statament fetch the next record into the variables. */
28. FETCH NEXT FROM Print_Student_Details INTO
29. @Student_RollNo, @Student_Name, @Student_Course
30. END
31. /* This statement closes the cursor*/
32. CLOSE Print_Student_Details
33. /* This statement deallocates the cursor*/
34. DEALLOCATE Print_Student_Details

The above cursor gives the following output:

Student_RollNo Student_Name Student_Course

1 Amit BCA

2 Rahul MCA

3 Jones B.tech

4 Riya BCA

5 Aaniya BBA

6 Saket MCA

7 Shobhit MBA

8 Ishika BCA
9 Parul B.tech

10 Yukti BCA

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.

o Header: The header contains the name of the procedure and the parameters or variables
passed to the procedure.
o 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:

1. 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.
2. 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.
3. 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.
A procedure may or may not return any value.

PL/SQL Create Procedure


Syntax for creating procedure:

1. CREATE [OR REPLACE] PROCEDURE procedure_name


2. [ (parameter [,parameter]) ]
3. IS
4. [declaration_section]
5. BEGIN
6. executable_section
7. [EXCEPTION
8. exception_section]
9. END [procedure_name];

Create procedure example

In this example, we are going to insert record in user table. So you need to create user
table first.

Table creation:

1. create table user(id number(10) primary key,name varchar2(100));

Now write the procedure code to insert record in user table.

Procedure Code:

1. create or replace procedure "INSERTUSER"


2. (id IN NUMBER,
3. name IN VARCHAR2)
4. is
5. begin
6. insert into user values(id,name);
7. end;
8. /

Output:

Procedure created.

You might also like