且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#windows应用程序防止插入重复记录SQL Server

更新时间:2023-01-22 16:52:43

Quote:

违反PRIMARY KEY约束'PK_khaas'。无法在对象'dbo.khaas'中插入重复键。该声明已被终止。

Violation of PRIMARY KEY constraint 'PK_khaas'. Cannot insert duplicate key in object 'dbo.khaas'. The statement has been terminated.



这是 PRIMARY KEY 的原则。

原则上,SQL不允许2条记录共享相同的PRIMARY KEY,因为它是识别每个记录的值,因此必须是唯一的。


That is the principle of PRIMARY KEY.
By principle, SQL do not allow 2 records to share the same PRIMARY KEY as it is the value identifying each records and thus must be unique.

Quote:

如何防止使用C#windows应用程序插入重复记录SQL服务器

How to prevent insert of duplicated records SQL server using C# windows application



您可以在插入新记录之前检查密钥是否存在。

甚至更好,有server为您生成一个唯一的密钥。


You can check if key exist before inserting new record.
Or even better, have the server generate a unique key for you.