SET NOCOUNT ON
DECLARE @FK_DepartmentNumber INT
DECLARE @UserIdNumber INT
DECLARE @AreaFunctionNumber INT

DECLARE db_user CURSOR FOR
  SELECT UserIdNumber FROM Personel WITH (NOLOCK) WHERE UserTypeNumber IN (3,4)  -- AutoDay/AutoNight
OPEN db_user

FETCH NEXT FROM db_user INTO @UserIdNumber

WHILE @@FETCH_STATUS = 0
BEGIN
  DECLARE db_department CURSOR FOR
    SELECT PK_Department FROM Departments WITH (NOLOCK) WHERE ISNULL(MarkAsDeleted, 0) = 0
  OPEN db_department

  FETCH NEXT FROM db_department INTO @FK_DepartmentNumber

  WHILE @@FETCH_STATUS = 0
  BEGIN
    IF NOT EXISTS (SELECT * FROM PersonelDepartmentsXtab WITH (NOLOCK) WHERE UserIDNumber = @UserIdNumber AND FK_Department = @FK_DepartmentNumber) 
      INSERT INTO PersonelDepartmentsXtab (UserIDNumber, FK_Department) VALUES (@UserIdNumber, @FK_DepartmentNumber)  
    FETCH NEXT FROM db_department INTO @FK_DepartmentNumber
  END
  CLOSE db_department
  DEALLOCATE db_department
  
  DECLARE db_access CURSOR FOR
    SELECT DISTINCT Number FROM iter_intlist_to_table('0,1,2,3,4,5,6,7,8,9')  -- TSelectorAreaFunctions
  OPEN db_access

  FETCH NEXT FROM db_access INTO @AreaFunctionNumber

  WHILE @@FETCH_STATUS = 0
  BEGIN
    IF NOT EXISTS (SELECT * FROM PersonelAccess WITH (NOLOCK) WHERE UserIdNumber = @UserIdNumber AND AreaFunctionNumber = @AreaFunctionNumber AND AreaNumber = 10)
      INSERT INTO PersonelAccess VALUES (@UserIdNumber, @AreaFunctionNumber, 0, 10)   -- 0=alReadOnly 10=ppSelector
    FETCH NEXT FROM db_access INTO @AreaFunctionNumber
  END
  CLOSE db_access
  DEALLOCATE db_access

  FETCH NEXT FROM db_user INTO @UserIdNumber  
END

CLOSE db_user
DEALLOCATE db_user