Wednesday 14 May 2014

CRM2011 RU16 OnPremise - Cannot import a Solution into existing database with a custom Activity entity with RU16

Run the below SQL Script after taking a full back of the database.


declare @AttributeId nvarchar(50), @SolutionId nvarchar(50), @OptionSetId nvarchar(50);

declare AttributeCursor cursor for
select a.AttributeId, a.OptionSetId, e.SolutionId
from Attribute a
join Entity e on a.EntityId = e.EntityId
where (a.PhysicalName = 'leftvoicemail' OR a.PhysicalName = 'isMapiPrivate' OR a.PhysicalName = 'OverriddenCreatedOn')
and a.ismanaged = 0 and e.IsManaged = 1
and e.overwritetime = 
(
--Get the solution ID of the solution which introduced these attributes
select min(overwritetime) 
from Entity e2 
where e2.EntityId = a.EntityId AND 
(
--Try to get the solution with the lowest overwritetime that is not equal to 0
OverwriteTime <> 0
OR 
--If none exist, we know overwritetime = 0 is correct
(OverwriteTime = 0  AND 0 = (SELECT max(overwritetime) from entity e3 where e2.EntityId = e3.EntityId and a.EntityId = e3.EntityId))
)
)


open AttributeCursor

fetch next from AttributeCursor
into @AttributeId, @OptionSetId, @SolutionId

while @@FETCH_STATUS = 0
BEGIN
--Updating AttributePickListValue
        update MetadataSchema.AttributePickListValue
        set IsManaged = 1, SolutionId = @SolutionId
        where OptionSetId = @OptionSetId

--Updating LocalizedLabel
        update LocalizedLabel 
   set IsManaged = 1, SolutionId = @SolutionId
        where ObjectId = @AttributeId

--Updating DependencyNodeBase
        update dependencynodebase
        set BaseSolutionId = @SolutionId, 
TopSolutionId = (select solutionId from Attribute
where AttributeId = @AttributeId
and OverwriteTime = 0)
where ObjectId = @AttributeId

--Updating OptionSet
        update MetadataSchema.OptionSet 
        set IsManaged = 1, SolutionId = @SolutionId
        where OptionSetId = @OptionSetId

--Updating Attribute
        update MetadataSchema.Attribute 
        set IsManaged = 1, SolutionId = @SolutionId
        where AttributeId = @AttributeId

        fetch next from AttributeCursor
        into @AttributeId, @OptionSetId, @SolutionId
END

CLOSE AttributeCursor;
DEALLOCATE AttributeCursor;