Friday, March 9, 2012

How to return a row counter?

Is it possible to return a row counter in a single select statement?
For example, I want to return Col1 and Col2 in TableA, but I need a counter
to identify the returned row's positioning.
RowCount ColA ColB
1 A B
2 C D
3 E F
I'd like to do it in a single select statement. If I have to declare a
variable and do a while statement, I could do it but it would be very
process-intensive.
Thanks!> Is it possible to return a row counter in a single select statement?
Sort of. But you really, really, really should consider appending this at
the presentation layer, which has to loop through all rows anyway. Doing
this at the database level forces SQL Server to inspect the entire set for
every row, and this will definitely have high potential to cause you some
performance issues.
http://www.aspfaq.com/2427|||Thanks, Aaron. I'll look into those options.
Do you know if Microsoft is planning on implementing this logic as a
function in the future?
"Aaron Bertrand [SQL Server MVP]" wrote:

> Sort of. But you really, really, really should consider appending this at
> the presentation layer, which has to loop through all rows anyway. Doing
> this at the database level forces SQL Server to inspect the entire set for
> every row, and this will definitely have high potential to cause you some
> performance issues.
> http://www.aspfaq.com/2427
>
>|||> Do you know if Microsoft is planning on implementing this logic as a
> function in the future?
Yes, SQL Server added ROW_NUMBER() and other ranking functions in SQL Server
2005.
http://msdn2.microsoft.com/en-us/library/ms186734

No comments:

Post a Comment