CREATE FUNCTION [dbo].[GetArrDepartureDate] (@Departuredate char(8), @departuretime char(5))  
RETURNS char(8) AS  
BEGIN 

  declare @Tempdate datetime 
  declare @daystarts char(5)

  declare @result char(8)

  select @daystarts = keyvalue from hotelsetup WITH (nolock) where searchkey = 'Arr24Hoursstarts'

  IF @daystarts IS NULL
  BEGIN
    SET @result =  @departuredate  
  END
  ELSE
  BEGIN
    IF @departuretime <@daystarts
    BEGIN
      SET @tempdate = convert (datetime,@departuredate) -1
      SET @result = convert (char(8),@tempdate,112)
    END
    ELSE
      SET @result =  @departuredate  


  END

  RETURN (@result)

END

