Is there a keyword or metainformation in SQL Server that'll tell you if TOP took effect?
EX:
Select TOP 5 * From Stuff
RESULT: 5 rows
What is the best way to determine if there would have been 6 or more?
I could do:
SELECT TOP 6 count(*) FROM Stuff
But I am concerned about a separate call to retrieve the count because there actual query is much more complicated than this one and on a large table.
Thanks!
The SQL SELECT TOP Clause The SELECT TOP clause is used to specify the number of records to return. The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can impact performance. Note: Not all database systems support the SELECT TOP clause.
Example - Using TOP PERCENT keywordSELECT TOP(10) PERCENT employee_id, last_name, first_name FROM employees WHERE last_name = 'Anderson' ORDER BY employee_id; This SQL Server SELECT TOP example would select the first 10% of the records from the full result set.
Limits the rows returned in a query result set to a specified number of rows or percentage of rows in SQL Server. When you use TOP with the ORDER BY clause, the result set is limited to the first N number of ordered rows. Otherwise, TOP returns the first N number of rows in an undefined order.
TOP (100) PERCENT is completely meaningless in recent versions of SQL Server, and it (along with the corresponding ORDER BY, in the case of a view definition or derived table) is ignored by the query processor. You're correct that once upon a time, it could be used as a trick, but even then it wasn't reliable.
There is nothing automatic you can use. You could use something along these lines
DECLARE @N INT = 5;
WITH T
AS (SELECT TOP (@N + 1) *
FROM master..spt_values
ORDER BY number)
SELECT TOP (@N) *,
CASE
WHEN Count(*) OVER () = (@N + 1) THEN 1
ELSE 0
END AS MoreRecords
FROM T
ORDER BY number
Well, you could select the top N+1 (where N in your example is 5, so in your example select the top 6) and discard the last one in your client code, and use the presence of a sixth element to determine if TOP would have had an effect had you used N in the first place. I am not sure there is much value of doing this, however.
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