C# SQL Top as parameter C# SQL Top as parameter sql sql

C# SQL Top as parameter


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

SELECT TOP (@topparam) * from table1


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

DECLARE @iNum INTSET @iNum = 10SELECT TOP (@iNum) TableColumnIDFROM TableName

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

CREATE PROCEDURE TopNRecords@intTop INTEGERASSET ROWCOUNT @intTopSELECT * FROM SomeTableSET ROWCOUNT 0GO


You could write an inline query:

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

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