0

I want to delete records of child table and its parent table however there is a catch in this, I have to delete the indirect child of that parent table too.

Let’s take an example to understand more on the problem:

  • My Database is very structural and I have specific names associated with some prefix like for Employee data all tables will start with Emplyee* tables.

  • Each module is having same prefix set of tables. I have almost 20 sets of table for which I have to delete data based on type provided means if Employer is provided, I need to delete data of employer and its employees and its products selected by employees.

  • Employer_Details has an ID (PK) which is reference in all Employer_* tables and also in Employee_MainTable. Employee_MainTable has an employee_ID (PK) which is referenced in all Employee_* table same with product.

So when I pass Employer as table name and column name as ID to proc, it should delete all data from tables (Employer, Employee and Product) based above condition. If I pass Employee, then it should delete data from Employee_* and Product_* tables.

I have started a bit but want some expert comment to make it easy. I do not want to mention tables name instead of that I just need some dynamic query which will get all tables based on reference with one more column order number so that I will delete according to order number.

We don't have cascade delete as these tables are existing and we can't change them. I want to get this by using Information_Schema.Tables means dynamic.

Hope it’s not too complicated!! Thanks!!

4

2 回答 2

2

如果父母有关系,您可以使用级联删除

于 2013-03-08T14:01:02.053 回答
0

如果您的表没有直接关系,那么您只需要编写一个过程来根据传入的信息删除您需要的内容

DECLARE @TableType varchar(30)

BEGIN
    IF(@TableType = 'Employer')
    BEGIN
        DELETE FROM MyTable1 WHERE ID = 1234;
        DELETE FROM MyTable2 WHERE ID = 1234;
    END

    IF(@TableType = 'Employee')
    BEGIN
        DELETE FROM MyTable3 WHERE Employee_ID = 1234;
        DELETE FROM MyTable4 WHERE Employee_ID = 1234;    
    END
END
于 2013-03-08T16:31:41.503 回答