2012-05-14 144 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需要....

相关问题