

/****** Object:  UserDefinedFunction [dbo].[apiPersonGetERP]    Script Date: 07.09.2021 06:22:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE FUNCTION [dbo].[apiPersonGetERP]
(
	@Id int
	
	
)
RETURNS  int
BEGIN
   DECLARE @res int;
 set @res = ISNULL((
	  select top 1 inny.ErpId from dbo.ApiCustomerPersons badany
  JOIN  dbo.ApiCustomerPersons inny ON 
  badany.CustPersonId = inny.CustPersonId
  and badany.VendorId = inny.VendorId 
 
  and ISNULL(badany.DeviceUid,'') = ISNULL(inny.DeviceUid,'')
  and (ABS(badany.SaveTS - inny.SaveTS))/(60*60*24)< 10 -- nie więcej niż 10 dni różnicy
  where inny.ErpId<>0 and badany.Id = @Id
     ORDER BY inny.SaveTS DESC
  )
	
	--,*
	 ,0);
	 return @res;
END




GO


