Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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", SomeValue)

How can I add a Parameter in this situation?

like image 355
Miguel Avatar asked May 02 '26 09:05

Miguel


1 Answers

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.

like image 120
gbn Avatar answered May 04 '26 22:05

gbn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!