Script all views/functions/procedures in a Sql Server database in dependency order

三世轮回 提交于 2019-12-22 08:38:19

问题


Sql Server 2008 (and probably most other versions): Management Studio has a 'generate scripts' option that can in theory script a whole database with all objects (Right click, tasks, Generate Scripts). It works OK for most things but when you use it to script all views/stored procedures/functions in a database, it generates a script that does not take account of dependencies between the objects.

e.g. If View A references Function B it won't necessarily put Function B in the script first.

It takes a long time to untangle the great long script that gets produced so that it is in an order that will run without errors.

There must be a better way. Whats the best way to get round this, preferably without spending any money?*

* (red gate ftw)


回答1:


Unfortunately, the only quick and easy way to create such a script is using some third party tools. We’re using Apex Script but there are also other tools out there and Red Gate probably has its own version of this.

Other options are:

  • Running the script many times until everything is executed
  • Trying to create correct order yourself using sys.dependancies which may not work always
  • Coming up with your own dependency algorithm which is an overkill …

There was a bug in sys dependencies views in previous versions SQL Server. I remember reading about it when SQL 2008 was about to be released.

I don’t remember all the detail but it was something about dependencies not working correctly when objects were dropped and re-created.




回答2:


Here's a poor-man's approach:

  1. Craft a query based on sys.sql_dependencies that lists from the bottom up. That is, list base objects first, then the objects upon which those depend, etc. This will give you the order in which to script your objects.
  2. Use powershell to then script those objects out.


来源:https://stackoverflow.com/questions/5541086/script-all-views-functions-procedures-in-a-sql-server-database-in-dependency-ord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!