2016-05-23 60 views
1

我試圖把這個SQL例如命令轉換爲C#SqlCommandC#的SqlCommand語法SQL命令

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

我至今

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

我完全失去如何編碼if not exists語句。任何幫助?

+0

我動態在飛行中添加列,並且不希望只捕獲異常時,列已經存在 –

回答

1

你需要執行你的第一選擇查詢,以檢查該列是否存在這樣的

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

我我拋出一個異常拋出:'System.FormatException'在mscorlib.dll上的int output = Convert.ToInt32(cmd.ExecuteScalar()); –

+0

你在做select count(*)嗎? – cableload

+0

抓住你的代碼中期編輯...測試更新的版本 –