从多个子表中删除行后,从父表中动态删除行



我有一个脚本,它将返回父表和子表的详细信息,其中包含各自的键列和表的行应该被删除的顺序。下面是脚本返回的详细信息:

| Child_table| Child_column| Parent_Table| Parent_Column| Delete_Order|
|:-----------|:------------| ------------| -------------|-------------|
| Child1     | Child1_ID   | Child2      | Child2_Id    |  2          |
| Child2     | Child2_ID1  | Parent1     | Parent_ID    |  1          |
| Child3     | Child3_ID   | Parent1     | Parent_ID    |  1          |
| Parent1    | Parent_ID   |             |              |  0          |

上表中Child1Child2的子表andChild2andChild3Parent1。现在我需要按Delete_Order列中给出的降序从子表到父表删除数据。

我需要帮助编写一个动态查询,将连接这些表和根据主键数据从Child和Parent表中删除数据

使用递归CTE创建DELETE语句。语句必须按照do desc的顺序运行。用合适的值替换'=1'

with cte as (
select cast('delete' + x.childAlias + ' from ' + Child_table + x.childAlias +
case when Parent_Column is null then ' where ' + Child_column + ' = 1;' else '' end as nvarchar(max))  sql,
x.childAlias, Child_column, 
Parent_Table, Parent_Column, 
Delete_Order do
from tbl
cross apply (select ' t' + cast(tbl.Delete_Order as varchar(3))) x(childAlias)

union all

select cte.sql + ' join ' + tbl.Child_table + x.childAlias + 
' on' + cte.childAlias+ '.' + cte.Child_column + ' =' + x.childAlias + '.'+ cte.Parent_Column +
case when tbl.Parent_Column is null then ' where' + x.childAlias + '.' + tbl.Child_column + ' = 1;' else '' end  sql,
x.childAlias, tbl.Child_column,
tbl.Parent_Table, tbl.Parent_Column,
do  
from cte
join tbl on cte.Parent_Table = tbl.Child_table
cross apply (select ' t' + cast(tbl.Delete_Order as varchar(3))) x(childAlias)
) 
select sql, do
from cte
where sql like '%where%'
order by do desc

,db&lt的在小提琴

最新更新