Cursor Usage In SQL Server

WHAT IS CURSOR?

In SQL Server, the Cursor walks through the recordset, which is returned as a select result, to perform a transaction on each row.

You can use it with Stored Procedure or Trigger or you can run TSQL code from within a job.

Let’s make a simple example to understand what a cursor is and how to use it.

Let’s write a script that sends a congratulatory mail to students who have successfully completed their education in an educational institution.

Our student information is kept in the following table.

Let’s send a congratulatory mail to the students who are on grade 70 or above and send an e-mail to the students who are below the score of 70 that they can not finish the course successfully.

You need to configure Database Mail to send mail via Database Mail.

You can benefit from the article titled “How To Configure Database Mail On SQL Server“.

CREATE A TABLE

 

After creating the table, I will add 3 records to my table using the following script.

 

INSERTING RECORDS TO THE TABLE

 

Then, using the cursor, go through the records in the student table one by one and check the score when we get to each record, and if it is over 70, we will send a congratulatory mail to that student and a failure mail below 70.

Within the code I have written explanations for easier understanding between / ** / expressions.

 

CREATING CURSOR

dbtut
Author: dbtut

We are a team with over 10 years of database management and BI experience. Our Expertises: Oracle, SQL Server, PostgreSQL, MySQL, MongoDB, Elasticsearch, Kibana, Grafana.

Leave a Reply

Your email address will not be published. Required fields are marked *