CREATE FUNCTION [dbo].[GetRootRoomNumber] (@ARoomNumber INTEGER)
RETURNS INTEGER AS
BEGIN
	DECLARE @Return INT;
	WITH RootRoom (RoomNumber, ParentRoomNumber) AS
	(
		SELECT RoomNumber, ParentRoomNumber
		FROM ROOMS WITH (NOLOCK)
		WHERE RoomNumber = @ARoomNumber
		UNION ALL
		SELECT Ro.RoomNumber, Ro.ParentRoomNumber
		FROM Rooms ro WITH (NOLOCK)
		INNER Join RootRoom RR ON ro.RoomNumber = RR.ParentRoomNumber
	)
	SELECT @Return = RoomNumber 
	FROM RootRoom 
	WHERE ParentRoomNumber IS NULL
	RETURN @Return
END