/*
  NB20080623 bug Personel Access safety taking care of the registration bug in 4.0 webupdate
  TL20071112 Inital revision
  Fixes broken access values in PersonelAccess (Access rights has been saved with wrong values since 3.36). 0 is changed to 1 and 1 is changed to 0
*/
/*
DELETE PersonelAccess WHERE UserIDNumber IN (
  SELECT DISTINCT UserIDNumber FROM Personel (NOLOCK) WHERE IsNull(MarkAsDeleted, 0) = 1 OR IsNull(ActivePerson, 1) <> 1 AND UserTypeNumber = 1
)

UPDATE PersonelAccess SET Access = 9 WHERE Access = 0
UPDATE PersonelAccess SET Access = 0 WHERE Access = 1
UPDATE PersonelAccess SET Access = 1 WHERE Access = 9
*/--nb20080623 Safety taking care of the registration bug in 4.0 webupdate
IF NOT EXISTS(SELECT sysobjects.name
    FROM syscolumns WITH (NOLOCK)
	  INNER JOIN sysobjects WITH (NOLOCK) ON syscolumns.id = sysobjects.id
	  INNER JOIN systypes WITH (NOLOCK) ON syscolumns.xtype = systypes.xtype
	WHERE SysObjects.Name = 'ArrangementLineDepartmentXTab'
	  AND syscolumns.name = 'FK_ArrangementLineNumber')
BEGIN
  print 'Starting conversion of PersonelAccess'
  DELETE PersonelAccess WHERE UserIDNumber IN (
    SELECT DISTINCT UserIDNumber FROM Personel WITH (NOLOCK) WHERE IsNull(MarkAsDeleted, 0) = 1 OR IsNull(ActivePerson, 1) <> 1 AND UserTypeNumber = 1
  )
  UPDATE PersonelAccess SET Access = 9 WHERE Access = 0
  UPDATE PersonelAccess SET Access = 0 WHERE Access = 1
  UPDATE PersonelAccess SET Access = 1 WHERE Access = 9
  print 'Conversion done'
END
ELSE
  print 'Conversion of PersonelAccess already done '
