且构网

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

如何防止将重复数据插入SQL Server表中?

更新时间:2022-11-28 13:26:13

首先,您可以通过使用唯一索引或约束来防止表中出现重复项。索引/约束可以按照以下建议协同工作。如果使用唯一索引而不是以下解决方案之一,则插入重复记录将引发错误,并且您将需要在另一端进行处理。

First, you can prevent a duplicate from ever occurring in the table by using a unique index or constraint. An index/constraint can work in concert with the suggestions below. If you only use a unique index and not one of the below solutions, inserting a duplicate record will throw an error and you will need to handle that on the other end.

另外,我可能会通过存储过程插入数据,以检查该行是否已存在。为此,您可以使用 MERGE 语句,如伪代码所示:

Additionally, I would probably insert the data via a stored procedure that checks to see if the row already exists. To do that, you can use either a MERGE statement, as shown in this pseudo code:

create procedure MyProcedure
(
    @Name nvarchar(100),
    ...
)
as

merge MyTable
using
(
    select @Name,...
) as source (Name, ...)
on MyTable.Name = source.Name
when not matched then
    insert (Name,...) values (source.Name,...)
when matched then
    update set Name = @Name,...

或者,您可以检查记录是否存在并手动插入或更新:

or, you could check for the records existence and insert or update manually:

create procedure MyProcedure
(
    @Name nvarchar(100),
    ...
)
as

    if not exists (select * from MyTable where Name = @Name)
    begin
        insert into MyTable (Name,...) values (@Name,...)
    end
    else
    begin
            update MyTable
            set ...
            where Name = @Name
    end