Cursors in sql server Part 63
Text version of the video
All SQL Server Text Articles
All SQL Server Slides
All Dot Net and SQL Server Tutorials in English
All Dot Net and SQL Server Tutorials in Arabic
Relational Database Management Systems, including sql server are very good at handling data in SETS. For example, the following “UPDATE” query, updates a set of rows that matches the condition in the “WHERE” clause at the same time.
Update tblProductSales Set UnitPrice = 50 where ProductId = 101
However, if there is ever a need to process the rows, on a row-by-row basis, then cursors are your choice. Cursors are very bad for performance, and should be avoided always. Most of the time, cursors can be very easily replaced using joins.
There are different types of cursors in sql server as listed below. We will talk about the differences between these cursor types in a later video session.
Let us now look at a simple example of using sql server cursor to process one row at time. We will be using tblProducts and tblProductSales tables, for this example. On my machine, there are 400,000 records in tblProducts and 600,000 records in tblProductSales tables. If you want to learn about generating huge amounts of random test data, please watch Part – 61 in sql server video tutorial. The link is below.
Cursor Example: Let us say, I want to update the UNITPRICE column in tblProductSales table, based on the following criteria
1. If the ProductName = ‘Product – 55’, Set Unit Price to 55
2. If the ProductName = ‘Product – 65’, Set Unit Price to 65
3. If the ProductName is like ‘Product – 100%’, Set Unit Price to 1000
For the SQL code samples used in the demo please visit my blog at the following link
The cursor will loop thru each row in tblProductSales table. As there are 600,000 rows, to be processed on a row-by-row basis, it takes around 40 to 45 seconds on my machine. We can achieve this very easily using a join, and this will significantly increase the performance. We will discuss about this in our next video session.
To check if the rows have been correctly updated, please use the following query.
Select Name, UnitPrice
from tblProducts join
tblProductSales on tblProducts.Id = tblProductSales.ProductId
where (Name=’Product – 55′ or Name=’Product – 65′ or Name like ‘Product – 100%’)