Pages

Tuesday, July 5, 2011

Method To Check For Record Existence Before Inserting in DB.

In some data base management applications, while creating a new record, we would require to check for any duplication's. i. before inserting we need to check whether the record already exist or not.
This could be handled in 3 different ways.

For example say you need to add new department details. and before inserting check whether the depart already exist or not by using the department name.

Method 1:
     - From code behind (.cs) file, make a call to DB and execute a select statement with where condition to the department name. And in the .cs file have a if condition and check for the no of rows in the returned value.
     - If the row count is 0, then make a call to insert the record.
     - If the row count is more than 1, then return a message saying record already exist.

Method 2: This works out only when the DB is normalized. ie. the table should have a primary key.
     - From the code behind make a call to insert the record, and have this part inside the try catch block. Now if the record doesn't exist, then it gets added successfully, else it throws an exception of primary key constraint. Now this could be got in catch block and give a message saying the record already exist.

Method 3: works out when we use stored procedure for inserting.
     - In the SP, have an "if not exists" condition before the execution of insert command.
ex.

     - We just need to have IF NOT EXISTS condition before insert. Similar to having a if condition in the stored procedure.

No comments:

Post a Comment