我需要从表中获取最少n个值的总和
Dim lot As String = "SELECT SUM(x2) AS x3 FROM (SELECT TOP '" & _TextBox2.Text & "' x1 As x2
FROM (
SELECT SharePrice As x1
FROM Shares
WHERE(Company = '" & _TextBox1.Text & "' AND Availability = True)
ORDER BY SharePrice ASC )
)"
我没有其他问题,除了TOP'" &安培; _TextBox2.Text& "'部分 SELECT TOP真的需要参数吗?
我可以用硬编码的整数替换文本框引用,它可以工作。但我想让它在用户输入的Visual Basic中运行
答案 0 :(得分:3)
您不能在查询的TOP n部分中的数字周围使用单引号。
变化:
SELECT TOP '" & _TextBox2.Text & "'
要:
SELECT TOP " & _TextBox2.Text & "
我还建议您使用参数化查询来帮助阻止SQL Injection。
答案 1 :(得分:0)
作为参数化查询,这样做要容易得多。除了防止sql注入攻击之外,它还避免了何时在引物周围放置引号的问题。
为了让Top能够工作,你需要用parens
包围参数名称Dim lot As String = " SELECT SUM(x2) AS x3
FROM
(SELECT TOP (@Top) x1 As x2
FROM (SELECT
SharePrice As x1
FROM Shares
WHERE
(Company = @CompanyName
AND Availability = True)
ORDER BY SharePrice ASC ))"
Dim cmd as SqlCommand = new SqlCommand (connection, lot)
cmd.AddWithValue (@Top, Int32.Parse(_TextBox2.Text))
cmd.AddWithValue (@CompanyName, _TextBox1.Text)