Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

c# - How can I prevent inserting duplicate data into a SQL Server table?

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

Example data to be inserted:

David  
James  
John  

If the 4th data is John again, I want the system to skip the duplicate record (John).

So far I have:

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 is last inserted, what should i do check the data?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you do not want duplicate data, you should consider enforcing that at the DB level with a UNIQUE CONSTRAINT or a UNIQUE INDEX

SQL Server 2008 also has a MERGE statement you could use to check for matched records. This could be helpful if you want to update an existing record.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...