
 CREATE VIEW [dbo].[ApiDocImportView] as
   SELECT   
	d.ErpId TrN_TrNID ,[CustId] TrN_PodId,     
	[NumberString] TrN_NumerPelny ,[Number] TrN_Numer,[Year] TrN_Rok,[Month] TrN_Miesiac,  
	def.ErpId TrN_DdfId,[Series] TrN_Seria  ,[Date] TrN_DataDok,   
	[Date] TrN_DataWys,[Date] TrN_DataOpe  ,
   [Description] TrN_Opis ,[vendorId] TrN_VendorId,[lines] TrN_Lines,[value] TrN_RazemNetto ,    16 as TrN_Mag2Id, RepositoryId TrN_MagId, PrecedentDoc TrN_NadrzDok,
   case when  SaveTS
   >ISNULL((select  MAX([dbo].[ApiGetSec](TS)) from dbo.ApiTaskHistories where RelObjectType=0 and RelObjectId = d.Id),0)
	then SaveTS
	else ISNULL((select  MAX([dbo].[ApiGetSec](TS)) from dbo.ApiTaskHistories where RelObjectType=0 and RelObjectId = d.Id),0)
	end SaveTS

	FROM [dbo].[ApiDocuments] d          
	 JOIN dbo.ApiDefinitions def ON d.DefId = def.Id 
	and def.Behaviour in ( 0,4) 
	--and d.ErpId=0 
	where [State] <4 

GO


