简体   繁体   English

当我尝试更新表时从数据库中获取错误消息

[英]Getting error message from data base when I try to update the table

I have created a table as below: 我创建了一个表,如下所示:

string fullTableName = string.Format("[dbo].[{0}]", tableName);
string fullKeyName = string.Format("[PK_{0}]", tableName);

string query = string.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14} {15} {16} {17} {18} {19}"
     , "USE [DB_15202_2614d162]"
     , "SET ANSI_NULLS ON"
     , "SET QUOTED_IDENTIFIER ON"
     , "CREATE TABLE ", fullTableName, " ([ClientCode] [nchar](5) NOT NULL, [CompanyName] [nvarchar](40) NOT NULL,"
     , "[Address1] [nvarchar](60) NOT NULL, [Address2] [nvarchar](60) NULL, [City] [nvarchar](20) NULL,"
     , "[Province] [nvarchar](10) NOT NULL, [PostalCode] [nvarchar](10) NULL, [YTDSales] [decimal](18, 2) NOT NULL,"
     , "[CreditHold] [tinyint] NOT NULL, [Notes] [nvarchar](max) NULL,"
     , "CONSTRAINT ", fullKeyName, " PRIMARY KEY CLUSTERED"
     , "([ClientCode] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY])"
     , "ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]"
     , "INSERT INTO ", fullTableName, " ([ClientCode], [CompanyName], [Address1], 
        [Address2], [City], [Province], [PostalCode], [YTDSales], [CreditHold], [Notes])
        VALUES (N'AROUT', N'Around the Horn', N'120 Hanover Sq.', NULL, N'London', N'ON', 
                N'L4N 7G5', CAST(1500.00 AS Decimal(18, 2)), 1, null)"
     , "INSERT INTO ", fullTableName, " ([ClientCode], [CompanyName], [Address1], 
        [Address2], [City], [Province], [PostalCode], [YTDSales], [CreditHold], [Notes])
        VALUES (N'BOTTM', N'Bottom-Dollar Markets', N'23 Tsawassen Blvd.', NULL, 
                N'Tsawassen', N'BC', N'V2R 7A6', CAST(4689.24 AS Decimal(18, 2)), 0, N'Longest standing customer')"
                                   );

            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = query;
                cmd.Connection = conn;

                conn.Open();

                cmd.ExecuteNonQuery();
            }
        }

when I try to update the table from here: 当我尝试从此处更新表时:

public static int UpdateClient(Client client)
    {
        using (SqlConnection conn = new SqlConnection(connString))
        {
            string query = string.Format("{0} {1} {2} {3} {4} {5}{6} {7} {8} {9}"
                          , "UPDATE Client906697"
                          , "SET ClientCode = @clientCode"
                          , "CompanyName = @companyName"
                          , ",Address1 = @address1"
                          , ",Address2 = @address2"
                          , ",City = @city"
                          , ",Province = @province"
                          , ",PostalCode = @postalCode"
                          , ",YTDSales =@ytdSales"
                          , ",CreditHold = @creditHold"
                          , ",Notes = @notes");

            byte creditHold = client.HoldsCredit ? (byte)1 : (byte)0;

            using (SqlCommand cmd= new SqlCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = query;
                cmd.Connection = conn;

                cmd.Parameters.AddWithValue("@clientCode", client.ClientCode);
                //cmd.Parameters.AddWithValue("@companyName", client.CompanyName);
                cmd.Parameters.AddWithValue("@address1", client.Address1);
                if (client.Address2 != null)
                {
                    cmd.Parameters.AddWithValue("@address2", client.Address2);
                }
                else
                {
                    cmd.Parameters.AddWithValue("@address2", DBNull.Value);
                }
                if (client.City != null)
                {
                    cmd.Parameters.AddWithValue("@city", client.City);
                }
                else
                {
                    cmd.Parameters.AddWithValue("@city", DBNull.Value);
                }
                cmd.Parameters.AddWithValue("@province", client.Province);
                cmd.Parameters.AddWithValue("@postalCode", client.PostalCode);
                cmd.Parameters.AddWithValue("@ytdSales", client.YTDSales);
                cmd.Parameters.AddWithValue("@creditHold", creditHold);
                if (client.Notes != null)
                {
                    cmd.Parameters.AddWithValue("@notes", client.Notes);
                }
                else
                {
                    cmd.Parameters.AddWithValue("@notes", DBNull.Value);
                }

                conn.Open();
                int rowsAffected = cmd.ExecuteNonQuery();
                return rowsAffected;


            }
        }
    }

I get duplicate key restraint error and I could not find why. 我收到重复的按键约束错误,但找不到原因。 Can anybody help me please? 有人可以帮我吗?

[ClientCode] is the primary key on your table. [ClientCode]是表上的主键。 Primary key cannot be updated. 主键无法更新。 You have to drop the constraint, update the rows you want and recreate the key again. 您必须删除约束,更新所需的行,然后再次重新创建键。

ClientCode is your primary key, meaning that any given value can only appear once in that column. ClientCode是您的主键,这意味着任何给定值只能在该列中出现一次。

When you do this update 当您执行此更新时

"UPDATE Client906697"
                      , "SET ClientCode = @clientCode"
                      , "CompanyName = @companyName"
                      , ",Address1 = @address1"
                      , ",Address2 = @address2"
                      , ",City = @city"
                      , ",Province = @province"
                      , ",PostalCode = @postalCode"
                      , ",YTDSales =@ytdSales"
                      , ",CreditHold = @creditHold"
                      , ",Notes = @notes");

There is no WHERE clause. 没有WHERE子句。 A WHERE clause determines which rows get updated. WHERE子句确定要更新的行。 If there isn't one then it tries to update every row in the table. 如果没有,则尝试更新表中的每一行。 So whatever the value of @clientCode is, you're trying to update every row in the table to have that value for ClientCode . 因此,无论@clientCode的值是@clientCode ,您都在尝试更新表中的每一行以使ClientCode具有该值。 If there's more than one record in the table then that's guaranteed to throw a duplicate key exception because multiple rows can't have the same ClientCode . 如果表中有多个记录,那么可以保证抛出重复的键异常,因为多行不能具有相同的ClientCode (And I'm sure that's not what you meant to do. ClientCode is your primary key so you probably don't want to change that anyway.) (而且我敢肯定这不是您的本意ClientCode是您的主键,因此您可能始终不想更改它。)

I think what you mean to do is this (sorry, I'm not going to try to put this in your string.Format , but you get the picture.) 我认为您的意思是这样做(对不起,我不会尝试将其放在您的string.Format ,但是您会得到图片。)

UPDATE Client906697"
    SET CompanyName = @companyName,
    Address1 = @address1,

    -- ETC

 WHERE ClientCode = @ClientCode

Now you're not changing the value of ClientCode , and you're only updating one row, the one that has the matching ClientCode . 现在,您无需更改ClientCode的值,而只需更新一行,即具有匹配的ClientCode

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

相关问题 当我尝试从 .NET 中的 SAP 访问数据时,我收到错误消息“无法识别的消息版本”。 - When I try to access data from SAP in .NET I get an error 'Unrecognized message version.' 尝试更新用户时收到无效的电子邮件错误? - Getting invalid email error when I try to update a user? 当我尝试 Output 时出现错误 从下拉列表中选择了什么 - Getting an Error When I Try To Output What Was Chosen From a Dropdown 当我尝试播放特定动画剪辑时收到错误消息 - I am getting an Error Message when i try to play a specific Animation Clip 我尝试执行Web应用程序时收到此错误消息 - i am getting this error message when i try to execute my web application 当我尝试使用visual c#连接SQL Server时收到此错误消息 - I am getting this error message when I try to connect SQL Server using visual c# 尝试更新访问数据库中的记录时出现错误 - I am getting an error when I try to update records in my access database 尝试从 gridview 更新时出现死锁错误 - deadlock error when try to update from gridview 使用SQLBulkCopy将数据插入到Azure SQL数据库表中时,出现错误消息“等待操作超时”? - When inserting data using SQLBulkCopy into an Azure SQL Database table I am getting an error message “The wait operation timed out”? 数据表添加数据行时出现错误[] - Data Table Getting error when i add data rows[]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM