Showing posts with label Stored Procedures. Show all posts
Showing posts with label Stored Procedures. Show all posts

Wednesday, 31 January 2018

Recompile All Table, Stored Procedures and Function In SQL Server

CREATE PROCEDURE [dbo].[spEXECsp_RECOMPILE]
AS
BEGIN
    DECLARE @TableName varchar(128)
    DECLARE @OwnerName varchar(128)
    DECLARE @CMD1 varchar(8000)
    DECLARE @TableListLoop int
    DECLARE @TableListTable table
    (
        UIDTableList int IDENTITY(1, 1),
        OwnerName varchar(128),
        TableName varchar(128)
    )

    INSERT INTO @TableListTable
    (
        OwnerName,
        TableName
    )
    SELECT u.[Name],
           o.[Name]
    FROM sys.objects o
        INNER JOIN sys.schemas u
            ON o.schema_id = u.schema_id
    WHERE o.type IN (   'U', -- table
                        'P', -- stored procedures
                        'FN' -- scalar functions
                    )
    ORDER BY u.[Name],
             o.[Name]

    SELECT @TableListLoop = MAX(UIDTableList)
    FROM @TableListTable

    WHILE @TableListLoop > 0
    BEGIN
        SELECT @TableName = TableName,
               @OwnerName = OwnerName
        FROM @TableListTable
        WHERE UIDTableList = @TableListLoop

        SELECT @CMD1 = 'EXEC sp_recompile ' + '[' + @OwnerName + '.' + @TableName + ']' + char(13)

        --PRINT @CMD1
        EXECUTE (@CMD1)

        SELECT @TableListLoop = @TableListLoop - 1
    END

    SELECT *
    FROM @TableListTable

    SET NOCOUNT OFF

END
------------------------------------------------------
--To run used
EXECUTE [dbo].spEXECsp_RECOMPILE

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...