Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect syntax for SELECT TOP with a Parameter

I used to have this one

Dt = MyMod.GetDataTable("SELECT TOP " & QuestionsPerCats(i) & " * From Questions WHERE CategoriesID ='" & Cats(i) & "' ORDER BY NEWID()")

but now i decided to use sqlparameters like

Dim cmd As New SqlCommand("SELECT TOP @QuestionsPerCats * From Questions WHERE CategoriesID = @CategoriesID ORDER BY NEWID()", conn)
Dim sqlParam As SqlParameter = Nothing
sqlParam = cmd.Parameters.Add("@QuestionsPerCats", SqlDbType.SmallInt)
sqlParam.Value = QuestionsPerCats(i)
sqlParam = cmd.Parameters.Add("@CategoriesID", SqlDbType.SmallInt)
sqlParam.Value = Cats(i)

which unfortunately "renders" like

SELECT TOP @QuestionsPerCats * From Questions WHERE CategoriesID = @CategoriesID ORDER BY NEWID()

and returns the following error

Incorrect syntax near '@QuestionsPerCats'.

So what am i doing wrong here?

like image 721
OrElse Avatar asked Oct 20 '25 03:10

OrElse


1 Answers

Try:

SELECT TOP (@QuestionsPerCats) *
FROM Questions
WHERE CategoriesID = @CategoriesID
ORDER BY NEWID()

(SQL Server 2005 and up)

like image 75
Cade Roux Avatar answered Oct 21 '25 17:10

Cade Roux