【问题标题】:update table sql server fields maybe empty更新表 sql 服务器字段可能为空
【发布时间】:2011-12-27 14:45:27
【问题描述】:

我想在我的 asp.net 应用程序中更新一个数据库。更新的字段在文本框中设置。

SqlCommand cmd = new SqlCommand();
cmd.Connection = con;

cmd.ExecuteNonQuery();
cmd.CommandText = "update dbo.User_Info SET FirstName=@FirstName, LastName=@LastName,Degree=@Degree,Organization=@Organization,Phone=@Phone,Ext=@Ext where UserName =@username";
cmd.Parameters.Add("FirstName", SqlDbType.VarChar).Value = TextFirstName.Text;
 cmd.Parameters.Add("LastName", SqlDbType.VarChar).Value = TextLastName.Text;
 cmd.Parameters.Add("Degree", SqlDbType.VarChar).Value = TextDegree.Text;
 cmd.Parameters.Add("Organization", SqlDbType.VarChar).Value = TextOrg.Text;
 cmd.Parameters.Add("Phone", SqlDbType.VarChar).Value = TextPhone.Text;
 cmd.Parameters.Add("Ext", SqlDbType.VarChar).Value = TextExt.Text;

但是,也许有些字段我根本不想更新它们。把它们留空,那么如何修改代码呢? 例如,假设我只想更新 FirstName,命令应该是

cmd.CommandText = "update dbo.User_Info SET FirstName=@FirstName where UserName =@username";

但是另一个人只想更新“Degree”,因此命令将是:

cmd.CommandText = "update dbo.User_Info SET Degree=@Degree where UserName =@username";

是否有考虑各种场景的通用命令?

【问题讨论】:

    标签: c# asp.net sql-server tsql


    【解决方案1】:

    通用?我对此表示怀疑。一些选项:

    通过动态添加字段,根据输入自定义您的 UPDATE 语句:

    string sql = "update dbo.User_Info SET ";
    if (TextFirstName.Text != null)
    {
        sql += "FirstName=@FirstName, ";
        cmd.Parameters.Add("FirstName", SqlDbType.VarChar).Value = TextFirstName.Text;
    }
    // etc.
    

    更改您的 SQL 语句以检查 NULL 参数,如果它们为 NULL,则保留初始值:

    // If @FirstName is NULL, "update" with the original value
    cmd.CommandText = "update dbo.User_Info SET FirstName=COALESCE(@FirstName, FirstName)," 
    // etc. 
    

    【讨论】:

      【解决方案2】:

      您需要根据控件的内容构建更新查询吗?您可以迭代它们并仅在它们不为空时才使用它们,如下所示(粗略示例如下):

      string query = "UPDATE User_Info SET ";
      foreach (Control ctl in panel.Controls)
      {
          if (ctl.Type == "Textbox")
          {
              query += ctl.Tag + " = " + "@" + ctl.Tag //assuming you preload the table names on the tags of the controls and you wanna name the parameters like that
              cmd.Parameters.AddWithValue("@" + ctl.Tag, ctl.Text);
              query += ", "
          }
       }
       //You need here something to eliminate the last comma
       query += "WHERE UserName =@username"
       cmd.Parameters.AddWithValue("@username", _usrName);
      

      类似的东西可以工作。当然,您可以始终使用 switch 语句来代替迭代。

      【讨论】:

      • Control 没有 Type 属性。你可以做typeof(TextBox).Equals(ctl.GetType())
      • 看起来不错,是否还有其他与查询无关的文本框?我如何区分它们?
      • 不要设置他们的标签。它又快又脏(更不用说很难维护了),但它确实有效。还有,犬夜叉所说的。
      猜你喜欢
      • 2021-11-11
      • 2021-08-18
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 2016-01-19
      • 2018-04-07
      • 1970-01-01
      相关资源
      最近更新 更多