• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

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?
0
Hecatonchires
Asked:
Hecatonchires
  • 2
  • 2
1 Solution
 
Anthony PerkinsCommented:
Do it this way:

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

SET ROWCOUNT TO @X
[snip]

ORDER BY
     dateAdded DESC
GO
0
 
poayseeCommented:
'SELECT TOP'+ @X +'

[snip]

ORDER BY
     dateAdded DESC'
0
 
Anthony PerkinsCommented:
Typo, it should be:

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

SET ROWCOUNT @X
[snip]

ORDER BY
     dateAdded DESC
GO
0
 
poayseeCommented:
Declare @sqlSel as varchar(6000)
set @sqlSel =
'SELECT TOP'+ @X +'

[snip]

ORDER BY
     dateAdded DESC'

exec (@sqlSel)
0
 
HecatonchiresAuthor Commented:
I was a little worried I'd have to set the rowcount back to 0 after that, but works a treat.  Thanks acperkins
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now