将varchar值转换为int类型时转换失败

时间:2012-05-14 06:31:19

标签: sql visual-studio-2010

我正在尝试使用嵌套SELECT语句的INSERT语句。这两个数据库字段都是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:转换时转换失败   varchar值'(SELECT ApplicationID FROM general where   Business_Name =“a”)'到数据类型int。

我唯一想到的是它试图将整个SELECT语句插入INT字段。我错了吗?我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

因为您引用单引号来引用查询,所以它被视为字符串。您应该删除查询的单引号

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

答案 1 :(得分:1)

只需删除查询周围的撇号。

变化:

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

为:

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

答案 2 :(得分:0)

另外:如果您想根据另一个表中的SELECT将数据插入到表中,则需要使用VALUES关键字,而是使用此式:

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

不需要VALUES ....