0

我正在尝试此代码,但出现错误:

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

4

1 回答 1

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 
于 2013-10-21T20:56:36.973 回答