简体   繁体   English

更新 SQL 中的主键值

[英]Updating primary key value in SQL

I am creating a form that updates the SQL database with content written in it.我正在创建一个表单,用其中写入的内容更新 SQL 数据库。 ClientCode is a primary key. ClientCode 是一个主键。 My update query is the following:我的更新查询如下:

string query = $@"UPDATE {clientTableName}
                                SET ClientCode = @clientCode,
                                    CompanyName = @companyName,
                                    Address1 = @address1,
                                    Address2 = @address2,
                                    City = @city,
                                    Province = @province,
                                    PostalCode = @postalCode,
                                    YTDSales = @ytdSales,
                                    CreditHold = @creditHold,
                                    Notes = @notes
                                WHERE ClientCode = @clientCode";

Problem with this query is it will select the new clientCode in the where cause, meaning that the query will not be able to select the correct primary key.这个查询的问题是它会在 where 原因中选择新的 clientCode,这意味着查询将无法选择正确的主键。

For example, if I type "BOTTN", the query will look for "BOTTN" instead of "BOTTM" in the where cause.例如,如果我键入“BOTTN”,则查询将在 where 原因中查找“BOTTN”而不是“BOTTM”。

How I can solve this?我该如何解决这个问题?

在此处输入图片说明

You need to differentiate between the old clientCode and the new clientCode.您需要区分旧的 clientCode 和新的 clientCode。 The WHERE clause needs to contain the old clientCode in order to target the existing row in the database. WHERE子句需要包含旧的 clientCode 以定位数据库中的现有行。 Then you can update the row, including the value for the new clientCode.然后您可以更新该行,包括新 clientCode 的值。

string query = $@"UPDATE {clientTableName}
                            SET ClientCode = @newClientCode,     -- NEW
                                CompanyName = @companyName,
                                Address1 = @address1,
                                Address2 = @address2,
                                City = @city,
                                Province = @province,
                                PostalCode = @postalCode,
                                YTDSales = @ytdSales,
                                CreditHold = @creditHold,
                                Notes = @notes
                            WHERE ClientCode = @oldClientCode";  -- OLD

Get the new client code from the text box in your EditDialog and save the old client code as a member variable or something when you retrieve the row from the database in order to display the individual fields in the EditDialog .EditDialog的文本框中获取新的客户端代码,并在从数据库中检索行时将旧的客户端代码保存为成员变量或其他内容,以便在EditDialog显示各个字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM