CREATE PROCEDURE dbo.GetFirstHallLineProductNumber @AReferencenumber INT, @AGuestnumber INT, @AProductnumber INT OUTPUT AS
BEGIN
  DECLARE @ProductNumber INT

  IF (@AGuestnumber = 0)
  BEGIN
    SELECT TOP 1 @Productnumber = ReservationConferenceLine.ProductNumber
    FROM ReservationConferenceLine WITH (NOLOCK)
    WHERE (1=1)
      AND ReservationConferenceLine.ReferenceNumber = @AReferencenumber
      AND ReservationConferenceLine.GuestNo = @AGuestnumber
      AND ISNULL(ReservationConferenceLine.Tablebooking, 0) = 0
      AND ISNULL(ReservationConferenceLine.ProductNumber, 0) > 0
    ORDER BY ReservationConferenceLine.ScreenLine
  END
  ELSE
  BEGIN
    SELECT TOP 1 @Productnumber = ReservationConferenceLine.ProductNumber
    FROM ReservationConferenceLine WITH (NOLOCK)
    WHERE (1=1)
      AND ReservationConferenceLine.ReferenceNumber = @AReferencenumber
      AND ReservationConferenceLine.GuestNo = @AGuestnumber
      AND ISNULL(ReservationConferenceLine.Tablebooking, 0) = 0
      AND ISNULL(ReservationConferenceLine.ProductNumber, 0) > 0
    ORDER BY ReservationConferenceLine.ScreenLine

	IF @ProductNumber = 0
	BEGIN
      SELECT TOP 1 @Productnumber = ReservationConferenceLine.ProductNumber
      FROM ReservationConferenceLine WITH (NOLOCK)
      WHERE (1=1)
        AND ReservationConferenceLine.ReferenceNumber = @AReferencenumber
        AND ReservationConferenceLine.GuestNo = 0
        AND ISNULL(ReservationConferenceLine.Tablebooking, 0) = 0
        AND ISNULL(ReservationConferenceLine.ProductNumber, 0) > 0
      ORDER BY ReservationConferenceLine.ScreenLine
	END
  END

  SELECT @AProductNumber = @ProductNumber
END
