ALTER PROCEDURE [dbo].[PRPTINVDOCDETAILN]
(
	@DocDateFrom VARCHAR(20)
	,@DocDateTo VARCHAR(20)
	,@DocStatus VARCHAR(20)
	,@DocNo VARCHAR(20)
	,@DocType VARCHAR(20)
)
AS

--DECLARE @DocDateFrom VARCHAR(20) = ''
--DECLARE @DocDateTo VARCHAR(20) = ''
--DECLARE @DocStatus VARCHAR(20) = ''
--DECLARE @DocNo VARCHAR(20) = '00000800'
--DECLARE @DocType VARCHAR(20) = 'GICU'

IF (@DocDateFrom <> '') BEGIN SET @DocDateFrom = @DocDateFrom END ELSE BEGIN SET @DocDateFrom = '19000101' END
IF (@DocDateTo <> '') BEGIN SET @DocDateTo = @DocDateTo END ELSE BEGIN SET @DocDateTo = '99991231' END

DECLARE @DefCompIDDesc VARCHAR(250) = (SELECT TOP(1) CompanyDescription FROM dbo.PCMEPCOMPID)

SELECT DISTINCT head.DocNo
		,dbo.fn_formatdatetime(head.DocDate, 'dd/mm/yyyy') AS DocDate
		,head.DocType
		,dt.DocTypeDesc
		,head.NoResi
		,head.Description
		,head.CompanyID
		,CASE WHEN comp.CompanyDescription <> '' THEN comp.CompanyDescription ELSE @DefCompIDDesc END CompanyDescription
		,item.MaterialID
		,mat.Description AS MaterialDesc
		,mat.ExternalID
		,item.Quantity
		,item.Warehouse
		,wh.Description AS WarehouseDesc
FROM dbo.PTRMATERIALHEAD AS head
INNER JOIN dbo.PTRMATERIALITEM AS item
	ON head.DocNo = item.DocNo
LEFT JOIN dbo.PMDMAT0001 AS mat
	ON item.MaterialID = mat.MaterialID
LEFT JOIN dbo.PCMBSDOCTYPE AS dt
	ON head.DocType = dt.DocType
LEFT JOIN dbo.PCMFILOWAREHOUSE AS wh
	ON item.Warehouse = wh.Warehouse
LEFT JOIN dbo.PCMEPCOMPID AS comp
	ON head.CompanyID = comp.CompanyID
WHERE (head.DocType = @DocType OR @DocType = '')
	AND (head.DocDate >= @DocDateFrom AND head.DocDate <= @DocDateTO)
	AND (head.DocStatus = @DocStatus OR @DocStatus = '')
	AND (head.DocNo = @DocNo OR @DocNo = '')