
/****** Object:  StoredProcedure [dbo].[API_KntLokalizacjaSyncErpToApi]    Script Date: 2021-09-08 10:06:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[API_KntLokalizacjaSyncErpToApi]	
AS 
BEGIN

-- 
update dbo.ApiCustomerLocations
set State=-2 where ErpId<>0
and NOT EXISTS ( select * from dbo.Lokalizacje where ID = ErpId);

declare @SyncId int;
INSERT INTO [dbo].[ApiSynchronizations] 
   ([SaveTS],[SchemaId],[ObjectType],[OperatorId],[Message],[Status],[TS],[SyncType]) 
             VALUES 
  ([dbo].[ApiGetSec](CURRENT_TIMESTAMP),-1, 11,-1,'',1,CURRENT_TIMESTAMP,2);

  set @SyncId = (SELECT SCOPE_IDENTITY());
  --select @SyncId;

  -- wybieramy zmiany
  declare @KntLokalizacjaErpId int;

DECLARE Knt_Cursor CURSOR FOR	 
	
  select k.Id KntId--, ci.Id HistId 
  from dbo.ChangeInfos ci
  JOIN dbo.Lokalizacje k ON ci.SourceGuid = k.Guid where 
  SourceTable = 'Lokalizacje' 
  and dbo.ApiGetSec(Time)> ISNULL((select Max([SaveTS]) from dbo.[ApiSynchronizations] where [ObjectType] = 11 and [SyncType] = 2 and [Status]=2),0)
  and NOT EXISTS ( select * from dbo.ApiSyncItems where HistId = ci.Id);
  

OPEN Knt_Cursor;
FETCH NEXT FROM Knt_Cursor INTO @KntLokalizacjaErpId
WHILE @@FETCH_STATUS = 0
  BEGIN
	  exec [dbo].[API_KntLokalizacjaUpdateErp] @KntLokalizacjaErpId;
	  FETCH NEXT FROM Knt_Cursor INTO @KntLokalizacjaErpId
   END;
CLOSE Knt_Cursor;
DEALLOCATE Knt_Cursor;



  --exec [dbo].API_KntUpdateErp @id;

  -- konczenie synchronizacji
  update dbo.ApiSynchronizations set Status = 2 where Id = @SyncId;
END
  
GO


