CREATE FUNCTION [dbo].[WareTicketGetPeriodStartEnd] (@APeriodStartType INT, @ADate DATETIME)
  RETURNS @Result TABLE (PeriodStart DATETIME, PeriodEnd DATETIME) AS
BEGIN
/*
*/
  DECLARE @LPeriodStart DATETIME
  DECLARE @LPeriodEnd DATETIME

  SET @LPeriodStart =
  CASE @APeriodStartType
    WHEN 1 THEN CAST(CAST(@ADate AS DATE) AS DATETIME)
    WHEN 2 THEN DATEADD(WEEK, 1, (DATEADD(DAY, -(DATEPART(WEEKDAY, @ADate)-1), DATEADD(DAY, DATEDIFF(DAY, 0, @ADate), 0))))
    WHEN 3 THEN DATEADD(MONTH, DATEDIFF(MONTH, 0, @ADate)+1, 0)
    WHEN 4 THEN DATEADD(QUARTER, DATEDIFF(QUARTER, 0, @ADate)+1, 0)
    WHEN 5 THEN DATEADD(YEAR, DATEDIFF(YEAR, 0, @ADate)+1, 0)
    WHEN 6 THEN DATEADD(DAY, -(DATEPART(WEEKDAY, @ADate)-1), DATEADD(DAY, DATEDIFF(DAY, 0, @ADate), 0))
    WHEN 7 THEN DATEADD(MONTH, DATEDIFF(MONTH, 0, @ADate), 0)
    WHEN 8 THEN DATEADD(QUARTER, DATEDIFF(QUARTER, 0, @ADate), 0)
    WHEN 9 THEN DATEADD(YEAR, DATEDIFF(YEAR, 0, @ADate), 0)
  END

  SET @LPeriodEnd =
  CASE @APeriodStartType
    WHEN 1 THEN DATEADD(MILLISECOND, -3, (DATEADD(DAY, 1, CAST(CAST(@ADate AS DATE) AS DATETIME))))
    WHEN 2 THEN DATEADD(WEEK, 1, (DATEADD(DAY, 7-(DATEPART(WEEKDAY, @ADate)), DATEADD(MILLISECOND, -3, DATEADD(DAY, DATEDIFF(DAY, 0, @ADate) + 1, 0)))))
    WHEN 3 THEN DATEADD(MILLISECOND, -3, (DATEADD(MONTH, DATEDIFF(MONTH, 0, @ADate)+2, 0)))
    WHEN 4 THEN DATEADD(MILLISECOND, -3, (DATEADD(QUARTER, DATEDIFF(QUARTER, 0, @ADate)+2, 0)))
    WHEN 5 THEN DATEADD(MILLISECOND, -3, (DATEADD(YEAR, DATEDIFF(YEAR, 0, @ADate)+2, 0)))
    WHEN 6 THEN DATEADD(DAY, 7-(DATEPART(WEEKDAY, @ADate)), DATEADD(MILLISECOND, -3, DATEADD(DAY, DATEDIFF(DAY, 0, @ADate) + 1, 0)))
    WHEN 7 THEN DATEADD(MILLISECOND, -3, (DATEADD(MONTH, DATEDIFF(MONTH, 0, @ADate)+1, 0)))
    WHEN 8 THEN DATEADD(MILLISECOND, -3, (DATEADD(QUARTER, DATEDIFF(QUARTER, 0, @ADate)+1, 0)))
    WHEN 9 THEN DATEADD(MILLISECOND, -3, (DATEADD(YEAR, DATEDIFF(YEAR, 0, @ADate)+1, 0)))
  END

  INSERT INTO @Result (PeriodStart, PeriodEnd)
  VALUES (@LPeriodStart, @LPeriodEnd)

  RETURN
END