【发布时间】:2016-02-19 16:16:55
【问题描述】:
我正在使用 Microsoft SQL Server 2008 R2 并为数据库的所有对象(如表、函数、触发器、过程、视图、约束等)生成一个包含脚本的 ddl 文件。
现在我的要求是按字母顺序为数据库对象生成这个 ddl 文件,并且对对象类型的所有查询都应该组合在一起。
即:-
Drop Table A1
Create Table A1
Alter Table A1
Drop Table B1
Create Table B1
Alter Table B1
Drop Function F1
Create Function F1
Drop Procedure P1
Create Procedure P1 and so on..
查询是从代码中完美执行的,因为它是按照顺序在代码中处理的。
问题:当我以相同的顺序直接在数据库上执行 SQL 文件时,我遇到了以下两个问题。
案例一: 表 B1 的主键是表 A1 的外键。在这种情况下,如果我们直接在数据库上执行 SQL 文件,那么 Alter Table A1 查询会报错
Cannot find the object "B1" because it does not exist or you do not have permissions.
正在执行中,因为表 B1 尚未创建。
案例二: 表 A1 的主键是表 B1 的外键。在这种情况下,Drop Table A1 查询会报错
Could not drop object 'A1' because it is referenced by a FOREIGN KEY constraint. (Microsoft SQL Server, Error: 3726)
如果我们直接在数据库上执行 SQL 文件,则在执行中。
提前致谢!
【问题讨论】:
-
由于像这样的循环外键,大多数 DDL 生成器会首先创建所有表,包括主键和索引,然后,一旦创建了所有表,外键使用
ALTER TABLE添加。