CREATE OR ALTER FUNCTION HM.ForeignOrderWithAdvanceInvoiceExists(@saleDocumentId INT) 
RETURNS BIT
AS
BEGIN
	DECLARE @aiExists BIT
	-- wskazany lub korygowany dokument
	DECLARE @sdId INT =
		ISNULL( ( SELECT ISNULL(iddokkoryg, id)
					FROM HM.DK
				   WHERE id = @saleDocumentId ), 0 )

	-- powiazanie faktura-zamowienie/zamowienia (korekty nie maja swoich transakcji)
	;WITH cte AS
	(
		SELECT
			HM.AdvanceInvoiceExists(owner_id) as result
		FROM 
		(
			SELECT tzo.owner_id
				    FROM HM.TR AS tdk
						 INNER JOIN HM.PO ON tdk.id = PO.id2
						 INNER JOIN HM.TR AS tzo ON PO.id1 = tzo.id AND tzo.owner_base = 45
				   WHERE tdk.owner_id = @sdId AND tdk.owner_base = 16
		) tr
	)
	SELECT @aiExists = CASE WHEN EXISTS (SELECT 1 FROM cte WHERE result = 1) THEN 1 ELSE 0 END;
	-- czy istnieje zaliczka do powiązanych zamówień
	RETURN @aiExists 
END