C# SQL Top as parameter

2019-01-25 01:07发布

问题:

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.

回答1:

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

SELECT TOP (@topparam) * from table1


回答2:

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


回答3:

You could write an inline query:

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

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