具有多个相同值的SQL更新列

时间:2014-01-09 10:02:23

标签: c# sql-server

我尝试了所有我能知道的事情,基本上我有一个客户端表(Sql Server)

表格如下所示

create table Client
(
Name nvarchar(100),(I want to be null)
EmployeesNo nvarchar(50),
CompanyCapital int
)

这个简单的表,我遇到的问题是我想要更新的时候。 问题是我可以在Name中有多个具有相同值的数据,因此如何区分Name中的Values以使它们唯一,Update看起来像:

using(SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Data"].ToString())
{
    if(con.State.ToString() == "Closed")
    {
    con.Open();
    }
    using(SqlCommand com = new SqlCommand("Update Client set Name = @name, EmployeesNo = @emp, CompanyCapital = @com where Name = @name2 (Should I update by some another thing that it will make it unique ???)",con))
    {
    com.Parameters.Add(new SqlParameter("@name2",Mod));(Mod = string I initialized in constructor from another form;)
    com.Parameters.Add(new SqlParameter("@name",textBox1.Text));
    com.Parameters.Add(new SqlParameter("@emp",textBox2.Text));
    com.Parameters.Add(new SqlParameter("@com",textBox3.Text));
    com.ExecuteNonQuery();
    }
}

因此,当我更新或用户更新这些值时,如果我有多个具有相同值的数据,它将覆盖所有这些值,我不想要这样,请记住,值是从文本框插入和更新的。 我试着考虑使用主键,但我怎么知道在哪里更新主键,导致即时通讯使用文本框,我不希望用户输入内容的ID,谢谢。

2 个答案:

答案 0 :(得分:0)

如果您需要唯一识别您的记录,应该使用主键(例如ID)。

为了知道需要更新的记录的ID,只需将表单中的ID存储为隐藏和只读字段。

答案 1 :(得分:0)

Parameters.Add方法的第二个参数,即SqlDbType。不是参数值。

改为使用Parameters.AddWithValue

或将值放在对象初始值设定项中,

com.Parameters.Add(new SqlParameter("@name2", SqlDbType.VarChar) {Value = Mod});
相关问题