【问题标题】:C# SqlCommand syntax for this SQL command此 SQL 命令的 C# SqlCommand 语法
【发布时间】:2016-05-23 03:15:18
【问题描述】:

我正在尝试将此 SQL 示例命令转换为 C#SqlCommand:

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 语句。有什么帮助吗?

【问题讨论】:

  • 我动态添加列,不想在列已经存在时捕获异常

标签: c# sql-server sqlcommand


【解决方案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

【讨论】:

  • 我在 int output=Convert.ToInt32(cmd.ExecuteScalar()); 的 mscorlib.dll 中抛出一个异常:'System.FormatException'行
  • 你在做 select count(*) 吗?
  • 在编辑过程中发现你的代码...测试更新版本
  • 非常感谢您的帮助!我不得不改变这个'"+Healee+"'",openCon);
猜你喜欢
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
  • 2013-03-07
  • 2015-12-13
  • 2013-04-29
  • 1970-01-01
相关资源
最近更新 更多