Monday, March 26, 2012

How to trace the records that have been related to the child table

The problem of mine is, I have a datagrid, Which displays data from a Employee(parent) table.

Now I want to delete some records based on the user selected checkbox,
only those records which has no related records in the EmployeeProject(child) can be deleted.
I want to know which are all the record that cannot be deleted?

How can I achieve this?

You need to find out the related records on the child tables by following the primary/foreign key relationships. In the future you can use theON DELETE CASCADE command, or similar, when you create a table, so it will delete all child records automatically. If you don't know the table relationships, I suggest you find out as much as possible about the structure you're working with before allowing data deletion.

|||

SELECT Employee.*,CASE WHEN EXISTS(SELECT * FROM EmployeeProject ep WHERE ep.EmployeeID=e.EmployeeID) THEN 0 ELSE 1 END AS Deletable

FROM Employee e

Then in your datagrid, make a button column that has a commandname of "Delete". Convert that column to a template field. Now databind the button's visible in the template field to Deletable. This isn't a perfect solution because changes can take place in the database from the time you generate the page until you get back the request to delete, but it handles the vast majority of cases. Just make sure you handle the case where you are requested to delete a record that either no longer exists (Most code will just silently fail anyhow), or is no longer deletable (Try/catch the attempt to delete, and on failure, re-databind the grid and toss up an error to the user).

|||

Sorry, didn't notice that you wanted checkboxes. Use the same query, just databind the checkbox'ed enabled property to the Deletable field.

No comments:

Post a Comment