How can I prevent duplicate data from being inserted into a SQL Server table?

I have a series of data that needs to be written to SQL, what should I do to check the data in SQL to prevent data from being inserted into the table?

Sample data to insert:

David  
James  
John  

If the fourth data is back John, I want the system to skip the duplicate record (John).

So far I:

SqlConnection myCnn = new SqlConnection(cnn);
String _state = "Insert into CamNo1(platename, date, camID, path, filename) OUTPUT INSERTED.platename values(@msg, getdate(), @camID, @path, @filename)";
SqlCommand _Query = new SqlCommand(_state, myCnn);

_Query.Parameters.AddWithValue("@msg", msg);
_Query.Parameters.AddWithValue("@camID", camID);
_Query.Parameters.AddWithValue("@path", imageFile);
_Query.Parameters.AddWithValue("@filename", name);

try
{
   myCnn.Open();
   string checkname = (string)_Query.ExecuteScalar();
   myCnn.Close();

   getcheckname = checkname;
   Console.WriteLine("OK");
}
catch (Exception)
{
}

I got the string value checkname that was inserted last, what should I check the data for?

+5
source share
3 answers

-, . / . , , , .

, , , , , . MERGE, :

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,...

:

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
+5

, , DB UNIQUE CONSTRAINT

SQL Server 2008 MERGE, . , .

+6

, .

, , , - . :

declare @subject as varchar(100);
set @subject = 'hello'

insert into Subjects ([name]) 
select @subject 
where not exists (select 1 from Subjects where [name] = @Subject)
+2
source

All Articles