SELECT TOP与参数的语法不正确

时间:2011-04-07 18:53:39

标签: asp.net sql vb.net sql-server-2005 sqlparameters

我曾经有过这个

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

但现在我决定使用像

这样的sqlparameters
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)

,不幸的是“呈现”像

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

并返回以下错误

Incorrect syntax near '@QuestionsPerCats'.

那我在这里做错了什么?

3 个答案:

答案 0 :(得分:11)

尝试:

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

(SQL Server 2005 and up)

答案 1 :(得分:0)

在({3}}链接

中定义的()中包含@QuestionsPerCats
SELECT TOP (@QuestionsPerCats) * 
From Questions 
WHERE CategoriesID = @CategoriesID ORDER BY NEWID()

答案 2 :(得分:0)

尝试将其更改为:

cmd.Parameters.Add("@QuestionsPerCats", SqlDbType.SmallInt)
cmd.Parameters("@QuestionsPerCats").Value = QuestionsPerCats(i)


cmd.Parameters.Add("@CategoriesID", SqlDbType.SmallInt)
cmd.Parameters("@CategoriesID").Value = Cats(i)

用于向命令添加参数的方法有点奇怪。我怀疑这可能是你错误的原因。