gpt4 book ai didi

sql-server - 违反 PRIMARY KEY 约束。无法在对象中插入重复的键

转载 作者:行者123 更新时间:2023-12-02 10:52:57 25 4
gpt4 key购买 nike

我继承了一个项目,但遇到了 SQL 错误,我不确定如何修复。

在电子商务网站上,代码将订单发货信息插入到另一个数据库表中。

以下是将信息插入表中的代码:

string sql = "INSERT INTO AC_Shipping_Addresses   
(pk_OrderID, FullName, Company, Address1, Address2, City, Province, PostalCode, CountryCode, Phone, Email, ShipMethod, Charge_Freight, Charge_Subtotal)
VALUES (" + _Order.OrderNumber;
sql += ", '" + _Order.Shipments[0].ShipToFullName.Replace("'", "''") + "'";
if (_Order.Shipments[0].ShipToCompany == "")
{
sql += ", '" + _Order.Shipments[0].ShipToFullName.Replace("'", "''") + "'";
}
else
{
sql += ", '" + _Order.Shipments[0].ShipToCompany.Replace("'", "''") + "'";
}
sql += ", '" + _Order.Shipments[0].Address.Address1.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Address2.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.City.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Province.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.PostalCode.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Country.Name.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Phone.Replace("'", "''") + "'";
if (_Order.Shipments[0].ShipToEmail == "")
{
sql += ",'" + _Order.BillToEmail.Replace("'", "''") + "'";
}
else
{
sql += ",'" + _Order.Shipments[0].ShipToEmail.Replace("'", "''") + "'";
}
sql += ", '" + _Order.Shipments[0].ShipMethod.Name.Replace("'", "''") + "'";
sql += ", " + shippingAmount;
sql += ", " + _Order.ProductSubtotal.ToString() + ")";
bll.dbUpdate(sql);

它工作正常,但也输出以下 SQL 错误:

Violation of PRIMARY KEY constraint 'PK_AC_Shipping_Addresses'. Cannot insertduplicate key in object 'dbo.AC_Shipping_Addresses'. The duplicate key valueis (165863).

从阅读类似的问题来看,我似乎应该在声明中声明ID。

这是正确的吗?我该如何调整代码来解决这个问题?

最佳答案

当我尝试使用 EntityFramework 插入新记录时,我在恢复的数据库上遇到了相同的错误。事实证明,身份/种子把事情搞砸了。

使用重新设定种子命令修复了该问题。

DBCC CHECKIDENT ('[Prices]', RESEED, 4747030);GO

关于sql-server - 违反 PRIMARY KEY 约束。无法在对象中插入重复的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36043439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com