A cursor is a way to iterate each row one by one in a SQL Server table. Although, T-SQL is a set based language however, many a times need arises to do row by row operations. Below is a simple cursor in SQL Server to select values from a table.

1_simple cursor in sql server

The query declares a sample_cursor to iterate through Sales.SalesOrderDetail table. The @@Fetchstatus function returns the status of the last cursor FETCH against a cursor, where 0 means successful, -1 is failed or row is not in result set and -2 means that row fetched is not present in the cursor.  Thus, we can iterate through a cursor while @@Fetchstatus =0. The complex operation is done inside the while loop. The example shown here is just to explain the cursor; it doesn’t perform any complex operation.

 

Regards

Ahmad Osama

Like us on FaceBook Join the fastest growing SQL Server group on FaceBook

Follow me on TwitterFollow me on FaceBook