IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'dbo.[CF_Turno_Destinatario]') 
                   and type = 'FN')
BEGIN
    DROP FUNCTION dbo.[CF_Turno_Destinatario]
END
GO

CREATE FUNCTION [dbo].[CF_Turno_Destinatario] (@Id_Turno INT)
RETURNS VARCHAR(1000)
AS 
BEGIN

DECLARE @Razon_Social VARCHAR(100)
DECLARE @Razon_Sociales VARCHAR(1000)
DECLARE @Id_Cliente INT

SELECT @Razon_Social = C.Razon_Social, @Id_Cliente = T.Id_Cliente FROM CRM_Turnos T, Clientes C
WHERE C.Id_Cliente = ISNULL(T.Id_Cliente,0)
AND T.Id_Turno = @Id_Turno

IF @Id_Cliente = 0	RETURN ''



DECLARE curNombre CURSOR FOR
	SELECT ISNULL(LTRIM(RTRIM(C.Razon_Social)), '') AS Razon_Social
	FROM CRM_Turnos_Clientes TC , Clientes C 
	WHERE TC.Id_Cliente = C.Id_Cliente
	AND TC.Id_Turno = @Id_Turno 
	AND ISNULL(TC.Id_Cliente,0) <> 0

SET @Razon_Sociales=@Razon_Social

OPEN curNombre
FETCH NEXT FROM curNombre INTO @Razon_Social
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @Razon_Sociales= @Razon_Sociales + ' / ' + @Razon_Social
	FETCH NEXT FROM curNombre INTO @Razon_Social
END
CLOSE curNombre
DEALLOCATE curNombre

RETURN @Razon_Sociales
END
