How to avoid multiple data in SQL table

BeUnique 2,332 Reputation points
2024-11-08T10:18:11.5733333+00:00

I am developing Web application and i used SQL server for database storing (backend).

In every form will have submit button and record will be stored into database.

sometimes, end user clicking "Submit" button at multiple times.

so, many duplicate entry will be occupying in a table.

To avoid this, i am using IF NOT EXISTS statement.

Will the below query work to avoid duplicate entry even if clicks multiple times "Submit" button.

BEGIN
   IF NOT EXISTS (SELECT * FROM Employee 
                   WHERE ENo = @ENo
                   AND JoinNo = @JoinNo
                   AND JoinDate = JoinDate)
   BEGIN
       INSERT INTO EmailsRecebidos (ENo, JoinNo, JoinDate,DOB,Address)
       VALUES (@ENo, @JoinNo, @JoinDate,@DOB,@Address)
   END
END
SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. LiHongMSFT-4306 31,566 Reputation points
    2024-11-11T07:58:28.0766667+00:00

    Hi @BeUnique

    Not sure why you check data exists from table Employee, while insert into another table EmailsRecebidos.

    To avoid duplicate, shouldn't the logic be both the same table?

    IF NOT EXISTS 
    (SELECT * FROM YourTable WHERE column1 = @value1 AND column2 = @value2)
    BEGIN
      INSERT INTO YourTable (column1, column2) VALUES (@value1, @value2);
    END
    

    Best regards,

    Cosmog


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 47,436 Reputation points
    2024-11-08T10:45:10.6133333+00:00

    When the 3 columns in the WHERE clause are the primary key for the table, then yes, it will work.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.