Groups | Blog | Home
all groups > sql server mseq > december 2004 >

sql server mseq : Running counter



MichaelK
12/27/2004 1:37:05 PM
Is it possible to make a query to have a counter which would have
a sequential number of each record in the query starting with 1?

Thanks,
Michael

MichaelK
12/27/2004 4:08:54 PM
Thanks Hugo.
Interesting idea and works, but takes very long.
Unfortunately can't use it, need something faster.

Hey guys any other ideas?

Regards,
Michael

[quoted text, click to view]

Derrick Leggett
12/27/2004 7:04:34 PM
Insert the records into a table variable or temp table (if more than 10k
records) that includes an identity column. The query selects the final
resultset. How big of a recordset are you talking about here? Why do you
need to do this?


[quoted text, click to view]

Hugo Kornelis
12/28/2004 12:27:35 AM
[quoted text, click to view]

Hi Michael,

That depends. Relational databases handle sets, which are UNordered by
definition, so there is no such thing as an intrinsic "row number". But if
you can define something to base the numbering on, you can have SQL Server
add the numbers.

As an example, the following query will list all authors with a ranking
based on alphabetic order of last name (note how the tie for Albert Ringer
and Ann Ringer is handled!):

USE pubs
GO
SELECT au_id, au_lname, au_fname,
(SELECT 1 + COUNT(*)
FROM authors AS b
WHERE b.au_lname < a.au_lname) AS rank
FROM authors AS a
ORDER BY rank
GO

Best, Hugo
--

Hugo Kornelis
12/28/2004 10:05:40 AM
[quoted text, click to view]

Hi Michael,

Here's another way to write the same query, that might perform quicker
(you'll need to test it on your end to see if it's better for you):

SELECT a.au_id, a.au_lname, a.au_fname,
1 + COUNT(*) AS rank
FROM authors AS a
INNER JOIN authors AS b
ON b.au_lname < a.au_lname
GROUP BY a.au_id, a.au_lname, a.au_fname
ORDER BY rank

Another important thing to consider is that the column you use to base the
ranking on should be indexed. A nonclustered index on only that column
would be best for this query. (Of course, the final choice of indexes
should be based on ALL queries, plus the impact of more indexes on insert,
update and delete performance).


Derrick's suggestion might be useful as well. Probably faster than any
truly relational approach. But you should be aware that multi-row inserts
can be handled in any order - even if you write INSERT INTO ... SELECT ...
ORDER BY ..., SQL Server is still free to choose another ordering when
inserting the rows.
Usually, the rows WILL be inserted (and given identity values) in the
order you specify, but this behaviour is NOT guaranteed.


You'll find more useful ideas on this subject in Aaron's article, which is
here: http://www.aspfaq.com/show.asp?id=2427. Be sure to also follow the
links near the end of this article.

Best, Hugo
--

AddThis Social Bookmark Button