tags:

views:

172

answers:

3

Trying to parameterize the value of TOP in my sql statement.

SELECT TOP @topparam * from table1

command.Parameters.Add("@topparam",SqlDbType.VarChar, 10).Value = somevalue.ToString();

This doesn't seem to work. Anyone have any suggestions?
Just to clarify, I don't want to use stored procedures.

A: 

You could write an inline query:

EXEC 'SELECT TOP ' + @topparam + ' * FROM ... '

Parse it as an int and that will prevent a SQL injection attack.

Russell
+6  A: 

In SQL Server 2005 and above, you can do this:

SELECT TOP (@topparam) * from table1
Cade Roux
This led me to my answer. I was passing value in as varchar, switching to int fixed it. Thanks all.
muhan
+3  A: 

You need to have at least SQL Server 2005. This code works fine in 2005/8 for example ...

DECLARE @iNum INT
SET @iNum = 10
SELECT TOP (@iNum) TableColumnID
FROM TableName

If you have SQL Server 2000, give this a try ...

CREATE PROCEDURE TopNRecords
@intTop INTEGER
AS
SET ROWCOUNT @intTop

SELECT * FROM SomeTable

SET ROWCOUNT 0
GO
JP Alioto