Development resources, articles, tutorials, code samples, tools and downloads for ASP.Net, SQL Server, Reporting Services, T-SQL, Windows, AWS, SAP HANA and ABAP
SQL developers can create nested cursor in SQL Server by defining an outer cursor and within the cursor code a new cursor is defined for each row in main cursor select.
The inner cursor is created, executed, closed and deallocated each time in the outer cursor for each row.
In short, a nested cursor is a defining a loop in another loop in SQL Server.
SQL Server administrators and t-sql developers can use nested cursors for complex structures.
But when considering performance issues even using a sql cursor is not suggested, a nested cursor is not the first solution that will be choosen.
I want to give a nested cursor sample t-sql code which uses AdventureWorks2008 sample database.
This nested sql cursor sample will loop through all departments in Department table in AdventureWorks2008 sql database and list all employee working in that department using the Employee and EmployeeDepartmentHistory tables.
The output of the above SQL Server nested cursor will be as follows:
SQL developers should always keep that in mind, if there is a better way to solve the t-sql problem without using sql cursors that method should be choosen.
For example the above list can also be created using the following transact-sql select statement.