Share via

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
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

LiHongMSFT-4306 31,621 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".

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 47,621 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.

    Was this answer helpful?


Your answer

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