Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 can this be done without a cursor?

Author  Topic 

elic05
Yak Posting Veteran

62 Posts

Posted - 2011-11-22 : 07:34:00
I wrote a proc that selects only 5 items for each category
can it be done without a cursor?




CREATE PROC GetPictures
AS
BEGIN
DECLARE @CategoryCode int;
declare @PostsDetails PostsDetails;
declare categoryCursor CURSOR FOR
SELECT Id FROM Category
OPEN categoryCursor
FETCH NEXT FROM categoryCursor
INTO @CategoryCode;
WHILE @@FETCH_STATUS = 0
BEGIN
insert into @PostsDetails
SELECT top(5) *
FROM Post
WHERE CategoryId=@CategoryCode
order by VoteUntill desc
FETCH NEXT FROM categoryCursor
into @CategoryCode
END
close categoryCursor
DEALLOCATE categoryCursor
select * from @PostsDetails
END
RETURN


nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2011-11-22 : 07:37:24
insert @PostsDetails (...)
select ...
from (
select *, seq = row_number() over (partition by CategoryId order by VoteUntill desc)
) a
where seq <= 5


==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

elic05
Yak Posting Veteran

62 Posts

Posted - 2011-11-22 : 13:10:23
nigelrivett
thanks
I didnt know about row_number()....
your stalement "Cursors are useful if you don't know sql."
seems correct...
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-11-22 : 23:48:02
quote:
Originally posted by elic05

nigelrivett
thanks
I didnt know about row_number()....
your stalement "Cursors are useful if you don't know sql."
seems correct...


see what all you can do with row_number

http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/multipurpose-row-number-function.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -