我看到this topic。 这与我的问题非常相似。 但我不想使用任何第三方来创建脚本。 我想创建一个脚本,以依赖顺序和编程方式删除和创建数据库的视图。 我怎么能做这样的事情?
答案 0 :(得分:0)
最后我发现我的答案是这样的, 但请记住,这仅适用于具有一个嵌套级别的视图。不多 ! :
SELECT MIN(Row) AS Row, CreateCmd FROM (
SELECT Row_Number() OVER (ORDER BY S.Row) As Row, S.CreateCmd FROM (
SELECT 0 AS Row, RTRIM(ISNULL(smv.definition, ssmv.definition)) AS CreateCmd
FROM sys.all_objects AS v
LEFT OUTER JOIN sys.sql_modules AS smv ON smv.object_id = v.object_id
LEFT OUTER JOIN sys.system_sql_modules AS ssmv ON ssmv.object_id = v.object_id
INNER JOIN (SELECT object_id, referenced_major_id FROM sys.sql_dependencies
GROUP BY object_id, referenced_major_id) AS a ON v.object_id = a.referenced_major_id
WHERE (v.type = 'V' OR v.type = 'P' OR v.type = 'IF' OR v.type = 'TF' OR v.type = 'FN')
AND SCHEMA_NAME(v.schema_id) = N'dbo' AND is_ms_shipped <> 1
AND smv.execute_as_principal_id IS NULL AND ssmv.execute_as_principal_id IS NULL
GROUP BY v.Name, smv.definition, ssmv.definition
UNION ALL
SELECT 1 AS Row, RTRIM(ISNULL(smv.definition, ssmv.definition)) AS CreateCmd
FROM sys.all_objects AS v
LEFT OUTER JOIN sys.sql_modules AS smv ON smv.object_id = v.object_id
LEFT OUTER JOIN sys.system_sql_modules AS ssmv ON ssmv.object_id = v.object_id
INNER JOIN (SELECT object_id, referenced_major_id FROM sys.sql_dependencies
GROUP BY object_id, referenced_major_id) AS a ON v.object_id = a.object_id
WHERE (v.type = 'V' OR v.type = 'P' OR v.type = 'IF' OR v.type = 'TF' OR v.type = 'FN')
AND SCHEMA_NAME(v.schema_id) = N'dbo' AND is_ms_shipped <> 1
AND smv.execute_as_principal_id IS NULL AND ssmv.execute_as_principal_id IS NULL
GROUP BY v.Name, smv.definition, ssmv.definition
) S GROUP BY S.Row, CreateCmd
) D GROUP BY CreateCmd ORDER BY Row