IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FNFATURAADETBUL]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[FNFATURAADETBUL]
GO

CREATE FUNCTION [dbo].[FNFATURAADETBUL]
(  @SATINALMAISLID INT)
RETURNS INT
AS
BEGIN
	   RETURN (
				SELECT SUM(ADET)
				FROM
				(
					SELECT ISNULL(SUM(FATISL.FADET), 0) AS ADET
					FROM FATISL WITH(NOLOCK)
						 INNER JOIN FATURA WITH(NOLOCK) ON FATURA.FATID = FATISL.FATID
					WHERE(ISNULL(FATURA.IRSALIYE, 0) = 0)
						 AND (FATISL.SATINALMAISLID = @SATINALMAISLID)
					UNION ALL
					SELECT ISNULL(SUM(FATISL.FADET), 0)
					FROM FATISL WITH(NOLOCK)
						 INNER JOIN FATURA WITH(NOLOCK) ON FATURA.FATID = FATISL.FATID
						 INNER JOIN FATISL AS F2 WITH(NOLOCK) ON F2.FATISLID = FATISL.IRSISLID
					WHERE(ISNULL(FATURA.IRSALIYE, 0) = 0)
						 AND (F2.SATINALMAISLID = @SATINALMAISLID)
				) AS TBL
	)
END
GO