-First
Declare @orderNum varchar(255)Create Table#ttableName (IDint Identity(1,1), Ordersvarchar(255))Declare @n int,@rows int
Insert#ttableName (Orders)SelectOrdernum fromForderswhereOrderId< ---Select @rows =count (1) from Pe_ordersSelect @rows =@ @rowcount Set @n=1 while @n<=@rows begin Select @orderNum=Ordernum fromPe_orderswhereOrdernum=(SelectOrders from#ttableNamewhereId=@n)Print(@OrderNum)Select @n=@n+1 EndDrop Table#ttableName
-Second
Declare @tmp varchar( -)--temporary variable to hold the cursor valueDeclareY_currcursor for --declare that the cursor is OrdernumSelectOrdernum fromForderswhereOrderId< -OpenY_curr--Open CursorFetch Next fromY_curr into @tmp ----Start loop cursor variable while(@ @fetch_status=0)---Returns the state of the last cursor executed by the FETCH statement, rather than the state of any cursors currently open for the connection. begin Print(@tmp)UpdateFordersSetfunctionary+@tmp whereOrdernum=@tmp --manipulating Databases Fetch Next fromY_curr into @tmp --start loop cursor variable EndCloseY_curr--Close CursorsdeallocateY_curr--Releasing Cursors
--Third
SelectOrdernum,username,moneytotal into#t fromforders PODECLARE @n int,@error int--Set @n=1Set @error=0 BEGIN TRAN --Declaration of Business Declare @tmp varchar( -),@userN varchar( -)--temporary variable to hold the cursor value DeclareY_currcursor for --declare that the cursor is Ordernum,username SelectOrdernum,username fromForderswhereOrderid< - OpenY_currFetch Next fromY_curr into @tmp,@userN while @ @fetch_status = 0 BEGIN Select IsNull(sum(Moneytotal),0), Ordernum from#twhereUsername=@userN --Set @[email protected]+1 Set @error=@error+@ @error--log whether the correct 0 is correct after each run of SQL Fetch Next fromY_curr into @tmp,@userN END IF @error=0 BEGIN Commit Tran --SubmitENDELSE BEGIN ROLLBACK TRAN --rolling back ENDCloseY_currdeallocateY_currDROP TABLE#t
SQL loop statements in several ways (variable loops, cursor loops, transactions)