CREATE FUNCTION dbo.IsNamelistNeeded (@ReferenceNumber INT)
RETURNS BIT AS  
BEGIN 

	DECLARE @LineCount INT
	DECLARE @RoomCount INT
	DECLARE @PaxCount INT
	DECLARE @NamelistPerPersonMandatory VARCHAR(10)
	DECLARE @Result BIT
	DECLARE @NamelistSetting INT
	DECLARE @ProductNumber INT

	SET @RoomCount = 0
	SET @PaxCount = 0
	SET @Result = 0

	SELECT  @LineCount = COUNT(*) FROM RESERVATIONROOMLINEXTAB (NOLOCK)
	WHERE ReferenceNumber = @ReferenceNumber AND GuestNumber = 0

	SET @LineCount = ISNULL(@LineCount, 0)

	IF @LineCount = 1
	BEGIN
		SELECT @RoomCount = NumberOfRooms, @ProductNumber = ProductNumber FROM RESERVATIONROOMLINE RL (NOLOCK)
		INNER JOIN RESERVATIONROOMLINEXTAB RLX (NOLOCK) ON RL.LINENUMBER = RLX.LINENUMBER AND Rlx.ReferenceNumber = @ReferenceNumber AND RLX.GuestNumber = 0

		SELECT @NamelistSetting = NameListSetting FROM Products (NOLOCK)
		WHERE ProductNumber = @ProductNumber

		SET @NamelistSetting = ISNULL(@NamelistSetting, 1)
		
		IF @NamelistSetting = 2
		BEGIN
			SELECT @NamelistPerPersonMandatory = KeyValue FROM HotelSetup
			WHERE SearchKey = 'NamelistPerPersonMandatory'

			SET @NamelistPerPersonMandatory = ISNULL(@NamelistPerPersonMandatory, '')
			IF @NamelistPerPersonMandatory = '1' 
			BEGIN
				SELECT @PaxCount = Adults + Children1 + Children2 FROM RESERVATIONROOMLINE RL (NOLOCK)
				INNER JOIN RESERVATIONROOMLINEXTAB RLX (NOLOCK) ON RL.LINENUMBER = RLX.LINENUMBER AND Rlx.ReferenceNumber = @ReferenceNumber AND RLX.GuestNumber = 0

				Set @PaxCount = ISNULL(@PaxCount, 0)
			END
		END
	END
	IF @LineCount > 1 OR @RoomCount > 1 OR @PAXCount > 1
		SET @Result = 1
	RETURN @Result	
END
