C # SQL Top as parameter

Trying to parameterize the TOP value in my sql statement.

SELECT TOP @topparam * from table1 command.Parameters.Add("@topparam",SqlDbType.VarChar, 10).Value = somevalue.ToString(); 

This does not work. Anyone have any suggestions?
To clarify, I do not want to use stored procedures.

+41
sql sql-server tsql
Aug 14 '09 at 0:15
source share
3 answers

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

 SELECT TOP (@topparam) * from table1 
+63
Aug 14 '09 at 0:19
source share

You should 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, try ...

 CREATE PROCEDURE TopNRecords @intTop INTEGER AS SET ROWCOUNT @intTop SELECT * FROM SomeTable SET ROWCOUNT 0 GO 
+8
Aug 14 '09 at 0:20
source share

You can write an inline query:

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

Parse it as an int, and this will prevent an SQL injection attack.

0
Aug 14 '09 at 0:18
source share



All Articles