开发者

using cursors and displaying row numbers

I have declared the following cursor and have 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 any other way to assign / define a number to each row and display it in the console. I have found the function Row_numbe开发者_如何学运维r() and used it like select ROW_NUMBER() over (order by (select 0)) As Rownumber to do it.

I want to know if it is possible to use the KEYSET in my cursor to do it? How can I do it with KEYSET?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜