
CREATE PROCEDURE [dbo].[API_WmsProdSyncErpToApi]	
AS 
BEGIN

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

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

  -- wybieramy zmiany
  declare @ObjectId int;
  declare @ObjectType int;

DECLARE Doc_Cursor CURSOR FOR	 
select  d.Id,  500 ObjectType  from dbo.DokHandlowe d where 
	 Stan=1 and Kategoria=501 and RealizacjaStan>=10
    and NOT EXISTS ( select * from dbo.[ApiSyncItems] s where s.[SchemaId] = -500 and s.ObjectType = 40 and s.[ObjectId] = d.ID);
  
  

OPEN Doc_Cursor;
FETCH NEXT FROM Doc_Cursor INTO @ObjectId, @ObjectType
WHILE @@FETCH_STATUS = 0
  BEGIN
	  exec [dbo].API_WMSDokCreate @ObjectId, @ObjectType, 0, @SyncId,0;

	  FETCH NEXT FROM Doc_Cursor INTO  @ObjectId, @ObjectType
   END;
CLOSE Doc_Cursor;
DEALLOCATE Doc_Cursor;



  --exec [dbo].API_KntUpdateErp @id;

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