简体   繁体   中英

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

Now want to retrieve Top N records Or All Records with a single Query. right now I'm using 2 different Queries to achieve.

//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 ?

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.

// 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. So, if @Rows is 0 or null, return all rows, otherwise, return @Rows 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

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