Create Temporary cursor in MS SQL Server


In this article I am give to explain what is temporary cursor and how you can use it in a stored procedure. Temporary cursor is very useful and it is very simple. The Temporary cursor is very fast and easy and it requires very less code compared to the normal cursor.

Here I am going to explain you the syntax for creating temporary cursor. You can use temporary cursor in Stored Procedure and also in a simple and regular queryy. Below examples shows both the syntax.

Syntax




select * into TemporaryTable from tbaleName
while exists(select * from TemporaryTable )
Begin
it Return one by one row
you can write multiple Statement
End


Example




Create Proc ProcedureName()
as
Begin
select * into #Temp from tbaleName
while exists(select * from #Temp)
Begin
declare @ID int,@Name varchar(150),@Address varchar(250)
select @ID=id,@Name=Name,@Address=Address from #Temp
print '---------------------Personal Details------------'
print @ID
print @Name
Print @Address
print ---------------------Closr Personal Details-------'
delete from #Temp where ID=@ID
End
End


You can see how temporary cursor is returning one by one row in above example like normal cursor.
If any problem or any question about this query please post below.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: