Original: Common cursor looping usages in SQL Server stored procedures
With cursors, and while you can traverse every record in your query and pass the required fields to variables for appropriate processing
DECLARE @A1 VARCHAR(Ten),@A2 VARCHAR(Ten),@A3 INTDECLAREYoucurnameCURSOR for SELECTA1,a2,a3 fromYoutablenameOPENYoucurnameFetch Next fromYoucurname into @a1,@a2,@a3 while @ @fetch_status<>-1 begin --the action you want to perform is written hereFetch Next fromYoucurname into @a1,@a2,@a3 End CloseYoucurnamedeallocateYoucurname
Together with the exception capture and transaction, the complete process is as follows:
Create PROCEDURE [dbo].[Usp_createpanicbuyingcode]( @OrderNumber VARCHAR( -)) as DECLARE @A1 VARCHAR(Ten),@A2 VARCHAR(Ten),@A3 INT beginTrybegin Tran DECLAREYoucurnameCURSOR for SELECTA1,a2,a3 fromYoutablenameOPENYoucurnameFetch Next fromYoucurname into @a1,@a2,@a3 while @ @fetch_status<>-1begin--the action you want to perform is written hereFetch Next fromYoucurname into @a1,@a2,@a3EndCloseYoucurnamedeallocateYoucurnameCOMMIT TRAN EndTrybeginCatchROLLBACK EndCatch
Common cursor looping usages in SQL Server stored procedures