3

我以前有这个

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'.

那么我在这里做错了什么?

4

3 回答 3

12

尝试:

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

(SQL Server 2005 及更高版本)

于 2011-04-07T18:56:57.923 回答
0

在 () 中包含 @QuestionsPerCats,如此链接中所定义

SELECT TOP (@QuestionsPerCats) * 
From Questions 
WHERE CategoriesID = @CategoriesID ORDER BY NEWID()
于 2011-04-07T18:58:46.177 回答
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)

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

于 2011-04-07T18:59:18.383 回答