I have a requirement wherein I need to script out the definition of all objects that depend on a single table. See the below example.
Let's say I have a table and there are 15 objects(views, SPs, Functions, triggers etc) that depend on it. Then I need definition of all those 15 objects.
This needs to be done on 15 servers. Is there a way to script all those objects using a T-SQL script? Currently I am noting all the objects down in an excel and scripting out definitions of all the objects manually which is very tedious. :(
-
SSMS has a scripting option that allows you script out dependent objects You can write them to file or new tab/window.Steve Mangiameli– Steve Mangiameli2016年10月13日 18:50:27 +00:00Commented Oct 13, 2016 at 18:50
-
@SteveMangiameli Right click > View Dependencies shows dependencies for me in SSMS but its Script button is grayed out. Would you share the way you found?Forrest– Forrest2016年10月13日 19:48:06 +00:00Commented Oct 13, 2016 at 19:48
2 Answers 2
It looks like you can get dependency information from many places, one of which is sys.sql_expression_dependencies
.
Sample query below:
SELECT OBJECT_NAME([referencing_id]), OBJECT_DEFINITION([referencing_id])
FROM sys.sql_expression_dependencies
WHERE referenced_entity_name = 'myTable'
GROUP BY [referencing_id]
I'm not confident that this system view is sufficient for all dependencies, but hopefully this is enough to get you started until someone more knowledgeable chimes in.
More info can easily be found by Googling "sql dependencies." E.g. https://stackoverflow.com/questions/22005698/how-to-find-all-the-dependencies-of-a-table-in-sql-server
-
I have added more details in my question. Please see if there is a better way to achieve this.SQLPRODDBA– SQLPRODDBA2016年10月13日 18:37:54 +00:00Commented Oct 13, 2016 at 18:37
-
@SQLPRODDBA Edited the sample query.Forrest– Forrest2016年10月13日 18:44:17 +00:00Commented Oct 13, 2016 at 18:44
In SSMS...
- Rt Click on the Database in question, navigate to Tasks and then Generate Scripts...
- Select Choose Objects on the left and then click the radio button to
Select specific database objects
- Select the object you wish to script
- In
Save to file
click theAdvanced
button - 6th option down, set
Generate Script for Dependent Objects
to true - Set any other options you want and click the
OK
button - Set the
File name
and path orSave to Clipboard
orSave to new query window
- Click the
Next
buttons to finish.