Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using variables with TOP 1

Status
Not open for further replies.

DomTrix

Programmer
Dec 28, 2004
94
GB
Hello there,

I am writing a stored procedure that is a simple select query. I want the calling code to supply a maximum number of rows to be returned but I cannot get the code to work using this parameter. Here is my code:

Code:
CREATE PROCEDURE dbo.selFeaturedItems
@maxItems	int

 AS

SELECT TOP @maxItems
		pro_ID,
		pro_Title,
		pro_Text
FROM product

...
...
RETURN

When i check syntax, I get error 170, incorrect syntax on the line that contains 'SELECT TOP @maxItems'. If I replace @maxItems with a literal value the code checks out fine.

Could anyone show me my mistake?

Thanks in advance

DT

 
In SQL 2000 TOP doesnt take a variable as a parameter, this has changed in SQL 2005.

So, you could try this alternate solution:

Code:
CREATE PROCEDURE dbo.selFeaturedItems
@maxItems    int

 AS
SET ROWCOUNT @maxItems 
SELECT 
        pro_ID,
        pro_Title,
        pro_Text
FROM product

...
...

SET ROWCOUNT 0
RETURN

Sunil
 
Great, thanks for the lightning reply :)

I suspected as much but had no idea of an alternative.

dt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top