57

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.

3 Answers 3

91

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

SELECT TOP (@topparam) * from table1
Sign up to request clarification or add additional context in comments.

3 Comments

This led me to my answer. I was passing value in as varchar, switching to int fixed it. Thanks all.
Is there a way to set @topparam to a value that means that it ignores the TOP and returns all rows?
@SimonGreen That is not possible in MS SQL, since it defeats the purpose of using TOP. You can write this c# code: var topParam = topArg != null ? "TOP(@topparam)" : ""; var qry = $"SELECT {topParam}..."
10

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

Comments

0

You could write an inline query:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.