IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FNETS_MEDISOFT_FATURA_ODEMETURLERI]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[FNETS_MEDISOFT_FATURA_ODEMETURLERI]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FNETS_MEDISOFT_FATURA_ODEMETURLERI]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N' CREATE FUNCTION  [dbo].[FNETS_MEDISOFT_FATURA_ODEMETURLERI]  
 (@FATID as Integer)   
 RETURNS NVARCHAR(100) AS   
 BEGIN  
 DECLARE @ODEMETURU AS NVARCHAR(20),@ODEMETURUADI AS NVARCHAR(100) 
  
 SET @ODEMETURUADI = ''''  
  
 DECLARE FATURA_ODEME_CURSOR CURSOR 
 FOR SELECT ODEMETURUADI FROM ODEMEISL (NOLOCK) INNER JOIN TODEMETURU (NOLOCK) ON (ODEMEISL.ODEMETURUID=TODEMETURU.ODEMETURUID)  
                WHERE (ODEMEISL.HSTHFATISLID = @FATID /*OR ODEMEISL.KRMHFATISLID=@FATID OR ODEMEISL.SGFATID=@FATID*/)  AND IPTAL=0 
                UNION ALL
                SELECT ODEMETURUADI FROM ODEMEISL (NOLOCK) INNER JOIN TODEMETURU (NOLOCK) ON (ODEMEISL.ODEMETURUID=TODEMETURU.ODEMETURUID)  
                WHERE (ODEMEISL.KRMHFATISLID=@FATID)  AND IPTAL=0
                UNION ALL
                SELECT ODEMETURUADI FROM ODEMEISL (NOLOCK) INNER JOIN TODEMETURU (NOLOCK) ON (ODEMEISL.ODEMETURUID=TODEMETURU.ODEMETURUID)  
                WHERE (ODEMEISL.SGFATID=@FATID)  AND IPTAL=0
 OPEN FATURA_ODEME_CURSOR  
 FETCH NEXT FROM FATURA_ODEME_CURSOR  INTO @ODEMETURU 
  
 WHILE @@FETCH_STATUS = 0 
 BEGIN 
     IF @ODEMETURU IS NULL SET @ODEMETURU='''' 
     IF @ODEMETURUADI ='''' SET @ODEMETURUADI = @ODEMETURU  
     ELSE  
     SET @ODEMETURUADI= @ODEMETURUADI+'',''+@ODEMETURU  
     FETCH NEXT FROM FATURA_ODEME_CURSOR  INTO @ODEMETURU 
 END 
  
 IF Cursor_Status(''variable'', ''FATURA_ODEME_CURSOR'')<>-1  
                CLOSE FATURA_ODEME_CURSOR 
 DEALLOCATE FATURA_ODEME_CURSOR 
  
 RETURN @ODEMETURUADI 
 END 
' 
END

GO


