多租户:如何删除租户?

发布于 2024-12-25 16:50:21 字数 192 浏览 1 评论 0原文

我有一个具有共享多租户的系统,这意味着每个表都包含所有租户的数据,并通过 TenantId 列来区分它们。

配置新租户既快速又简单,但现在我面临着删除单个租户的挑战。

鉴于实体相互依赖以保持一致性,当系统正在被其他租户使用时,如何轻松地从数据库中删除租户?

如果有帮助的话,系统使用 SQL Server 2008 R2。

I have a system with shared multitenancy, which means each table contains data for all tenants with a TenantId column to distinguish between them.

Provisioning a new tenant is quick and easy, however now I'm facing a challenge with deleting a single tenant.

Given that entities depend on each other for consistency, how do I delete a tenant easily from my database, while the system is in use by other tenants?

The system uses SQL Server 2008 R2, if that helps.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

十雾 2025-01-01 16:50:21

如果我没猜错的话 - 这是使用 FOREIGN KEYSON CASCADE 选项的经典案例。您只从主租户表中删除一条记录,并且由于 FKey 的正确链,系统会删除相关记录或使用 NULLDEFAULT 值更新引用列

有时将不起作用表通过 DELETE ON CASCADE 引用自身的情况

If I got you right - this is the classical case for use of FOREIGN KEYS with ON CASCADE option. You only delete one record from master tenants table and due to proper chain of FKeys the system deletes related records or updates the reference columns with NULL or DEFAULT value

Sometimes will not work in cases where table references itself with DELETE ON CASCADE

眼眸印温柔 2025-01-01 16:50:21

正如 Oleg 指出的那样,使用 ON CASCADE 选项的 FK 应该会有所帮助。但由于您没有向我们展示架构,我不太确定系统是否有可能抛出错误“引入外键约束导致循环或多个级联路径”。如果您看到此错误,则可能需要添加 INSTEAD OF DELETE 触发器来代替 CASCADE DELETE 来完成该工作。

CREATE TRIGGER dbo.Tenants_Delete 
ON dbo.Tenants
INSTEAD OF DELETE
AS
BEGIN;
    --Delete from the Child and Master table as per your need here.
    --Make use of the magic table DELETED
END;

As Oleg has pointed out FK with ON CASCADE option should help. But since you haven't shown us the schema, I am not very sure whether there is a possibility of system throwing an error saying "Introducing FOREIGN KEY constraint causes cycles or Multiple cascade paths". If you see this error then may be instead of CASCADE DELETE add a INSTEAD OF DELETE trigger to do the job.

CREATE TRIGGER dbo.Tenants_Delete 
ON dbo.Tenants
INSTEAD OF DELETE
AS
BEGIN;
    --Delete from the Child and Master table as per your need here.
    --Make use of the magic table DELETED
END;
无法言说的痛 2025-01-01 16:50:21

这是另一种方法:如果删除租户引起太多麻烦,您可以使用解决方法。

只需将布尔列 active 添加到您的租户表即可。然后引入一个仅选择活动租户的视图。调整存储过程以查找此视图中的数据,而不是原始租户表中的数据。

Here's another approach: If deleting the tenant causes too much headache, you may be able to use a workaround.

Simply add a boolean column active to your tenant table. Then introduce a view that selects only the active tenants. Adjust your stored procedures to look up the data in this view rather than in the original tenant table.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文