Link to home
Start Free TrialLog in
Avatar of Hecatonchires
Hecatonchires

asked on

TOP and Stored Proc parameter

I can select the top 10 rows no problem.
======================================
CREATE PROCEDURE [crmGetTopXActionsForMember]
      @memberno int,
      @brand int
AS
SELECT TOP 10

[snip]

ORDER BY
      dateAdded DESC
GO
======================================
I would like to do this:
======================================
CREATE PROCEDURE [crmGetTopXActionsForMember]
      @memberno int,
      @brand int,
      @X int,
AS
SELECT TOP @X

[snip]

ORDER BY
      dateAdded DESC
GO
======================================
as @X is currently specified in the application as configurable setting.  Unfortunately it throws out at SELECT TOP @X.

Is it possible to use a parameter to specify X in a TOP?

Should I be doing this another way entirely?
Avatar of Anthony Perkins
Anthony Perkins
Flag of United States of America image

Do it this way:

CREATE PROCEDURE [crmGetTopXActionsForMember]
     @memberno int,
     @brand int,
     @X int,
AS

SET ROWCOUNT TO @X
[snip]

ORDER BY
     dateAdded DESC
GO
Avatar of poaysee
poaysee

'SELECT TOP'+ @X +'

[snip]

ORDER BY
     dateAdded DESC'
ASKER CERTIFIED SOLUTION
Avatar of Anthony Perkins
Anthony Perkins
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Declare @sqlSel as varchar(6000)
set @sqlSel =
'SELECT TOP'+ @X +'

[snip]

ORDER BY
     dateAdded DESC'

exec (@sqlSel)
Avatar of Hecatonchires

ASKER

I was a little worried I'd have to set the rowcount back to 0 after that, but works a treat.  Thanks acperkins