简体   繁体   中英

How to get the current row number in an SQL Server 2000 query?

如何使用不支持ROW_NUMBER()函数的 SQL Server 2000 在 SQL 查询中获取行号?

You can always try to use a temp table with an identity column

DECLARE @table TABLE(
        [id] INT IDENTITY(1,1),
        Val VARCHAR(10)
)

DECLARE @TableFrom TABLE(
        Val VARCHAR(10)
)
INSERT INTO @TableFrom (Val) SELECT 'A'
INSERT INTO @TableFrom (Val) SELECT 'B'
INSERT INTO @TableFrom (Val) SELECT 'C'
INSERT INTO @TableFrom (Val) SELECT 'D'

INSERT INTO @table (Val) SELECT * FROM @TableFrom ORDER BY Val DESC
SELECT * FROM @table

Some of the best paging i have seen in Sql Server 2000 uses this pattern

DECLARE @PageStart INT,
        @PageEnd INT

SELECT  @PageStart = 51,
        @PageEnd = 100

SELECT  <TABLE>.*
FROM    (
            SELECT  TOP (@PageStart - 1)
                    <ID>
            FROM    (
                        SELECT  TOP (@PageEnd)
                                <ID>
                        FROM    TABLE
                        ORDER BY <ID> ASC
                    ) SUB
            ORDER BY SUB.<ID> DESC
        ) SUB INNER JOIN
        <TABLE> ON SUB.<ID> = <TABLE>.<ID>
ORDER BY SUB.<ID>

Another way to create a temp table with an identity to use:

SELECT Field1, Field2, IDENTITY(int, 1,1) AS MyID 
INTO #Temp 
FROM Table1

You can't use Row_Number() in Sql Server 2000 - it was introduced in 2005.

In case you wanted to use Row_Number for paging, here are some ideas on how to perform efficient paging in Sql 2000:

Another way of doing this without using a SQL defined function could be the following:

SELECT 
(SELECT COUNT(1) + 1 FROM YourTable t2 WHERE t2.Id < t.Id) AS RowNumber
FROM YourTable t

It's a bit tricky, but seems simpler that the options that others gave you.

Could you elaborate how the below query will solve the problem?

SELECT ( SELECT SUM(1)

FROM specimen_source_ref

WHERE specimen_source_rcd <= reg.specimen_source_rcd

) AS 'Row Number'

,*

FROM specimen_source_ref reg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM