2012-05-14 145 views
-2

我正在嘗試使用嵌套SELECT語句的INSERT語句。這兩個數據庫字段都是int類型。將varchar值轉換爲int類型時轉換失敗

我的發言:

energy_command = New SqlCommand("INSERT INTO energy ([ApplicationID], [usage], [policy], [audit], [lighting], [over_lighting], [controls], [turn_off], [energy_star], [weatherize],[thermostat], [natural_light], [air], [renewable_assessment], [on_site_renewable], [HVAC],[renewable_power], [efficient_enroll], [efficient_attain], [other]) " & 
"VALUES ('(SELECT ApplicationID FROM general where Business_Name = """ & txtName.Text & """)', '" & track_usage & "', '" & develop_strategy & "', '" & perform_audit & "', '" & replace_bulbs & "', '" & reduce_lighting & "', '" & lighting_controls & "', '" & not_in_use_policy & "', '" & energy_star & "', '" & weatherize & "', '" & program_thermo & "', '" & natural_light & "', '" & air_quality & "', '" & site_assessment & "', '" & renewable_power & "', '" & HVAC & "', '" & renewable_energy & "', '" & energy_programs & "', '" & energy_certification & "', '" & energy_other & "')", connection)` 

我的錯誤:

System.Data.SqlClient.SqlException: Conversion failed when converting the varchar value '(SELECT ApplicationID FROM general where Business_Name = "a")' to data type int.

我唯一的想法是,它試圖插入整個SELECT語句轉換成INT領域。我錯了嗎?我怎樣才能解決這個問題?

回答

2

因爲你把一個單引號引用查詢,所以它被認爲是一個字符串。您應該刪除您的查詢的單引號只是這

VALUES ((SELECT ApplicationID FROM general where Business_Name = "'" & txtName.Text & "'"), .... 
1

只需刪除查詢周圍的撇號。

變化:

'(SELECT ApplicationID FROM general where Business_Name = """ & txtName.Text & """)' 

到:

(SELECT ApplicationID FROM general where Business_Name = """ & txtName.Text & """) 
0

另外:如果你想將數據插入到基於從另一個表SELECT一個表,你需要使用VALUES關鍵字,而是使用這種樣式:

INSERT INTO dbo.YourTargetTable(Co1, Col2, ..., ColN) 
    SELECT 
     Src1, Src2, ...., SrcN 
    FROM 
     dbo.YourSourceTableHere 
    WHERE 
     YourConditionHere 

沒有VALUES需要....

相關問題