不要软删除包含其他表的外键的表中的行

时间:2012-04-20 09:16:51

标签: sql sql-server sql-server-2008

我在所有表格中都进行了软删除。在其他表中引用该ID时,我不应该软删除一行。此外,当删除被引用的子表,即Isdeleted = 1时,我应该能够软删除父记录。

您的建议表示赞赏。

1 个答案:

答案 0 :(得分:1)

您需要从架构生成一些动态sql。我没有时间将所有项目都转换为动态sql,但您可以使用游标循环或可能PIVOT作为动态SQL:

-- parent/child schemas, tables, columns
select parent_schema=p.TABLE_SCHEMA
, parent_table=p.TABLE_NAME
, parent_pk_column=p.COLUMN_NAME
, child_schema=c.TABLE_SCHEMA
, child_table=c.TABLE_NAME
, child_fk_column=c.COLUMN_NAME
from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE p
inner join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS pc
    on pc.UNIQUE_CONSTRAINT_SCHEMA=p.CONSTRAINT_SCHEMA
    and pc.UNIQUE_CONSTRAINT_NAME=p.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c
    on c.CONSTRAINT_SCHEMA=pc.CONSTRAINT_SCHEMA
    and c.CONSTRAINT_NAME=pc.CONSTRAINT_NAME
where exists(
    select 1 from INFORMATION_SCHEMA.COLUMNS
    where COLUMN_NAME='IsDeleted' and TABLE_SCHEMA=p.TABLE_SCHEMA and TABLE_NAME=p.TABLE_NAME
)

-- tables/pk columns having IsDeleted column but no children
select parent_schema=p.TABLE_SCHEMA
, parent_table=p.TABLE_NAME
, parent_column=p.COLUMN_NAME
from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE p
where not exists(
    select 1 from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
    where UNIQUE_CONSTRAINT_SCHEMA=p.CONSTRAINT_SCHEMA
    and UNIQUE_CONSTRAINT_NAME=p.CONSTRAINT_NAME
)
and exists(
    select 1 from INFORMATION_SCHEMA.COLUMNS
    where COLUMN_NAME='IsDeleted' and TABLE_SCHEMA=p.TABLE_SCHEMA and TABLE_NAME=p.TABLE_NAME
)