如何在参数化插入语句中使用Select语句

时间:2013-10-21 20:37:29

标签: vb.net oledb insert-into sql

我正在尝试此代码,但我收到错误:

Dim cmd3 As OleDbCommand = New OleDbCommand("INSERT INTO Criteria (Calculation, [Interval], Weight) VALUES (?, ?, ?)", Nordeen_Investing_3.con)
    cmd3.Parameters.AddWithValue("@Calculation", Calculation)
    cmd3.Parameters.AddWithValue("@[Interval]", Interval)
    cmd3.Parameters.AddWithValue("@Weight", "(SELECT (Avg(C." & Calculation & " * G.Growth) - Avg(C." & Calculation & ") * Avg(G.Growth)) / (StDevP(C." & Calculation & ") * StDevP(G.Growth)) AS Weight FROM " & Calculation & " AS C INNER JOIN " & Growth_Rate & " AS G " & On_Statement & ")")
    cmd3.ExecuteNonQuery()

这是错误消息:

Data type mismatch in criteria expression.

问题出在这行代码中:

cmd3.Parameters.AddWithValue("@Weight", "(SELECT (Avg(C." & Calculation & " * G.Growth) - Avg(C." & Calculation & ") * Avg(G.Growth)) / (StDevP(C." & Calculation & ") * StDevP(G.Growth)) AS Weight _ FROM " & Calculation & " AS C _ INNER JOIN " & Growth_Rate & " AS G _ " & On_Statement & ")")

如果我将Select Statement替换为Select Statement生成的值,那么代码运行正常。

我怎样才能让它发挥作用?

更新 根据以下建议,我已将代码更改为:

Dim cmd3 As OleDbCommand = New OleDbCommand("INSERT INTO Criteria (Calculation, [Interval], Weight) VALUES (?, ?, (SELECT (Avg(C." & Calculation & " * G.Growth) - Avg(C." & Calculation & ") * Avg(G.Growth)) / (StDevP(C." & Calculation & ") * StDevP(G.Growth)) AS Weight FROM " & Calculation & " AS C INNER JOIN " & Growth_Rate & " AS G " & On_Statement & "))", Nordeen_Investing_3.con)
    cmd3.Parameters.AddWithValue("@Calculation", Calculation)
    cmd3.Parameters.AddWithValue("@[Interval]", Interval)
    cmd3.ExecuteNonQuery()

运行新代码时收到此错误:

Unspecified error

1 个答案:

答案 0 :(得分:1)

您正在尝试通过子查询插入数据,这使您的查询方式不正确

应该是

INSERT INTO table1
SELECT id FROM table2
WHERE ...

在您的特定情况下,OleDBCommand的查询将类似于

"INSERT INTO Criteria (Calculation, [Interval], Weight)
SELECT ?, ?, (Avg(C." & Calculation & " * G.Growth) - Avg(C." & Calculation & ") * Avg(G.Growth)) / (StDevP(C." & Calculation & ") * StDevP(G.Growth)) AS Weight FROM " & Calculation & " AS C INNER JOIN " & Growth_Rate & " AS G " & On_Statement