CREATE FUNCTION [dbo].[GetWareGroupDepartmentString](@AWareGroupNumber INT, @AType TINYINT, @GetKeys BIT, @AAddDelimiter BIT, @AHotelNumber INT) RETURNS VARCHAR(2048) AS
BEGIN
/*
  Created by Kent Johansen marts 2013
  
  Type 1 = Cashier department
  Type 2 = Booking department
  Type 3 = Table Booking department

Changes:
*/
  DECLARE @Result VARCHAR (2048)
  DECLARE @Text Varchar (3)
  DECLARE @PK_Department int

  DECLARE #cr CURSOR FOR
    SELECT Departments.DepartmentNumber, Departments.PK_Department 
    FROM Departments WITH (NOLOCK)
    INNER JOIN WareGroupsDepartmentsXtab WITH (NOLOCK) ON WareGroupsDepartmentsXtab.FK_Department =  Departments.PK_Department 
      AND WareGroupsDepartmentsXtab.WareGroupNumber = @AWareGroupNumber 
      AND WareGroupsDepartmentsXtab.Type = @AType
    WHERE ISNULL(MarkAsDeleted,0) = 0
    AND (@AHotelNumber < 0 OR Departments.HotelNumber = @AHotelNumber)
    ORDER BY Departments.DepartmentNumber
  OPEN #cr
  
  FETCH NEXT FROM #cr INTO @Text, @PK_Department

  SET @Result = ''
  WHILE @@fetch_status = 0
  BEGIN
    IF @AAddDelimiter = 1 AND @Result <> ''
      SET @Result = @Result + ','

    IF @GetKeys = 1
      SET @Result = @Result + CONVERT(VARCHAR(3),@PK_Department)
    ELSE
      SET @Result = @Result + @Text

    FETCH NEXT FROM #cr INTO @Text, @PK_Department
  END

  CLOSE #cr
  DEALLOCATE #cr

  RETURN @Result
END