-2

我正在尝试使用嵌套 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字段中。我错了吗?我怎样才能解决这个问题?

4

3 回答 3

2

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

VALUES ((SELECT ApplicationID FROM general where Business_Name = "'" & txtName.Text & "'"), ....
于 2012-05-14T06:36:37.007 回答
1

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

改变:

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

到:

(SELECT ApplicationID FROM general where Business_Name = """ & txtName.Text & """)
于 2012-05-14T06:36:10.280 回答
0

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

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

不需要VALUES……

于 2012-05-14T06:45:37.927 回答