开发者

How to use SQL Parameter in this situation

My query is this: "SELECT TOP 5 * FROM [TableName] ORDER By NEWID()"

But I want to use a SQL Parameter so it could be something like this: "SELECT TOP @ParameterName * FROM [TableName] ORDER By NEWID()"

The normal way dosen't work:

Ct.Command.CommandText = "SELECT TOP @ParameterName * FROM [TableName] ORDER By NEWID()"
Ct.Command.Parameters.AddWithValue("@ParameterName", Some开发者_高级运维Value)

How can I add a Parameter in this situation?


Simply put parenthesis around the parameter. Supported since SQL Server 2005

Ct.Command.CommandText = "SELECT TOP (@ParameterName) * FROM [TableName] ORDER By NEWID()"

Note: TOP without parenthesis is for backwards compatibility; they should always be used

For backward compatibility, TOP expression without parentheses in SELECT statements is supported, but we do not recommend this.


Is it necessary to use the parameter this way? May be you will do something like this:

Ct.Command.CommandText = string.Format("SELECT TOP {0} * FROM [TableName] ORDER By NEWID()", 5);


Using dynamic T-SQL

EXEC('SELECT TOP ' + CAST(@ParameterName AS VARCHAR(5)) + ' * FROM [TableName] ORDER By NEWID()')


You have to create dynamic SQL here.

Ct.Command.CommandText = 
    String.Format("SELECT TOP {0} * FROM [TableName] ORDER By NEWID()",SomeValue)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜