2012-05-14 20 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.

私の唯一の思想は、INTフィールドに全体SELECT文を挿入しようとしているということです。私が間違っている?これをどうすれば解決できますか?

答えて

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

関連する問題