
set nocount on

PRINT 'PZOOSTALO'


select count(*) from  log.wall 
	where 
	--remoteid='69A29533-4869-E811-946E-D89D6719E0CA'
		 oldvalue is null 
		and  remoteid is not null
		and newvalue is not null


DECLARE @remoteid uniqueidentifier 
DECLARE @wallid uniqueidentifier 
DECLARE @adddate datetime 
declare @xmlval xml

DECLARE db_cursor CURSOR FOR 
	select top 100000 remoteid ,wallID, addDate from  log.wall 
	where 
	--remoteid='69A29533-4869-E811-946E-D89D6719E0CA'
		 oldvalue is null 
		and  remoteid is not null
		and newvalue is not null
		and operation !='insert'
		
	order by 3 desc

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @remoteid  ,@wallid ,@adddate

WHILE @@FETCH_STATUS = 0  
BEGIN  
   
	set @xmlval=     (select top 1 newvalue from log.wall x where x.remoteid = @remoteid and newvalue is not null   and x.addDate  < @addDate   order by adddate desc)
	if (@xmlval is not null)
	Begin
	 update log.wall
	 set oldvalue = @xmlval
	 where wallID =@wallID
	 print 'updated ' + cast( @wallid as varchar(36))
	END
	ELSE
	Begin
	 print 'previous not found ' + cast( @wallid as varchar(36))
	End

      FETCH NEXT FROM db_cursor INTO @remoteid  ,@wallid ,@adddate
 
END 

CLOSE db_cursor  
DEALLOCATE db_cursor 

set nocount off