John
John

Reputation: 447

Checking DB for Duplicate Data (C#)

I'm try to allow a user to add a category (to the database). However, I don't want there to be duplicate categories.

This is what I have so far:

using (var sqlcmd = new SqlCommand("INSERT INTO category_table AS e (Category) VALUES(@cat) WHERE e.Category != @cat;", sqlconnection))
 {
     //code here to add category to DB
 }

However, I get the error:

"SqlException Unhandled: Incorrect syntax near the keyword 'AS'."

Upvotes: 2

Views: 611

Answers (3)

Andy_Vulhop
Andy_Vulhop

Reputation: 4789

The problem is with your sql.

INSERT INTO category_table AS e (Category) VALUES(@cat) WHERE e.Category != @cat;

Inserts don't have a WHERE clause. Further, you can't alias the table you are inserting to.

If you want to only insert into the database conditionally, you need to use a SELECT to look and see if there's an existing Category of the same type and only insert if it does not exist, or set the column to be unique via a constraint.

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172438

First your insert syntax is wrong. It should be

INSERT INTO category_table (Category)  values(@cat)

Also remove the where condition. The syntax for insert is wrong.

So it would be like

using (var sqlcmd = new SqlCommand("INSERT INTO category_table (Category)  values(@cat)", sqlconnection))
 {
     //code here to add category to DB
 }

Secondly you need to make the column as unique for which you dont want duplication.

Upvotes: 0

walther
walther

Reputation: 13600

Simply mark the column as Unique. Don't do the work of DB in C#.

Upvotes: 2

Related Questions