Mr A
Mr A

Reputation: 6768

Check for duplicates in the table before inserting data into SQL Server with ASP.NET

I have got 3 columns in the table, I need to check the email field before insertion of new row, so if the email exist, it should not insert that row. Do I have to go through 2 queries to achieve that, so for instance first check :

Select count(*) FROM PRODUCT WHERE email = @email

AND THEN RUN AN INSERT

Insert INTO PRODUCT (....) VALUES (....)

Or is there any better way to achieve that ,

Any suggestions or advice will be appreciated .

Thanks

Upvotes: 0

Views: 5848

Answers (2)

Pilgerstorfer Franz
Pilgerstorfer Franz

Reputation: 8359

As marc_s mentioned you may use a conditional insert into. On the other hand, using a unique constraint on your email column may be very helpful too!

Just think of the possibility to insert data without your application. There would be no rule to avoid the same email!

CREATE TABLE Product
(
   xxx int NOT NULL,
   xxx xxx xxx,
   UNIQUE (email)
)

Just google for alter/create table(s) with unique constraints!

Upvotes: 1

marc_s
marc_s

Reputation: 754478

You can have an INSERT statement that checks for the condition, and only inserts something, if it doesn't already exist:

IF NOT EXISTS (SELECT * FROM dbo.Product WHERE email = @email)
   INSERT INTO dbo.Product(list of columns)
   VALUES(list of values)

Upvotes: 3

Related Questions