سؤال

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى dba.stackexchange
scroll top