Skip to content

Instantly share code, notes, and snippets.

@jnm2
Created December 23, 2016 18:14
Show Gist options
  • Save jnm2/faadcdd7ffe92e38b9cea0d92d5e1e99 to your computer and use it in GitHub Desktop.
Save jnm2/faadcdd7ffe92e38b9cea0d92d5e1e99 to your computer and use it in GitHub Desktop.
/*
Everything with no dependencies comes first. That way, when a new item is added with a dependency on an existing item, it doesn't cause the existing item to jump.
Of course an existing item taking a dependency on an existing item will cause a jump, may as well move the changing item.
An existing item taking a dependency on a new item will also jump. It doesn't really make sense to putting the new item first, out of order, if it doesn't have dependencies.
Basically: order by depth_of_deepest_dependency, original_order
*/
with
creating_objects as (
select
object_id,
row_number() over (order by schemas.name, objects.name) as original_order
from sys.objects
join sys.schemas on schemas.schema_id = objects.schema_id
where objects.type in ('v', 'p', 'if', 'tf') and schemas.name = 'vw'
),
creating_dependencies as (
select
referencing_id,
referenced_id
from sys.sql_expression_dependencies
join creating_objects on creating_objects.object_id = referenced_id
where referencing_id != referenced_id
),
recursive_depth_calculator as (
select
object_id,
0 as depth
from creating_objects
left join creating_dependencies on referencing_id = object_id
where referencing_id is null
union all
select
current_depth.referencing_id,
depth + 1
from recursive_depth_calculator
join creating_dependencies current_depth on object_id = referenced_id
)
select ids_with_depth.object_id from (
select
object_id,
max(depth) as max_depth
from recursive_depth_calculator
group by object_id
) ids_with_depth
join creating_objects on creating_objects.object_id = ids_with_depth.object_id
order by max_depth, original_order
@UbhiTS
Copy link

UbhiTS commented Nov 26, 2018

Dude, ur da BOMB !!!
You just solved my problem, Microsoft should package this script with every SQL installation so that when we generate scripts with individual files, we can execute them in order ... hats off !!!

@jnm2
Copy link
Author

jnm2 commented May 20, 2019

@UbhiTS I'm glad it helped! :')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment