Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a T-SQL conditional TOP clause possible?

Tags:

tsql

I want to dynamically use TOP or not sort of like this...

SELECT @SomeNumber CASE WHERE 0 THEN TOP 5 COLUMNNAME
                        ELSE COLUMNNAME
                   END
FROM TABLE
like image 739
apolfj Avatar asked Jun 24 '10 07:06

apolfj


People also ask

What is an alternative for top clause in SQL?

ROW_NUMBER function helps to give temporary numbers to the result set of the query and it can be also used instead of the TOP clauses. For example, the following query will return the first 4 rows of the Product table.

Which clause should be used with top?

We can use TOP Clause in a SQL delete statement as well. We should use the ORDER BY clause in the delete statement to avoid unnecessary deletion of data. In the above query, we want to retrieve the top 10 customers' records in [orderdate] ascending order.

How do you select top 10 values in SQL?

Example - Using TOP PERCENT keywordSELECT TOP(10) PERCENT contact_id, last_name, first_name FROM contacts WHERE last_name = 'Anderson' ORDER BY contact_id; This SQL SELECT TOP example would select the first 10% of the records from the full result set.

How do you keep records on top when ordering data?

Answer: In Order by clause you can use a number which will indicate the ordinal position of the column name used in the select statement. For example Order by 2 means order by the second column values specified in the SELECT statement.


1 Answers

I hope to have understood your problem: you want to select the TOP 5 rows if you pass @SomeNumber = 0 else select all th etable rows

As a first straight implementation you can do something like that

declare @SomeNumber as int

set @SomeNumber = 5
-- set @SomeNumber = 1

SELECT TOP (SELECT @SomeNumber) COLUMNNAME FROM MYTABLE

you can change the parameter value in order to have how many rows you want


Otherwise i suggest you to implement a stored procedure (and maybe you already did that, otherwise you can follow the next steps in order to do it)

CREATE procedure [dbo].[TOPCLAUSE]

    -- clause parameter
    @SomeNumber as integer

AS

IF @SomeNumber = 0 
BEGIN
    SELECT TOP 5 COLUMNNAME FROM MYTABLE
END
ELSE
BEGIN
    SELECT COLUMNNAME FROM MYTABLE
END

GO

Then you can call

exec [dbo].[TOPCLAUSE] 0

exec [dbo].[TOPCLAUSE] 1

I probably not answered your question but let me know if it helped you

like image 105
Marcello Faga Avatar answered Oct 11 '22 12:10

Marcello Faga