2016-05-23 18 views
1

Ich versuche, diese SQL-Beispiel-Befehl in eine C# SqlCommand zu drehen:C# SqlCommand Syntax für diesen SQL-Befehl

if not exists (select column_name 
       from INFORMATION_SCHEMA.columns 
       where table_name = 'TotalHeals' 
       and column_name = '"+Healee+"') 
    alter table TotalHeals add +Healee+ int 

Was ich bisher

// TO DO check to see if column exists instead of throwing error 
cmd2 = new SqlCommand("ALTER TABLE TotalHeals ADD " + Healee + " INT",openCon); 
cmd2.ExecuteNonQuery(); 

Ich bin völlig verloren haben, wie man code die if not exists-Anweisung. Irgendeine Hilfe?

+0

existieren zu überprüfen bin dynamisch Spalten on the fly hinzufügen und wollen nicht nur die Ausnahme fangen, wenn die Spalte bereits –

Antwort

1

Sie benötigen eine erste Auswahlabfrage auszuführen, ob die Spalte wie diese I

cmd = new SqlCommand("Select count(*) from 
        INFORMATION_SCHEMA.columns 
        where 
        table_name = 'TotalHeals' 
        and column_name = '"+Healee+"',openCon); 
int output=Convert.ToInt32(cmd.ExecuteScalar()); 

if (output>0) 
// column already present....handle that case.. 
else 
//alter your table to add the column 
+0

I existiert Ich werfe eine Exception geworfen: 'System.FormatException' in mscorlib.dll auf dem int output = Convert.ToInt32 (cmd.ExecuteScalar()); Linie –

+0

machst du Auswahl zählen (*)? – cableload

+0

Fangen Sie Ihren Code Mitte bearbeiten ... Testen der aktualisierten Version –