我正在我所有的表中进行软删除。当其他表中引用该 ID 时,我不应该软删除一行。此外,当引用的子表被删除时,即 Isdeleted = 1,那么我应该能够软删除父记录。
感谢您的建议。
我正在我所有的表中进行软删除。当其他表中引用该 ID 时,我不应该软删除一行。此外,当引用的子表被删除时,即 Isdeleted = 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
)