sql - 一次删除多个表

标签 sql sql-server tsql drop-table

SQL Server 支持 DIE 语法( drop table if exists ):

Multiple tables can be dropped in any database. If a table being dropped references the primary key of another table that is also being dropped, the referencing table with the foreign key must be listed before the table holding the primary key that is being referenced.



例子:
CREATE TABLE t1(i INT PRIMARY KEY);
CREATE TABLE t2(i INT PRIMARY KEY);
CREATE TABLE t3(i INT PRIMARY KEY, t2_id INT REFERENCES t2(i));

丢弃对象的正确方法是:t1/t3,最后是t2。

假设我们运行:
DROP TABLE IF EXISTS t1,t2,t3;
-- Could not drop object 't2' because it is referenced by a FOREIGN KEY constraint.

一切都在预料之中,DDL无法成功完成,因为有FK持有。

现在,我期待 DDL 应该持有 全有或全无行为 .所以我应该仍然保持我的 3 张 table 完好无损。但事实并非如此,表 t1 和 t3 被删除了。
SELECT * FROM t1;
-- Invalid object name 't1'.

SELECT * FROM t2;
SELECT * FROM t3;
-- Invalid object name 't3'.

db<>fiddle demo

看起来它在内部是作为 3 个独立的 drop 语句执行的,这很奇怪。

表 t1 和 t3 消失了还是我遗漏了一些明显的东西?

最佳答案

问题是,DBMS 会删除它可以删除的任何表,但此操作不是原子的。如果你想要一个原子表达式,你可以使用条件 ROLLBACK 到事务中(更多信息请参见 here)

关于sql - 一次删除多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56622718/

相关文章:

java - 超过 22 列的 jOOQ 查询示例

sql - 如何在大查询中查找sql​​上的 "String or binary data would be truncated"错误

sql-server - 日志传输带宽估计

sql - 通过变量插入多行

c# - 存储过程或函数需要未提供的参数

sql - 使用表名删除超过 12 个月的表

php - Codeigniter 插入 MySql 表具有自动递增 ID 的位置?

c# - 必须声明 UTL_RECOMP.RECOMP_SERIAL

sql-server - SQL Server 2008 到 SQL Server Compact Edition?

sql - 做数据透视时无用的错误消息