从 SQL 2008 中的外键关系生成删除语句?
是否可以通过脚本/工具根据表 fk 关系生成删除语句。
即我有表:DelMe(ID),并且有 30 个表,其中有 30 个表对其 ID 进行了 FK 引用,我需要首先删除这些表,是否有一些我可以运行的工具/脚本,它将根据 FK 关系生成 30 个删除语句为我 ?
(顺便说一句,我知道关系上的级联删除,我无法在这个现有数据库中使用它)
我正在使用 Microsoft SQL Server 2008
Is it possible via script/tool to generate a delete statement based on the tables fk relations.
i.e. I have the table: DelMe(ID) and there are 30 tables with fk references to its ID that I need to delete first, is there some tool/script that I can run that will generate the 30 delete statements based on the FK relations for me ?
(btw I know about cascade delete on the relations, I can't use it in this existing db)
I'm using Microsoft SQL Server 2008
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是 Aasim Abdullah,适用于 MS SQL Server 2008:
使用示例 1
请注意示例中完全限定列名的使用。 这很微妙,但您必须指定表名,生成的 SQL 才能正确执行。
使用示例 2
使用示例 3
Here is a script for cascading delete by Aasim Abdullah, works for me on MS SQL Server 2008:
Usage example 1
Note the use of the fully qualified column name in the example. It's subtle but you must specify the table name for the generated SQL to execute properly.
Usage example 2
Usage example 3
生成的 DELETE 语句用于带有参数的 SP,并作为 ON DELETE 触发器:
(此变体仅支持单列 FK)
DELETE statements generated for use in SP with parameter, and as ON DELETE triggers:
(this variant supports single column FKs only)
我很确定我在 Stack Overflow 上发布了代码,该代码使用
INFORMATION_SCHEMA
自动生成动态 SQL,但我找不到它。 让我看看能不能重生。您可能需要检查一下,我找不到原始代码,因此我修改了一些自动为星型模式构建扁平视图的代码。
I'm pretty sure I posted code here on Stack Overflow which does this automatically using
INFORMATION_SCHEMA
to generate dynamic SQL, but I can't find it. Let me see if I can regenerate it.You might need to check this out a bit, I couldn't find my original code, so I modified some code I had which builds flattend views for star-schemas automatically.
另一种技术是使用代码生成器来创建 Sql. 我很确定 MyGeneration (无连接)具有现有模板可以执行此操作。 使用该工具和正确的模板,您可以创建一个 SQL 脚本,轻松删除相关内容。
Another technique is to use a code generator to create the Sql. I'm pretty sure the MyGeneration (no connection) has existing templates to do this. Using that tool and the right template you can create a sql script that deletes the relevant stuff with no pain.
不幸的是,我认为级联是您需要的工具。 我知道无法使用它,但事实上它作为数据库的内置部分存在,几乎消除了对替代方案的需求。
Unfortunately, I think cascading is the tool you're asking for. I understand not being able to use it, but that fact that it exists as a built-in part of the db has pretty much killed the need for an alternative.
您可以创建具有相同名称的所有 fk 列,例如“row_id”
然后编写下面的代码:
You can create all fk columns with a same name like 'row_id'
Then write the code below: