Stored Procedure With an Optional Parameter Limiting Rows Returned if Specified
-
28-12-2020 - |
質問
How would one go about having a sproc that allows a consumer to optionally specify the number of rows returned?
If no row count is specified, then all rows returned.
解決
The "easiest" way is to parameterize input to TOP. The number I'm using is the maximum value for BIGINT. You'll probably never have more rows than this returned by a query.
USE master
GO
CREATE PROCEDURE dbo.Limiter (@Top BIGINT = 9223372036854775807)
AS
BEGIN
SELECT TOP (@Top) *
FROM sys.databases
END
EXEC dbo.Limiter @Top = 1
EXEC dbo.Limiter
Just be careful, because you can introduce parameter sniffing symptoms here.
If you review the plans for both of these, the TOP operator for both is expecting one row.
Whichever input to top executes first will be cached, unless you recompile, or add an OPTIMIZE FOR hint.
You should also be aware that adding a TOP operator may introduce row goals.
所属していません dba.stackexchange