IF NOT EXISTS (
    SELECT i.index_id
    FROM sys.indexes i
    JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
    JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
    WHERE 
        i.object_id = OBJECT_ID('dbo.EST_RPS_NFSE_ERRO') 
        AND i.type_desc = 'NONCLUSTERED'
        AND (
            (c.name = 'RPS_ID' AND ic.is_included_column = 0)
            OR (c.name = 'CD_EMP' AND ic.is_included_column = 0)
            OR (c.name = 'CD_FILIAL' AND ic.is_included_column = 0)
			OR (c.name = 'ID' AND ic.is_included_column = 0)
            OR (c.name = 'MSG_ERRO' AND ic.is_included_column = 1))
    GROUP BY i.object_id, i.index_id
    HAVING COUNT(*) = 5
)
BEGIN
    CREATE INDEX IX_EST_RPS_NFSE_ERRO_RPS_ID_CD_EMP_CD_FILIAL_MSG_ERRO
	ON dbo.EST_RPS_NFSE_ERRO (RPS_ID, CD_EMP, CD_FILIAL, ID DESC)
	INCLUDE (MSG_ERRO);
END
