CREATE function dbo.GetName ( @ref int, @guest int)
returns varchar(100)
as
begin
declare @name varchar(100)
declare @tempname varchar(100)

--Company
select @tempname = ltrim(rtrim(firstname + ' ' + lastname)) from reservationaddress WITH (nolock) inner join reservationaddressxtab WITH (nolock) on reservationaddress.addressnumber = reservationaddressxtab.addressnumber where addresstype = 2

--Agency
if len(@tempname) = 0
  select @tempname = ltrim(rtrim(firstname + ' ' + lastname)) from reservationaddress WITH (nolock) inner join reservationaddressxtab WITH (nolock) on reservationaddress.addressnumber = reservationaddressxtab.addressnumber where addresstype = 3

--Agent
if len(@tempname) = 0
  select @tempname = ltrim(rtrim(firstname + ' ' + lastname)) from reservationaddress WITH (nolock) inner join reservationaddressxtab WITH (nolock) on reservationaddress.addressnumber = reservationaddressxtab.addressnumber where addresstype = 6

--Guest
if len(@tempname) = 0 
  select @tempname = ltrim(rtrim(firstname + ' ' + lastname)) from reservationaddress WITH (nolock) inner join reservationaddressxtab WITH (nolock) on reservationaddress.addressnumber = reservationaddressxtab.addressnumber where addresstype = 1

set @name = @tempname
return @name
 
end

