我正在使用SQL Server内置功能(Task -> Generate script
)为视图生成脚本。我正在为每个对象(视图)创建单独的文件。我已经说过要在另一个数据库上执行的大约400个文件(包含所有视图的SQL脚本)并自动执行此操作我创建了BAT文件来处理这个问题。
有些视图依赖于其他视图,并且由于许多视图无法执行。我们有什么方法可以设定执行顺序并摆脱失败?
任何指针都会有很大的帮助。
如果您需要更多详细信息,请与我们联系。
由于
尊利
答案 0 :(得分:0)
你能试试这个查询吗?您可以执行创建脚本以便" gen" (代)。
DECLARE @cnt int = 0, @index int;
DECLARE @viewNames table (number int, name varchar(max))
DECLARE @viewGen table (id uniqueidentifier, gen int, name varchar(max), parentId uniqueidentifier)
INSERT INTO @viewNames
SELECT ROW_NUMBER() OVER(ORDER BY object_Id), name FROM sys.views
SELECT @cnt = COUNT(*) FROM @viewNames
SET @index = @cnt;
WHILE ((SELECT COUNT(*) FROM @viewGen) < @cnt)
BEGIN
DECLARE @viewName varchar(200)
SELECT @viewName = name FROM @viewNames WHERE number = @index;
DECLARE @depCnt int = 0;
SELECT @depCnt = COUNT(*) FROM sys.dm_sql_referencing_entities ('dbo.' + @viewName, 'OBJECT')
IF (@depCnt = 0)
BEGIN
INSERT INTO @viewGen SELECT NEWID(), 0, name, null FROM @viewNames WHERE number = @index;
END
ELSE
BEGIN
IF EXISTS(SELECT * FROM sys.dm_sql_referencing_entities ('dbo.' + @viewName, 'OBJECT') AS r INNER JOIN @viewGen AS v ON r.referencing_entity_name = v.name)
BEGIN
DECLARE @parentId uniqueidentifier = NEWID();
INSERT INTO @viewGen SELECT @parentId, 0, name, null FROM @viewNames WHERE number = @index;
UPDATE v
SET v.gen = (v.gen + 1), parentId = @parentId
FROM @viewGen AS v
INNER JOIN sys.dm_sql_referencing_entities('dbo.' + @viewName, 'OBJECT') AS r ON r.referencing_entity_name = v.name
UPDATE @viewGen
SET gen = gen + 1
WHERE Id = parentId OR parentId IN (SELECT Id FROM @viewGen WHERE parentId = parentId)
END
END
SET @index = @index - 1
IF (@index < 0) BEGIN SET @index = @cnt; END
END
SELECT gen as [order], name FROM @viewGen ORDER BY gen
期待结果:
order name
0 vw_Ancient
1 vw_Child1
1 vw_Child2
2 vw_GrandChild