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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With