views:

34

answers:

1

Hi

I have declared the following cursor and used a local variable @RowNo to print the number of each each row.

  declare TheCursor cursor 
  for select productName from products
  declare @RowNo int 
  declare @productName nvarchar(50)
  set @RowNo = 1
  open TheCursor
  fetch next from TheCursor into @productName
  print @RowNo
  print @productName
  set @RowNo = @RowNo+1
  set @productName=''

 while @@FETCH_STATUS=0
    begin
     fetch next from TheCursor into @productName
     print @RowNo
     print @productName
     set @RowNo = @RowNo+1
     set @productName=''
    end
 close TheCursor
 deallocate TheCursor

I am trying to find another ways to specify a number to each row and display it in the consul. I find the function Row_number() and used it like select ROW_NUMBER() over (order by (select 0)) As Rownumber to do it. And now I want to know is it imposible that I use the KEYSET in my cursor to do it? How can I do it with KEYSET?

+2  A: 

I don't completely understand what you're trying to achieve - but you could wrap your select statement including the ROW_NUMBER() function into a CTE (common table expression) and then go from there - no messy cursor needed, that really doesn't scale well:

WITH YourSelection AS
(
   SELECT    
      ProductName,
      ROW_NUMBER() OVER(ORDER BY ProductName) AS 'RowNum'
   FROM dbo.Products
)
SELECT ProductName, RowNum
FROM YourSelection

That should give you the product names, sorted by ProductName, and corresponding row numbers, too.

marc_s
i have read that using keyset after the keyword cursor will assign a nuber to each of the rows and you can use these unique numbers. but i dont kn9ow how to use the keyset
anna
I tried to steer Anna away from a cursor here as well: [solving a problem with cursors](http://stackoverflow.com/questions/3608916/solving-a-problem-with-cursors/3609529#3609529). Not sure if it's the same Anna or not as they appear to be different user IDs, but the questions are quite similar.
Joe Stefanelli
@anna: if you ever can, simply try to **avoid** cursors all together. Try my approach - what do you need to do with this data once you have it??
marc_s