In SQL Server 2017 I have a view, "ParentView" which is referenced by other views "ChildView1", "ChildView2", etc. Those views are referenced by other views "GrandChildView1", "GrandChildView2", etc. and so on and so forth. I make sure to setup all of my views to have "WITH SCHEMABINDING". When I want to make a change to "ParentView" I'm required to drop and create all of the dependent views. This, of course, makes perfect sense because I have "WITH SCHEMABINDING" on and I could be making a change that could break one of the dependent views. However, doing all of this is tedious through the user interface so I was wondering…
How can I get a script that takes a view or any object as input and creates a drop/create statement based on dependencies?
For example:
DROP VIEW [dbo].[GrandChild]
GO
DROP VIEW [dbo].[Child]
GO
ALTER VIEW [dbo].[Parent]
...
GO
CREATE VIEW [dbo].[Child]
...
GO
CREATE VIEW [dbo].[GrandChild]
...
GO
Notes
- This doesn't have to be specific to views. I also have dependent functions and stored procedures as well.
- None of my views are indexed views.
Best Answer
I've found a way to do this by using a couple of different scripts.
First, I needed to setup the "PrintString" stored procedure from Greg M. Lucas in order to print all of my statements without them being truncated.
Second, I created a temporary table to store all of the dependent entities so I can use it later to print my script. Included in the temporary table is an "Order" column for doing descending order on the drop statements and ascending order on the create statements.
Third, I fill my temporary table using a recursive CTE. In this example my parent view is called 'dbo.Project_Expanded'.
Fourth, I create my drop statements and then my create statements using my temporary table and I copy out the results. Note that my version only handles inline table-valued functions, procedures, and views. You will need to update it if you need to handle more object types.
Finally, I cleanup the temporary table and drop the "PrintString" procedure: