2016-05-23 13 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

抓住你的代码中期编辑...测试更新的版本 –