Try this:
/*
Example 1: Rename a table dbo.MyTable -> dbo.YourTable
EXEC dbo.USP_DROP_ENFORCED_DEPENDENCIES @SchemaName=N'dbo', @EntityName=N'MyTable', @Debug=1;
EXEC sp_rename N'dbo.MyTable', N'YourTable', N'OBJECT'
Example 2: Rename a column dbo.MyTable.MyColumn -> dbo.MyTable.YourColumn
EXEC dbo.USP_DROP_ENFORCED_DEPENDENCIES @SchemaName=N'dbo', @EntityName=N'MyTable', @ColumnName=N'MyColumn' @Debug=1;
EXEC sp_rename N'dbo.MyTable.MyColumn', N'YourColumn', N'COLUMN'
*/
CREATE Procedure dbo.USP_DROP_ENFORCED_DEPENDENCIES
(
@SchemaName sysname = 'dbo',
@EntityName sysname,
@ColumnName sysname = NULL,
@Debug bit = 0
)
AS
BEGIN
SET NOCOUNT ON;
SET ROWCOUNT 0;
DECLARE @ReferencingEntitySchema sysname, @ReferencingEntityName sysname, @ReferencingEntityType nvarchar(8), @SqlScript nvarchar(512);
DECLARE ReferencingEntitiesCursor CURSOR LOCAL FORWARD_ONLY
FOR
SELECT OBJECT_SCHEMA_NAME(dep.referencing_id) AS [schema]
,referencing_entity.name
,CASE referencing_entity.type
WHEN 'V' THEN N'VIEW'
ELSE /*IF, FN, TF*/ N'FUNCTION'
END as [type]
FROM sys.sql_expression_dependencies AS dep
INNER JOIN sys.objects AS referencing_entity
ON dep.referencing_id = referencing_entity.object_id
WHERE dep.referenced_entity_name = @EntityName
AND dep.referenced_schema_name = @SchemaName
AND is_schema_bound_reference = 1
AND ((@ColumnName IS NULL AND dep.referenced_minor_id = 0) OR COL_NAME(dep.referenced_id, dep.referenced_minor_id) = @ColumnName)
OPEN ReferencingEntitiesCursor
FETCH NEXT FROM ReferencingEntitiesCursor
INTO @ReferencingEntitySchema, @ReferencingEntityName, @ReferencingEntityType;
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC dbo.USP_DROP_ENFORCED_DEPENDENCIES @SchemaName=@ReferencingEntitySchema, @EntityName=@ReferencingEntityName, @Debug=@Debug;
--The goal is to produce the following script:
/*
DROP FUNCTION dbo.UFN_SOME_FUNCTION;
OR
DROP VIEW dbo.UFN_SOME_VIEW;
*/
SET @SqlScript = N'DROP ' + @ReferencingEntityType + N' ' + @ReferencingEntitySchema + '.' + @ReferencingEntityName;
IF(@Debug = 1)
RAISERROR (@SqlScript, 0/*severity*/, 0/*state*/) WITH NOWAIT;
EXEC (@SqlScript);
FETCH NEXT FROM ReferencingEntitiesCursor
INTO @ReferencingEntitySchema, @ReferencingEntityName, @ReferencingEntityType;
END
CLOSE ReferencingEntitiesCursor;
DEALLOCATE ReferencingEntitiesCursor;
END
GO