简体   繁体   English

如何从SQL Server中的表中检索前N行或所有行

[英]How to Retrieve either Top N rows OR all rows from a table in SQL Server

I have a datagridview in which a user is allowed to retriev either n records (using textbox) or All records by clicking on a buttun 我有一个datagridview其中一个允许用户retriev要么n通过点击记录(使用文本框)或所有记录buttun

Now want to retrieve Top N records Or All Records with a single Query. 现在想用单个查询检索Top N记录或所有记录。 right now I'm using 2 different Queries to achieve. 目前,我正在使用2种不同的查询来实现。

//retrieving Top N Records
 SELECT Top @Rows FROM CaseDetails //@Row is parameter 

And

 //retrieving All records
SELECT Top (SELECT COUNT(*) FROM CaseDetails) FROM CaseDetails

How can i Use a single query in SQL Server to perform these 2 options ? 如何在SQL Server使用单个查询来执行这两个选项?

This is a tricky one. 这是一个棘手的问题。

Really you'd probably pass @Rows in all cases, or NULL to select all rows, then null coalesce via ISNULL to select the count from the table to get all rows. 确实,您可能在所有情况下都传递了@Rows ,或者传递NULL来选择所有行,然后通过ISNULL合并null来从表中选择计数以获取所有行。

// Set the Rows param first
SELECT @Rows = ISNULL(@Rows, (SELECT COUNT(*) FROM CaseDetails))

// @Rows is parameter
SELECT TOP @Rows * FROM CaseDetails

I think you better off by creating a procedure like 我认为您最好创建一个类似

create procedure sp_fetch 
@row int = NULL
as
begin
if @row = 0 or @row is null
SELECT * FROM CaseDetails
else
select top @row * from CaseDetails
end

Then you can just call your procedure like 然后,您可以像这样调用程序

exec sp_fetch(10)

You don't need to count all rows before selecting. 选择之前不需要计数所有行。 Assuming @Rows is an int, then you can use the max value of an int as your default. 假设@Rows是一个int,则可以将int的最大值用作默认值。 So, if @Rows is 0 or null, return all rows, otherwise, return @Rows rows: 因此,如果@Rows为0或为null,则返回所有行,否则,返回@Rows行:

SELECT TOP (ISNULL(NULLIF(@Rows,0), 2147483647)) * FROM CaseDetails;

This is working fine 这很好

Declare parameters 声明参数

Create Procedure uspRetrieve
@Rows int =NULL
AS
BEGIN
   SET NOCOUNT ON;

   SET ROWCOUNT @Rows
   SELECT * FROM CaseDetails
End

IF you supply @Row=0 you will get all records else you get @Row =your limit 如果您提供@ Row = 0,则将获得所有记录,否则您将获得@Row =您的限制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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