Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
hello guys, i need help :)

i have a table like this

itemcode itemname icode serialnum
1 A 10 0
2 B 20 0
3 C 11 0
4 D 10 0
5 E 20 0
6 F 10 0
7 G 13 0

i want result like below table using Single Update Query Looping Cursors

itemcode itemname icode serialnum
1 A 10 1
2 B 20 1
3 C 11 1
4 D 10 2
5 E 20 2
6 F 10 3
7 G 13 1

item code is the pimary key in this table.

Please Help me in solving this asap as i am new to Curosrs

Thanks and regards
Harsha
Posted

1 solution

Refer : http://blog.sqlauthority.com/2007/01/01/sql-server-simple-example-of-cursor/[^]

Simple example(This sample taken from above reference)

Selecting Account Id Using CURSOR

SQL
DECLARE @AccountID INT  -- Declaring a variable for holding Account id
DECLARE @getAccountID CURSOR -- Declaring Cureser
--Initializing Cursor 
SET @getAccountID = CURSOR FOR 
SELECT Account_ID
FROM Accounts
--Opening Cursor
OPEN @getAccountID
--Fetching First Value
FETCH NEXT
--Assigning selected value into Variable
FROM @getAccountID INTO @AccountID
--Checking Fetching Status(@@FETCH_STATUS this return the last fetch status
--  0  - The FETCH statement was successful.
-- -1 - The FETCH statement failed or the row was beyond the result set.
-- -2 - The row fetched is missing.)and starting while loop
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @AccountID -- Printing AccountId. Here you can write your code.
--Fetching Next value
FETCH NEXT
FROM @getAccountID INTO @AccountID
END
--Closing Cursor
CLOSE @getAccountID
--Releasing Cursor
DEALLOCATE @getAccountID



Try:

SQL
update Table1  set serialnum = b.row1 from  Table1 as a inner JOIN
 (select itemcode,ROW_NUMBER() OVER(PARTITION BY icode  ORDER BY icode DESC) as row1   from Table1) as b
 on a.itemcode = b.itemcode
 
Share this answer
 
v3
Comments
Harsha Dev 14-Nov-12 3:28am    
ya it is correct kasim but i need in terms of looping Cursor !!! :)
Shanalal Kasim 14-Nov-12 3:36am    
Refer: http://forums.devarticles.com/general-sql-development-47/for-loop-cursor-151552.html
Harsha Dev 14-Nov-12 4:10am    
I have only posted again to get result of table above using looping cursor.
i need a query. :)
Shanalal Kasim 14-Nov-12 4:19am    
Provide more details for 'serialnum'.
The first 3 records serialnum is 1, 4&5 record serialnum is 2 please explain how to calculate this serialnum?
Harsha Dev 14-Nov-12 4:21am    
i want to update this serial number with the help of itemicode and itemcode columns!!!
it should update in one shot using loop cursor :)

Regards
Harsha

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900