选择TOP N并设置变量,如果可以选择更多

时间:2009-07-27 01:52:11

标签: sql sql-server sql-server-2008

是否有更有效的方法来执行以下SQL?

我想选择前50名的结果,但我也想设置一个变量来告诉我如果没有TOP我会得到更多的结果

DECLARE @MoreExists BIT
SET @MoreExists = 0

DECLARE @Count INT
SELECT @Count = Count(*) 
   FROM MyTable WHERE ... --some expensive where clause

IF @Count > 50
    SET @MoreExists = 1

SELECT TOP 50 Field1, Field2, ... 
    FROM MyTable WHERE ... --same expensive where clause

4 个答案:

答案 0 :(得分:5)

选择51结果,使用客户层中的前50个,并使用计数来了解是否还有更多。

答案 1 :(得分:2)

旋转@Dougs回答

SET NOCOUNT ON 

SELECT TOP 51 Field1, Field2, ... 
    into #t
    FROM MyTable WHERE ... --same expensive where clause

if @@rowcount > 50 
      SET @MoreExists = 1

 SET NOCOUNT OFF

 SELECT TOP 50 Field1, Field2, ... 
    from #t
    -- maintain ordering with an order by clause

答案 2 :(得分:0)

常用方法是使用ROW_NUMBER():

WITH MyTableEntries AS 
( 
    SELECT ROW_NUMBER() OVER (ORDER BY Date DESC) AS Row, col1, col2 
    FROM MyTable
    WHERE
          -- some expensive WHERE clause
)
SELECT col1, col2
FROM MyTableEntries 
WHERE Row BETWEEN(@PageIndex - 1) * @PageSize + 1 and @PageIndex*@PageSize

SqlServercentral article显示的有效方法:

DECLARE @startRow INT ; SET @startrow = 50
;WITH cols
AS
(
    SELECT table_name, column_name, 
        ROW_NUMBER() OVER(ORDER BY table_name, column_name) AS seq, 
        ROW_NUMBER() OVER(ORDER BY table_name DESC, column_name desc) AS totrows
    FROM [INFORMATION_SCHEMA].columns
)
SELECT table_name, column_name, totrows + seq -1 as TotRows
FROM cols
WHERE seq BETWEEN @startRow AND @startRow + 49
ORDERBY seq

答案 3 :(得分:0)

如何在子查询中使用COUNT(*)OVER ...

DECLARE @ReqCount int;
SET @ReqCount = 50;

SELECT TOP (@ReqCount) *
FROM 
(
SELECT *, Count(*) OVER() AS TotalCnt
FROM MyTable WHERE ...
) t
ORDER BY ...
;

如果您也想使用ROW_NUMBER(),请尝试:

SELECT *
FROM 
(
SELECT *, ROW_NUMBER() OVER (ORDER BY ...) AS RowNum, Count(*) OVER() AS TotalCnt
FROM MyTable WHERE ...
) t
WHERE RowNum BETWEEN @StartRange AND @EndRange
ORDER BY ...
;

然后您可以轻松查看TotalCnt> @ReqCount(或@EndRange),以便能够查看是否还有其他内容。

罗布

相关问题