Monday, March 26, 2012

How can I prevent from inserting duplicate data?

I have a table storing only 2 FKs, let's say PID, MID

Is there any way that I can check distinct data before row is added to this table?

For example, current data is

PID MID
----
100 2001
100 2005
101 3002
102 1009
102 7523
102 2449

If my query is about to insert PID 100, MID 2001, since it's existing data, i don't want to add it. Can I use trigger to solve this issue?

Thanks.

sql server allows you to add an index containing those two columns and set that index as a unique constraint.

this will prevent duplicates.

|||

I would rather do it in a stored proc:

IF NOT EXISTS( SELECT * FROM yourTable WHERE PID = @.PID AND MID = @.MID)

BEGIN

--do the insert

END

No comments:

Post a Comment