Skip to content

Instantly share code, notes, and snippets.

@tcartwright
Created July 6, 2017 18:13
Show Gist options
  • Select an option

  • Save tcartwright/12994135de3b841c64f20906bee2fbab to your computer and use it in GitHub Desktop.

Select an option

Save tcartwright/12994135de3b841c64f20906bee2fbab to your computer and use it in GitHub Desktop.
SQL SERVER: Refresh all sql modules
DECLARE @objects TABLE (RecID INT IDENTITY(1,1), name nvarchar(512), type varchar(5))
DECLARE @null_data TABLE (null_data varchar(1))
-- retrieve the list of objects
INSERT INTO @objects(name, type)
SELECT
'[' + SCHEMA_NAME(o.[schema_id]) + '].[' + o.name + ']', o.type
FROM sys.objects o
WHERE o.is_ms_shipped = 0
AND (o.type <> 'V' OR OBJECTPROPERTY(o.object_id, 'IsSchemaBound') = 0)
AND (o.type in ('P', 'V')
OR ( o.type in ('FN','IF', 'TF', 'AF', 'FS', 'FT')
AND OBJECTPROPERTY(o.[object_id], 'IsSchemaBound') = 0
) -- cant refresh these schema bound objects
)
order by
case
when o.type like '%F%' then 0
when o.type = 'V' then 1
when o.type = 'P' then 2
else 99
end
, o.name
-- counter variables
DECLARE @counter INT, @total INT
SELECT @counter = 1, @total = COUNT(*) FROM @objects
DECLARE @name sysname,
@type varchar(5),
@stmt nvarchar(max) = ''
-- start the loop
WHILE @counter <= @total BEGIN
SELECT @name = o.name, @type = o.type
FROM @objects o
WHERE RecID = @counter
PRINT 'REFRESHING: ' + @type + ' ' + @name
BEGIN TRY
-- refresh the object
EXEC sp_refreshsqlmodule @name
END TRY
BEGIN CATCH
PRINT 'REFRESH FAILED FOR : ' + @type + ' ' + @name + ', Error: ' + ERROR_MESSAGE()
END CATCH
SET @counter = @counter + 1
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment