Search code examples
asp.netsqlvb.netsql-server-2005sqlparameter

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?


Solution

  • Try:

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

    (SQL Server 2005 and up)