SQL Server 数据库初始化准备脚本

通常我们在项目部署前都会写一份数据库初始化脚本。由于数据库外键的限制,我们需要按照数据引用顺序添加初始记录,这个整理过程相当麻烦。

因此写了以下脚本,原理是先去掉所有外键,然后执行一次清空,然后添加数据,最后恢复外键。

网上也有暂时禁用外键添加数据的方法,但由于SQL Server在有外键的情况下,不能使用TRUNCATE TABLE语句,因此暂时禁用外键时,只能使用DELETE语句清除无用数据。如果觉得删除外键不安全,也可以考虑将以下脚本修改为禁用外键的方式运行。

脚本在 SQL Server 2005、SQL Server 2008 R2、SQL Server 2012 上测试过,都没有问题。

 1 SET NOCOUNT ON;
 2 
 3 DECLARE @script NVARCHAR(255);
 4 
 5 --缓存所有外键
 6 SELECT OBJECT_NAME(fk.constraint_object_id) AS name, OBJECT_NAME(fk.parent_object_id) AS ptab, pc.name AS pcol, OBJECT_NAME(fk.referenced_object_id) AS rtab, rc.name AS rcol
 7 INTO #FK_ON
 8 FROM sys.foreign_key_columns fk
 9 LEFT JOIN sys.columns pc ON fk.parent_column_id = pc.column_id AND fk.parent_object_id = pc.[object_id]
10 LEFT JOIN sys.columns rc ON fk.referenced_column_id = rc.column_id AND fk.referenced_object_id = rc.[object_id];
11 
12 BEGIN TRAN
13 
14 --删除所有外键
15 DECLARE cur_fk_off CURSOR FOR SELECT 'ALTER TABLE [dbo].[' + OBJECT_NAME(parent_object_id) + '] DROP CONSTRAINT ' + name FROM sys.foreign_keys;
16 OPEN cur_fk_off
17 FETCH NEXT FROM cur_fk_off INTO @script
18 WHILE @@FETCH_STATUS = 0
19 BEGIN
20     EXEC(@script)
21     FETCH NEXT FROM cur_fk_off INTO @script
22 END
23 CLOSE cur_fk_off
24 DEALLOCATE cur_fk_off
25 
26 --清空所有表
27 DECLARE cur_tabs CURSOR FOR SELECT 'TRUNCATE TABLE [dbo].[' + name + ']' FROM sys.tables;
28 OPEN cur_tabs
29 FETCH NEXT FROM cur_tabs INTO @script
30 WHILE @@FETCH_STATUS = 0
31 BEGIN
32     EXEC(@script)
33     FETCH NEXT FROM cur_tabs INTO @script
34 END
35 CLOSE cur_tabs
36 DEALLOCATE cur_tabs
37 
38 --写入初始化数据
39 --INSERT INTO ...
40 
41 --重建所有外键
42 DECLARE cur_fk_on CURSOR FOR SELECT 'ALTER TABLE [dbo].[' + ptab + '] ADD CONSTRAINT ' + name + ' FOREIGN KEY ([' + pcol + ']) REFERENCES [dbo].[' + rtab + '] ([' + rcol + '])' FROM #FK_ON;
43 OPEN cur_fk_on
44 FETCH NEXT FROM cur_fk_on INTO @script
45 WHILE @@FETCH_STATUS = 0
46 BEGIN
47     EXEC(@script)
48     FETCH NEXT FROM cur_fk_on INTO @script
49 END
50 CLOSE cur_fk_on
51 DEALLOCATE cur_fk_on
52 
53 --清除缓存
54 DROP TABLE #FK_ON
55 
56 COMMIT TRAN
57 GO

本文出自于 飞扬的尘埃的博客 转载请注明出处。

posted on 2015-01-27 17:07  飞扬的尘埃  阅读(8505)  评论(0编辑  收藏  举报

导航