IF EXISTS(
    SELECT * FROM sys.columns 
    WHERE Name = N'ValueDateOld' AND Object_ID = Object_ID(N'BA_Metadata'))
BEGIN
		DECLARE @dateValue NVARCHAR (MAX), @metaid int;
		DECLARE @SQLString nvarchar(500); 
		DECLARE @meta_cursor CURSOR;

		SET @SQLString =  N'set @cursor = cursor for select BM.[Id], BM.[ValueDateOld] from [dbo].BA_Metadata as BM LEFT OUTER JOIN [dbo].BA_MetadataDefinition as BMD  on BM.MetadataDefinition_Id=BMD.Id where BMD.Type=''datetime'' and BM.[ValueDateOld] is not null open @cursor;'
		exec sys.sp_executesql
		@SQLString,N'@cursor cursor output',@meta_cursor output

		FETCH NEXT FROM @meta_cursor INTO @metaid, @dateValue

		WHILE @@FETCH_STATUS = 0
		BEGIN

			UPDATE [dbo].BA_Metadata
				SET [ValueDate]=cast(@dateValue as datetimeoffset(7))
				WHERE [id] = @metaid

			FETCH NEXT FROM @meta_cursor 
			INTO @metaid, @dateValue
		END 

		CLOSE @meta_cursor;
		DEALLOCATE @meta_cursor;
		ALTER TABLE [dbo].BA_Metadata DROP COLUMN ValueDateOld
END;
