DECLARE @NumberOfRooms INT
DECLARE @NumberOfAttendees INT
DECLARE @ReferenceNumber INT
DECLARE @LineNumber INT

IF EXISTS(select * from hotelsetup h (nolock)
inner join HotelSetupValueXTab hvx (nolock) on h.HotelSetUpNumber = hvx.HotelSetupNumber
inner join HotelSetupValue hv (nolock) on hvx.FK_ValueNumber = hv.PK_ValueNumber
where SearchKey = 'internalcourseproduction' and hv.KeyValue = '1')
BEGIN
	DECLARE #CUR CURSOR FOR
	select numberOfRooms,Referencenumber,rl.LINENUMBER from reservationreservationxtab rrx (nolock)
	inner join RESERVATIONROOMLINEXTAB rlx (nolock) on rlx.ReferenceNumber = rrx.FK_ReferenceNumberSub and rrx.FK_ReferenceNumber = rrx.FK_ReferenceNumberSub
	inner join reservationroomline rl (nolock) on rl.LINENUMBER = rlx.LINENUMBER

	Open #CUR

	FETCH NEXT FROM #CUR 
	INTO @NumberOfRooms, @ReferenceNumber, @LineNumber

	WHILE (@@FETCH_STATUS = 0)
	BEGIN

		SELECT @NumberOfAttendees = SUM(numberOfRooms) FROM reservationreservationxtab rrx (NOLOCK)
		INNER JOIN RESERVATIONROOMLINEXTAB rlx (NOLOCK) on rlx.ReferenceNumber = rrx.FK_ReferenceNumberSub AND rrx.FK_ReferenceNumber <> rrx.FK_ReferenceNumberSub
		inner join reservations r (nolock) on rlx.ReferenceNumber = r.ReferenceNumber and rlx.GuestNumber = r.guestnumber and r.status <6
		INNER JOIN reservationroomline rl (NOLOCK) ON rl.LINENUMBER = rlx.LINENUMBER
		WHERE RRX.FK_ReferenceNumber = @ReferenceNumber

		if @NumberOfAttendees IS NULL
			SET @NumberOfAttendees = 0

		UPDATE ReservationRoomline 
		SET InitialNumberOfRooms = @NumberOfRooms + @NumberOfAttendees
		WHERE LINENUMBER = @LineNumber

		FETCH NEXT FROM #CUR 
		INTO @NumberOfRooms, @ReferenceNumber, @LineNumber

	end

	CLOSE #CUR
	DEALLOCATE #CUR
END