質問

I am trying this code but I am getting an error:

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()

This is the error message:

Data type mismatch in criteria expression.

The problem lies in this line of code:

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 & ")")

If I substitute the Select Statement with the value that the Select Statement produces then the code runs fine.

How can I get this to work?

UPDATE Based upon the suggestion below I have changed my code to this:

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()

I received this error when I ran the new code:

Unspecified error

役に立ちましたか?

解決

You are trying to insert data through a subquery, the way you are making the query is not right

It should be something like

INSERT INTO table1
SELECT id FROM table2
WHERE ...

In your particular case, the query for the OleDBCommand will look like

"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 
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top