我曾经有过这个

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

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

最佳答案

尝试:

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

(SQL Server 2005 and up)

关于asp.net - 带参数的 SELECT TOP 语法不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5586081/

10-11 12:03