/*
	Dieses Script muss vor dem ersten Start von theasoft V4 ausgeführt werden
    Das Script aktualisiert die Datensstruktur der theasoft Datenbank.
	
	- Bitte achten Sie darauf das die richtige (theasoft) Datenbank ausgewählt ist. -
*/

--------------------- Versions und Datenbankprüfungen ---------

--#region Prüfung auf Theasoft Datenbank
IF NOT EXISTS 
	(SELECT * 
	 FROM dbo.sysobjects 
	 WHERE id = OBJECT_ID('dbo.NVData') AND OBJECTPROPERTY(id, 'IsUserTable') = 1)
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='
		
																																															Print ''
																																															Print '		Keine theasoft V4 Datenbank!!!'	
																																															Print '		Bitte wechseln Sie die Datenbank'
																																															Print ''
																																															Print '=============================================='
																																															Print ''
																																															Print ''
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
																																															Print ''
																																															Print ''
																																															RAISERROR('Keine Theasoft Datenbank!!!', 20, -1) WITH LOG
																																															SET NOEXEC ON
END
GO
--#endregion

--#region SQL-Server Versionsprüfung
DECLARE @serverVersion INT
SELECT @serverVersion = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
	IF @serverVersion < 10
	
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='
																																															Print ''
																																															Print '		Die SQL-Server-Version 2005 u. älter wird nicht mehr unterstützt!!!'	
																																															Print '		Bitte migrieren Sie auf eine aktuelle Version'
																																															Print ''
																																															Print '=============================================='
																																															Print ''
																																															Print ''
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
																																															Print ''
																																															Print ''
																																															RAISERROR('Nicht unterstützte SQL-Server-Version!!!', 20, -1) WITH LOG
																																															SET NOEXEC ON
END
GO
--#endregion

--#region Datenbankmodel Versionsprüfung 166
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 166 OR (Minor=166 AND Build < 100)))))
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='		
																																															Print ''
																																															Print '		Der Versionsunterschied ist zu groß!!!'	
																																															Print '		Bitte führen Sie DbScript_2016.sql aus dem Unterordner OptionalScripts aus '
																																															Print '		bevor Sie DBScript.sql ausführen      '
																																															Print ''
																																															Print '=============================================='
																																															Print ''
																																															Print ''																																															Print''
																																															Print''
																																															RAISERROR(N'Datenbankversion zu alt!!!', 20, -1) WITH LOG
																																															SET NOEXEC ON
END
GO
--#endregion

--#region Datenbankmodel Versionsprüfung 181
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major > 4 OR (Major = 4 AND (Minor >= 181))))
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='		
																																															Print ''
																																															Print '		Veraltete Skriptversion!!!'	
																																															Print '		Bitte führen Sie DbScript_2018.sql bzw. DbScript.sql aus.'
																																															Print ''
																																															Print '=============================================='
																																															Print ''
																																															Print ''																																															Print''
																																															Print''
																																															RAISERROR(N'Skriptversion veraltet!!!', 20, -1) WITH LOG
																																															SET NOEXEC ON
END
GO
--#endregion

--------------------- Ende Versions und Datenbankprüfungen ----

--------------------- HilfsProzeduren -------------------------

--#region Standards setzen
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
--#endregion

--#region DeleteConstraint
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DeleteConstraint'))
BEGIN
	DROP PROCEDURE dbo.DeleteConstraint 
END
go

CREATE PROCEDURE dbo.DeleteConstraint
	@tab varchar(100), 
	@field varchar(100)
AS
BEGIN
	DECLARE @defname varchar(100)
	SELECT @defname = name 	FROM sysobjects so JOIN sysconstraints sc ON so.id = sc.constid 
			WHERE object_name(so.parent_obj) = @tab
			AND so.xtype = 'D'
			AND sc.colid = 	(SELECT colid FROM syscolumns WHERE id = OBJECT_ID(@tab) AND name = @field)
	
	IF @defname <> '' BEGIN
		EXEC ('ALTER TABLE '+@tab+' DROP CONSTRAINT '+@defname)
		Print 'Default Constraint '+@defname+' gelöscht.'
	END	
END
GO
--#endregion

--#region DropIndexByTable
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DropIndexByTable'))
BEGIN
	DROP PROCEDURE dbo.DropIndexByTable
END
go
CREATE PROCEDURE dbo.DropIndexByTable 
	@tablename varchar(100)
AS
BEGIN

DECLARE @ConstraintName VARCHAR(100) 
DECLARE cview_cursor CURSOR FOR 
	SELECT so.name FROM sysobjects so JOIN sysconstraints sc
		ON so.id = sc.constid  
		WHERE object_name(so.parent_obj) = @tablename
		AND so.xtype = 'UQ'

OPEN cview_cursor 
	FETCH NEXT FROM cview_cursor 
	INTO @ConstraintName 
	WHILE @@FETCH_STATUS = 0 
	BEGIN  
		Print @ConstraintName
		declare @ccmd varchar(100)
	
		select @ccmd='ALTER TABLE '+@tablename+' DROP CONSTRAINT '+@ConstraintName
		exec (@ccmd)

		FETCH NEXT FROM cview_cursor 
		INTO @ConstraintName 
	END 
CLOSE cview_cursor 
DEALLOCATE cview_cursor 


DECLARE @IndexName VARCHAR(100) 
DECLARE view_cursor CURSOR FOR
		SELECT  i.name AS IndexName 
		FROM sysindexes AS i 
		WHERE OBJECT_NAME( i.id ) = @tablename and NOT ([Status]&0x800)=0x800 and  not i.name LIKE '_WA_Sys%' and impid = 0
	
OPEN view_cursor 
	FETCH NEXT FROM view_cursor 
	INTO @IndexName 
	WHILE @@FETCH_STATUS = 0 
	BEGIN  
		Print @IndexName
		declare @cmd varchar(100)
		select @cmd='DROP INDEX ' +@tablename+ '.'+ @IndexName
		exec (@cmd)

		FETCH NEXT FROM view_cursor 
		INTO @IndexName 
	END 
CLOSE view_cursor 
DEALLOCATE view_cursor 


END
GO
--#endregion

--#region PrepareUniqueColumnIndex
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].PrepareUniqueColumnIndex'))
BEGIN
	DROP PROCEDURE dbo.PrepareUniqueColumnIndex 
END
Go
CREATE PROCEDURE dbo.PrepareUniqueColumnIndex 
	(@tablename varchar(100),
	@columnname varchar(100),
	@primarykey varchar(100),
	@type varchar(100))
AS
BEGIN
	DECLARE @cmd NVARCHAR(MAX);
	SELECT @cmd='UPDATE '+@tablename+' SET '+@columnname+' = b.Neu 
		FROM '+ 
		@tablename+' as a inner join (
				SELECT 
					CAST
					(
					(CAST(ROW_NUMBER() OVER 
						(PARTITION BY '+ 
		@columnname+' ORDER BY LM) 
					AS NVARCHAR(2)) +COALESCE('+ 
		@columnname+',''#NAME#'')) AS '+@type+') AS neu
					,ROW_NUMBER() OVER (PARTITION BY 
		'+@columnname+' ORDER BY lm) AS nummer,
		'+@primarykey+'
				FROM 
		'+@tablename+'
				) AS b 
	ON 
		a.'+@primarykey+'=b.'+@primarykey+'
	WHERE b.nummer>1';
	EXECUTE SP_EXECUTESQL @cmd
END
GO
--#endregion

--#region DropColumn
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DropColumn'))
BEGIN
	DROP PROCEDURE dbo.DropColumn 
END
GO
CREATE PROCEDURE dbo.DropColumn 
	@tablename varchar(100),
	@columnname varchar(100)
AS
BEGIN
IF  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = @columnname and o.id = OBJECT_ID(N'[dbo].[' + @tablename+ ']'))	
	BEGIN
		--TODO: Ggf. Index entf.
		declare @defname varchar(100)
		declare @cmd varchar(100)
		SELECT @defname = name 

		FROM sysobjects so JOIN sysconstraints sc ON so.id = sc.constid 
			WHERE object_name(so.parent_obj) = @tablename
				AND so.xtype = 'D'
				AND sc.colid = 	(SELECT colid FROM syscolumns 
								WHERE id = object_id(@tablename) AND name = @columnname)

		SELECT @cmd='alter table '+ @tablename + ' drop constraint ' + @defname
		EXEC (@cmd)
			
		IF EXISTS (SELECT TOP 1 S.NAME FROM SYS.SYSOBJECTS S JOIN SYS.SYSCOLUMNS C ON S.ID = C.CDEFAULT
			WHERE C.ID = OBJECT_ID( @tablename) AND C.NAME =  @columnname)
		BEGIN

			SELECT @cmd ='sp_unbindefault ''' +  @tablename + '.' + @columnname + ''''
			EXEC (@cmd)
		END
		
		SELECT @cmd='alter table '+@tablename+ ' drop COLUMN [' + @columnname + ']'
		EXEC (@cmd)
		print('Column '+@columnname+' dropped!')
	END
END
GO

--#endregion

--#region DropDefault
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DropDefault'))
BEGIN
	DROP PROCEDURE dbo.DropDefault 
END
GO
CREATE PROCEDURE dbo.DropDefault 
	@tablename varchar(100),
	@columnname varchar(100)
AS 

BEGIN
	declare @default sysname,	@exec    nvarchar(4000)

	select 	@default = o.name
	from syscolumns c inner join sysobjects o on c.cdefault = o.id
	where c.cdefault > 0 and c.id = OBJECT_ID(@tablename) and
	c.name = @columnname

	set @exec = 'alter table ' + @tablename + ' drop constraint ' + @default
	print @exec
	if @exec is not NULL exec sp_executesql @exec
END
GO
--#endregion

--Stored Procedure zum Löschen von Rollen, die vorher allerdings alle Member aus de Rolle entfernt
--#region DropRoleWithDropRoleMember

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DropRoleWithDropRoleMember'))
BEGIN
	DROP PROCEDURE dbo.DropRoleWithDropRoleMember 
END
GO
CREATE PROCEDURE dbo.DropRoleWithDropRoleMember 
	@role varchar(100)
AS 

BEGIN
	DECLARE @RoleName sysname
	set @RoleName = @role
	IF  EXISTS (SELECT * FROM dbo.sysusers WHERE name = @RoleName AND issqlrole = 1)
	Begin
 
      DECLARE @RoleMemberName sysname
      /* Cursor to Loop in for Each Member have the Role Privilege and Drop RoleMember */
      DECLARE Member_Cursor CURSOR FOR
      select [name]
      from dbo.sysusers
      where uid in (
            select memberuid
            from dbo.sysmembers
            where groupuid in (
                  select uid
                  FROM dbo.sysusers where [name] = @RoleName AND issqlrole = 1))
 
      OPEN Member_Cursor;
 
      FETCH NEXT FROM Member_Cursor
      into @RoleMemberName
 
      WHILE @@FETCH_STATUS = 0
      BEGIN
 
            exec sp_droprolemember @rolename=@RoleName, @membername= @RoleMemberName
 
            FETCH NEXT FROM Member_Cursor
            into @RoleMemberName
      END;
 
      CLOSE Member_Cursor;
      DEALLOCATE Member_Cursor;
      /* End Of Cursor */
 
	END
	
	/* Checking If Role Name Exists In Database */
	IF  EXISTS (SELECT * FROM dbo.sysusers WHERE name = @RoleName)
		EXEC sp_droprole @rolename = @RoleName
	
END
go
--#endregion

--Die Prozedur ConvertToXml konvertiert Spalten von VARCHAR, NVARCHAR, TEXT und NTEXT nach XML.
--Vor der Konvertierung wird die Spalte ggf. auf MAX erhöht, unvollständiger Inhalt entfernt und die Codierungsangabe im XML korrigiert.
--#region ConvertColumnToXml
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].ConvertColumnToXml'))
BEGIN
	DROP PROCEDURE dbo.ConvertColumnToXml 
END
GO
CREATE PROCEDURE dbo.ConvertColumnToXml 
	@tablename VARCHAR(100),
	@columnname VARCHAR(100),
	@sparse BIT = 0,
	@endTag VARCHAR(100) = ''
AS 

BEGIN
	DECLARE @collation VARCHAR(100)
	DECLARE @codePage VARCHAR(4)
	DECLARE @sql nvarchar(4000)
	DECLARE @systemTypeId TINYINT
	DECLARE @maxLength SMALLINT
	DECLARE @isSparse BIT
	DECLARE @sqlSparse VARCHAR (10)
	DECLARE @debug BIT

	SET @debug = 0

	IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(@tablename) AND [name] = @columnname AND system_type_id IN (35, 99, 167, 231)) BEGIN
		PRINT('Changing ' + @tablename + '.' + @columnname + ' to XML...')

		SELECT @systemTypeId = s.system_type_id, @maxLength = s.max_length, @isSparse = s.is_sparse
		FROM sys.columns s WHERE s.object_id = OBJECT_ID(@tablename) AND s.[name] = @columnname

		IF @isSparse = 1 OR @sparse = 1
        	SET @sqlSparse = 'SPARSE'
        ELSE
			SET @sqlSparse = ''
        
		IF @debug = 1
			PRINT ('	isSparse = ' + CONVERT(VARCHAR, @isSparse))

		--varchar oder nvarchar die nicht max sind von kaputten einträgen bereinigen
		IF(@systemTypeId IN (167, 231) AND @maxLength <> -1) BEGIN
			PRINT('	Increasing size of ' + @tablename + '.' + @columnname + ' to MAX...')
			
			-- konvertieren in den passenden max, damit das replace platz hat
			IF @systemTypeId = 167 BEGIN
				SET @sql = 'ALTER TABLE [' + @tablename + '] ALTER COLUMN ['+@columnname + '] VARCHAR(MAX) ' + @sqlSparse + ' NULL'
			END ELSE BEGIN
				SET @sql = 'ALTER TABLE [' + @tablename + '] ALTER COLUMN ['+@columnname + '] NVARCHAR(MAX) ' + @sqlSparse + ' NULL'
			END

			IF @debug = 1
				PRINT @sql

			EXECUTE sp_executesql @sql

			IF @endTag = '' BEGIN
				SET @endTag = '>'
			END
		END

		IF (@endTag <> '') BEGIN
			PRINT('	Removing broken XML content from ' + @tablename + '.' + @columnname + '...')
			SET @sql = ('UPDATE ['+@tablename +'] SET ['+@columnname+'] = NULL WHERE ['+@columnname+'] IS NOT NULL AND NOT ['+@columnname+'] LIKE ''%'+ @endTag +'%''')
			
			IF @debug = 1
				PRINT @sql

			EXECUTE sp_executesql @sql
		END

		-- bei text und varchar das encoding der xml daten anpassen
		IF @systemTypeId IN (35, 167) BEGIN
			SELECT @collation = collation_name FROM sys.columns c WHERE c.name = @columnname AND c.object_id = OBJECT_ID(@tablename)
			SELECT @codePage = CONVERT(VARCHAR(4),COLLATIONPROPERTY( [name], 'CodePage')) FROM sys.fn_helpcollations() WHERE [name] = @collation
			PRINT('	Collation is ' + @collation)
			PRINT('	CodePage is ' + @codePage)
			PRINT('	Update ' + @tablename + '.' + @columnname + ' XML content to use different encoding...')

			SET @sql = 'UPDATE [' + @tablename + '] SET [' + @columnname + '] =  REPLACE(REPLACE(CONVERT(VARCHAR(MAX),['+@columnname +']),
			 ''<?xml version="1.0" encoding="utf-8"?>'',''<?xml version="1.0" encoding="windows-'+ @codepage +'"?>''),
			  ''<?xml version="1.0" encoding="utf-16"?>'',''<?xml version="1.0" encoding="windows-'+ @codepage +'"?>'')
			  WHERE NOT [' + @columnname+'] IS NULL'
		
			IF @debug = 1
				PRINT @sql
			
			EXECUTE sp_executesql @sql
		END ELSE BEGIN
			
			PRINT('	Update ' + @tablename + '.' + @columnname + ' XML content to use utf-16 encoding...')

			SET @sql = 'UPDATE [' + @tablename + '] SET [' + @columnname + '] =  REPLACE(CONVERT(NVARCHAR(MAX),['+@columnname +']),
			 ''<?xml version="1.0" encoding="utf-8"?>'',''<?xml version="1.0" encoding="utf-16"?>'')
			  WHERE NOT [' + @columnname+'] IS NULL'
		
			IF @debug = 1
				PRINT @sql
			
			EXECUTE sp_executesql @sql
		END
		
		PRINT('	Converting column to XML...')
		SET @sql = 'ALTER TABLE ['+@tablename +'] ALTER COLUMN ['+@columnname+'] XML ' + @sqlSparse + ' NULL'
		
		IF @debug = 1
			PRINT @sql
		
		EXECUTE sp_executesql @sql
	END
END
GO
--#endregion

--------------------- Ende HilfsProzeduren --------------------

--------------------- Begin Änderungsblock --------------------
--------------------- Scripterstelldatum : 13.02.2017 ---------
--------------------- Datenbankänderungen ab hier -------------
--------------------- möglichst mit regions umschließen -------

--#region ----------- 4.166.x Release Übertrag ----------------

--Änderungen aus CreateDb_2016.sql

--2017-02-20 sh
--#region Spalte InReport in Tabelle RapportSpalte (wurde versehentlich gelöscht)
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'InReport' and o.id = OBJECT_ID(N'[dbo].[RapportSpalte]'))
BEGIN
	ALTER TABLE dbo.RapportSpalte ADD InReport INT NOT NULL CONSTRAINT DF_RapportSpalte_InReport DEFAULT 0
END
GO
--#endregion

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[PersKatTechnik]'))	DROP VIEW [dbo].PersKatTechnik
GO

--#endregion (4.166.x Release Übertrag)

--#region ----------- 4.171.x ---------------------------------

--#region TK 20170209 Adressplan Settings
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 171 OR (Minor = 171 AND Build < 1)))))
BEGIN
	ALTER TABLE [Plan] ALTER COLUMN [Settings] NVARCHAR(MAX)
END
GO

 IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 171 OR (Minor = 171 AND Build < 1)))))
BEGIN
	EXEC('UPDATE [Plan] SET [Settings] =  REPLACE([plan].Settings, ''<?xml version="1.0" encoding="utf-8"?>'',''<?xml version="1.0" encoding="utf-16"?>'') FROM [PLAN] WHERE NOT [Settings] IS NULL')
	ALTER TABLE [Plan] ALTER COLUMN [Settings] XML NULL
	ALTER TABLE [AdressPlan] ALTER COLUMN [PlanSettings] XML NULL
END
GO

IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 171 OR (Minor = 171 AND Build < 1)))))
BEGIN
 
	UPDATE [plan] SET Settings.modify('replace value of (/DailyScheduleSettings/CellMargins/Right/text())[1] with "-1"') from [Plan] Where  planart = 130 and not  [plan].Settings is null   
	   AND  [plan].Settings.value('(/DailyScheduleSettings/CellMargins/Right)[1]',  'int') = 0

	UPDATE [plan] SET Settings.modify('replace value of (/ActivityPlanSettings/TableStyle/CellMargins/Right/text())[1] with "-1"') from [Plan] Where  planart = 30 and not  [plan].Settings is null   
	   AND  [plan].Settings.value('(/ActivityPlanSettings/TableStyle/CellMargins/Right)[1]',  'int') = 0

	UPDATE [plan] SET Settings.modify('replace value of (/MasterPlanSettings/TableStyle/CellMargins/Right/text())[1] with "-1"') from [Plan] Where  planart = 120 and not  [plan].Settings is null   
		AND  [plan].Settings.value('(/MasterPlanSettings/TableStyle/CellMargins/Right)[1]',  'int') = 0

	UPDATE [plan] SET Settings.modify('replace value of (/ProductionPlanSettings/TableStyle/CellMargins/Right/text())[1] with "-1"') from [Plan] Where  planart = 99 and not  [plan].Settings is null   
		AND  [plan].Settings.value('(/ProductionPlanSettings/TableStyle/CellMargins/Right)[1]',  'int') = 0

	UPDATE [plan] SET Settings.modify('replace value of (/CastAndPersStatusPlanSettings/TableStyle/CellMargins/Right/text())[1] with "-1"') from [Plan] Where  planart = 170 and not  [plan].Settings is null   
		AND  [plan].Settings.value('(/CastAndPersStatusPlanSettings/TableStyle/CellMargins/Right)[1]',  'int') = 0
		
    UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <SexFilter>female</SexFilter> into (/ts_DataAddressPlanSettings)[1]') WHERE NOT PlanSettings IS NULL AND  Geschlecht = 0
	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <SexFilter>male</SexFilter> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND Geschlecht = 1
	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <SexFilter>both</SexFilter> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND Geschlecht = 2

	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <GroupBy>ContactCategory</GroupBy> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND gruppieren = 1
	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <GroupBy>ContactCategorySortNo</GroupBy> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND gruppieren = 2
	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <GroupBy>Alphabetical</GroupBy> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND gruppieren = 3
	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <GroupBy>Workarea</GroupBy> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND gruppieren = 4
	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <GroupBy>None</GroupBy> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND gruppieren = 0

	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <FilterWithBirthday>true</FilterWithBirthday> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND FilterGeburtsdatum = 1

	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <FilterProductionteam>All</FilterProductionteam> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND Produktionsteam = 0
	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <FilterProductionteam>BasicCast</FilterProductionteam> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND Produktionsteam = -1
	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <FilterProductionteam>ActivityCast</FilterProductionteam> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND Produktionsteam = 1
	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <FilterProductionteam>ActorSeason</FilterProductionteam> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND Produktionsteam = 2
	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <FilterProductionteam>Contracts</FilterProductionteam> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND Produktionsteam = 3

	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <PageSettings><PaperKind>PaperKind.A4</PaperKind><LandScape>true</LandScape></PageSettings> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND QFormat = 1
	UPDATE [AdressPlan] SET  [PlanSettings].modify('insert <PageSettings><PaperKind>PaperKind.A4</PaperKind><LandScape>false</LandScape></PageSettings> into (/ts_DataAddressPlanSettings)[1]') WHERE  NOT PlanSettings IS NULL AND  (QFormat = 0 OR QFormat IS NULL)
END
GO
--#endregion TK 20170209 Adressplan Settings

--#region TK 20170227 Werk Rollenqualifikation
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[WorkVersionRoles_Qualifications]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.WorkVersionRoles_Qualifications(
		WorkVersionRoleQualificationId INT IDENTITY(1,1) NOT NULL,
		WorkVersionRoleId INT NOT NULL,
		QualificationId INT NOT NULL,		
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_WorkVersionRoles_Qualifications PRIMARY KEY NONCLUSTERED (WorkVersionRoleQualificationId) ON [PRIMARY],
		CONSTRAINT FK_WorkVersionRoles_Qualifications_Qualification FOREIGN KEY(QualificationId) REFERENCES Qualification (QualificationId),
		CONSTRAINT FK_WorkVersionRoles_Qualifications_WorkVersionRoles FOREIGN KEY(WorkVersionRoleId) REFERENCES WorkVersionRoles (WorkVersionRoleId),
	) ON [PRIMARY]

	CREATE UNIQUE NONCLUSTERED INDEX IX_WorkVersionRoles_Qualification_WorkVersionRoleId_QualificationId ON WorkVersionRoles_Qualifications (WorkVersionRoleId, QualificationId) ON [PRIMARY]
	CREATE CLUSTERED INDEX IX_WorkVersionRoles_Qualification_WorkVersionRoleId ON WorkVersionRoles_Qualifications (WorkVersionRoleId) ON [PRIMARY]
END
GO

GRANT SELECT ON WorkVersionRoles_Qualifications TO [public]
GRANT DELETE, INSERT, UPDATE ON WorkVersionRoles_Qualifications TO WorksWrite
GO
--#endregion TK 20170227 Werk Rollenqualifikation

--#region TK 20170309
GRANT DELETE, INSERT, UPDATE ON DienstplanArten_Update TO PersoAdmin
GRANT DELETE, INSERT, UPDATE ON DienstplanArten_Update TO DispoAdmin
GRANT DELETE, INSERT, UPDATE ON DienstplanArten_Update TO OrchesterAdmin
GRANT DELETE, INSERT, UPDATE ON DienstplanArten_Update TO ChorAdmin
GRANT DELETE, INSERT, UPDATE ON DienstplanArten_Update TO BallettAdmin

REVOKE DELETE, INSERT, UPDATE ON DienstplanArten TO PersoAdmin
REVOKE DELETE, INSERT, UPDATE ON DienstplanArten TO DispoAdmin
REVOKE DELETE, INSERT, UPDATE ON DienstplanArten TO OrchesterAdmin
REVOKE DELETE, INSERT, UPDATE ON DienstplanArten TO ChorAdmin
REVOKE DELETE, INSERT, UPDATE ON DienstplanArten TO BallettAdmin

GRANT DELETE, INSERT, UPDATE ON ABJahresabschluss_Update TO PersoAdmin
GRANT DELETE, INSERT, UPDATE ON ABJahresabschluss_Update TO DispoAdmin
GRANT DELETE, INSERT, UPDATE ON ABJahresabschluss_Update TO OrchesterAdmin
GRANT DELETE, INSERT, UPDATE ON ABJahresabschluss_Update TO ChorAdmin
GRANT DELETE, INSERT, UPDATE ON ABJahresabschluss_Update TO BallettAdmin

REVOKE DELETE, INSERT, UPDATE ON Jahresabschluss TO PersoAdmin
REVOKE DELETE, INSERT, UPDATE ON Jahresabschluss TO DispoAdmin
REVOKE DELETE, INSERT, UPDATE ON Jahresabschluss TO OrchesterAdmin
REVOKE DELETE, INSERT, UPDATE ON Jahresabschluss TO ChorAdmin
REVOKE DELETE, INSERT, UPDATE ON Jahresabschluss TO BallettAdmin
GO
--#endregion TK 20170309

--#region TK 20170314 Zeitkontenbudget
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.TimeAccountBudgets') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.TimeAccountBudgets(
		TimeAccountBudgetId INT IDENTITY(1,1) NOT NULL,
		YearCloseId INT NOT NULL,
		TimeAccountId INT NOT NULL,
		BudgetValue FLOAT NOT NULL CONSTRAINT DF_TimeAccountBudgets_BudgetValue DEFAULT 0,
		BudgetBase TINYINT  NOT NULL CONSTRAINT DF_TimeAccountBudgets_BudgetBase DEFAULT 0,
		Notes VARCHAR(1000) SPARSE NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_TimeAccountBudgets PRIMARY KEY NONCLUSTERED (TimeAccountBudgetId) ON [PRIMARY],
		CONSTRAINT FK_TimeAccountBudgets_YearCloses FOREIGN KEY(YearCloseId) REFERENCES Jahresabschluss (ID),
		CONSTRAINT FK_TimeAccountBudgets_TimeAccounts FOREIGN KEY(TimeAccountId) REFERENCES Zeitkonten (ZeitktoNr)
	) ON [PRIMARY]
	CREATE CLUSTERED INDEX IX_TimeAccountBudgets ON TimeAccountBudgets (TimeAccountId) ON [PRIMARY]
	CREATE UNIQUE INDEX IX_TimeAccountBudgets_YearClosesId_TimeAccountId_BudgetBase ON TimeAccountBudgets (YearCloseId, TimeAccountId, BudgetBase) ON [PRIMARY]
END
GO
GRANT SELECT ON TimeAccountBudgets TO [public]
GRANT DELETE, INSERT, UPDATE ON TimeAccountBudgets TO BudgetWrite
GO
--#endregion TK 20170314 Zeitkontenbudget

--#region TK 20170317 Abo Jahre für Produktionsprüfung
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CheckSeasonsCount' and o.id = OBJECT_ID(N'dbo.RingBez'))
BEGIN
	ALTER TABLE dbo.RingBez ADD CheckSeasonsCount TINYINT NOT NULL CONSTRAINT DF_Subscription_CheckSeasonsCount DEFAULT 0
	EXEC ('UPDATE RingBez SET CheckSeasonsCount =5 ')
END
GO
--#endregion

--#region TK 20170322 Description für Bestellpositionen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Notes' and o.id = OBJECT_ID(N'dbo.OrderPos'))
BEGIN
	ALTER TABLE dbo.OrderPos ADD Notes VARCHAR(1000) SPARSE NULL
END
GO
DropColumn 'OrderPos', 'Unity'
GO
--#endregion

--#region TK 20170323 Sollplan für Krankstunden
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'WorkingTimeForSickRank' and o.id = OBJECT_ID(N'dbo.DienstplanEintragArt'))
BEGIN
	ALTER TABLE dbo.DienstplanEintragArt ADD WorkingTimeForSickRank INT NULL
	EXEC ('UPDATE DienstplanEintragArt SET WorkingTimeForSickRank = 0 WHERE DienstplanEintragArtId = 1')
	ALTER TABLE dbo.DutyRosterPeriodStatus ADD IsSickCloseStatus  BIT NOT NULL  CONSTRAINT DF_DutyRosterPeriodStatus_IsSickCloseStatus DEFAULT 0
	EXEC ('UPDATE DutyRosterPeriodStatus SET IsSickCloseStatus = 1 WHERE IsClosedStatus = 1')
	ALTER TABLE dbo.AZTypen ADD WorktimeIgnoreWorkingPercentage  BIT NOT NULL  CONSTRAINT DF_AZTypen_WorktimeIgnoreWorkingPercentage DEFAULT 0
END
GO
--#endregion

--#region TK 20170324 DutyRosterPeriods eindeutig pro Abt/Periode
 IF EXISTS (SELECT * FROM dbo.sysobjects so LEFT JOIN dbo.syscomments sm ON sm.id = so.id
			WHERE so.id = OBJECT_ID(N'dbo.UQ_DutyRosterPeriods_DepartmentId_Start_End_LC') )
 BEGIN
	DELETE FROM DutyRosterPeriods WHERE DutyRosterPeriods.DutyRosterPeriodId NOT IN 
	(SELECT
		drp.DutyRosterPeriodId
			FROM DutyRosterPeriods drp
				JOIN (SELECT Start, [End], DepartmentId, MAX(LC) AS LC
							FROM DutyRosterPeriods
							GROUP BY	Start, [End],DepartmentId) AS LatestEntries

						ON drp.DepartmentId = LatestEntries.DepartmentId
					AND drp.Start = LatestEntries.Start
					AND drp.[End] = LatestEntries.[End]
					AND drp.LC = LatestEntries.LC)

	ALTER TABLE [dbo].[DutyRosterPeriods] DROP CONSTRAINT [UQ_DutyRosterPeriods_DepartmentId_Start_End_LC]
	CREATE UNIQUE NONCLUSTERED INDEX IQ_DutyRosterPeriods_DepartmentId_Start_End ON DutyRosterPeriods (DepartmentId, Start, [End]) ON [PRIMARY]

	ALTER TABLE dbo.DutyRosterPeriodStatus ADD IsReleasedStatus  BIT NOT NULL  CONSTRAINT DF_DutyRosterPeriodStatus_IsReleasedStatus DEFAULT 0
	EXEC ('UPDATE DutyRosterPeriodStatus SET IsReleasedStatus = 1 WHERE IsClosedStatus = 1')
	UPDATE UserGruppe SET OptionsFlag = OptionsFlag + 192 WHERE BerechtigungsbereichID = 5
END
GO
--#endregion

--#region TK 20170331 CountDownRoles
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CountDownRoles]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
Print 'Create CountDownRoles'
--DROP TABLE CountDownRoles
	CREATE TABLE CountDownRoles(
		CountDownRoleId INT IDENTITY(1,1) NOT NULL,
		CountDownId INT NOT NULL,
		RoleId INT NOT NULL,
		StartOffsetMinutes INT NOT NULL  CONSTRAINT DF_CountDownRoles_StartOffsetMinutes DEFAULT 0,
		EndOffsetMinutes INT NOT NULL  CONSTRAINT DF_CountDownRoles_EndOffsetMinutes DEFAULT 0,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_CountDownRolesId PRIMARY KEY NONCLUSTERED (CountDownRoleId) ON [PRIMARY],
		CONSTRAINT FK_CountDownRoles_CountDown FOREIGN KEY(CountDownId) REFERENCES CountDown (CountDownId),
		CONSTRAINT FK_CountDownRoles_Roles FOREIGN KEY(RoleId) REFERENCES BesetzungStd (Id),
	) ON [PRIMARY]

	CREATE CLUSTERED INDEX IX_CountDownRoles_CountDownId ON CountDownRoles (CountDownId) ON [PRIMARY]

	DELETE FROM  CountDown WHERE NOT SNR IS NULL AND NOT EXISTS (SELECT * FROM Stücke WHERE Stücke.SNr = CountDown.snr)

	UPDATE CountDown SET ForActivityTypeId = NULL WHERE ForActivityTypeId = 0
	DELETE FROM  CountDown WHERE NOT ForActivityTypeId IS NULL AND NOT EXISTS (SELECT * FROM AuffTypen WHERE AuffTypen.AuffTNr = ForActivityTypeId)

	
	DELETE FROM  CountDown WHERE NOT AufftNr IS NULL AND NOT EXISTS (SELECT * FROM AuffTypen WHERE AuffTypen.AuffTNr = CountDown.AufftNr)
	ALTER TABLE CountDown ALTER COLUMN Zrnr INT NULL
	UPDATE CountDown SET zrnr = NULL WHERE Zrnr = 0
	DELETE FROM  CountDown WHERE NOT ZrNr IS NULL AND NOT EXISTS (SELECT * FROM zr WHERE zr.zrnr = ZrNr)
	
	ALTER TABLE dbo.CountDown  WITH CHECK ADD  CONSTRAINT FK_CountDowns_Productions FOREIGN KEY(Snr)
	REFERENCES dbo.Stücke (Snr) ON DELETE CASCADE
	ALTER TABLE dbo.CountDown CHECK CONSTRAINT FK_CountDowns_Productions

	ALTER TABLE dbo.CountDown  WITH CHECK ADD  CONSTRAINT FK_CountDowns_Stages FOREIGN KEY(zrnr)
	REFERENCES dbo.Zr (zrnr) ON DELETE SET NULL
	ALTER TABLE dbo.CountDown CHECK CONSTRAINT FK_CountDowns_Stages

	ALTER TABLE dbo.CountDown  WITH CHECK ADD  CONSTRAINT FK_CountDowns_ActivityTyp FOREIGN KEY(AufftNr)
	REFERENCES dbo.AuffTypen (AuffTNr) ON DELETE CASCADE
	ALTER TABLE dbo.CountDown CHECK CONSTRAINT FK_CountDowns_ActivityTyp

END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.CountDownRoles_Update'))	DROP VIEW dbo.CountDownRoles_Update
GO
CREATE VIEW dbo.CountDownRoles_Update
		AS
	SELECT	CountDownRoles.*
	FROM	CountDownRoles
	WHERE EXISTS (
			SELECT * FROM BesetzungStd AS R
					INNER JOIN Gruppe AS G ON R.Besitzer = G.GruppeID
					INNER JOIN UserGruppe AS Ug ON G.GruppeID = Ug.GruppeID   
					INNER JOIN UserPW ON Ug.Userid  = UserPW.Userid 
					WHERE ug.BerechtigungsbereichID = 4 AND ug.Schreiben = 1  AND UserPW.Username = CURRENT_USER  AND R.ID = CountDownRoles.RoleId ) 
WITH CHECK OPTION
GO
GRANT SELECT,DELETE, INSERT, UPDATE ON CountDownRoles_Update TO [public]
GRANT SELECT ON CountDownRoles TO [public]
GO
--#endregion TK 20170227 Werk Rollenqualifikation

--#region TK 20170406 Secret Cast

ALTER PROCEDURE [dbo].[GetActivitiesInternal2]
	@start DATETIME,
	@end DATETIME,
	@condition VARCHAR(MAX),
	@order VARCHAR(MAX),
	@joins INT,
	@include INT,
	@userId INT,
	@ShowActivitiesWithoutRights BIT --AND Cast
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	
	SET NOCOUNT ON
	DECLARE @SQLQuery AS NVARCHAR(MAX)
	DECLARE @permissionPeriodStart DATETIME
	DECLARE @permissionPeriodEnd DATETIME

	-- *** Spielzeitberechtigungen prüfen ***
	SELECT @permissionPeriodStart = MIN(s.SpzStart), @permissionPeriodEnd = MAX(s.SpzEnde)
		FROM Spielzeittabelle AS s
			INNER JOIN UserForAccess AS us	ON s.spznr = us.spznr
		WHERE us.UserId = @userId AND s.SpzNr <> 0

	if (@permissionPeriodStart IS NULL)
		BEGIN 
			SELECT @start = '30000101'
			SELECT @end = '30000101'
		END
	ELSE
		BEGIN
			IF (@start < @permissionPeriodStart)	BEGIN SELECT @start = @permissionPeriodStart END
			IF (@end > @permissionPeriodEnd)		BEGIN SELECT @end = @permissionPeriodEnd END
		END

	-- *** Wenn weitere Daten mitgeladen werden Temp Tabelle mit  ActivityIds erstellen ***
	IF (@include <> 0)  CREATE TABLE #ActivitiesNP (ActivityId INT NOT NULL, NoPermission BIT NOT NULL)

	-- *** Berechtigungen des Users für Aktivitäten (2) und Besetzungen (4) in Temp Tabelle ***
	CREATE TABLE #Permissions (UserGruppeId INT NOT NULL, BerechtigungsbereichId INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #Permissions SELECT UserGruppe.GruppeId, UserGruppe.BerechtigungsbereichID, OptionsFlag  FROM UserGruppe WHERE UserId = @userId AND BerechtigungsbereichId IN (2,4)

	-- *** Spalten für ausgabe, wenn auch Daten ohne Berechtigungen geladen werden die ProduktionsId als 0 und keine Bemerkungen zurückgeben ***
	
	DECLARE @secretfields VARCHAR(MAX)
	DECLARE @fields VARCHAR(MAX)
	SET @fields  =', Aufführg.AuffNr, Aufführg.ZRNr,
					Aufführg.Datum, Aufführg.UhrBeg, Aufführg.UhrEnde, Aufführg.DiplaDru, Aufführg.VonZeit,  Aufführg.Pl, 
					Aufführg.Status, Aufführg.PreisNr, Aufführg.ZuAuffNr, Aufführg.Gesperrt, Aufführg.CreateCountDownId, 
					Aufführg.IsTimeSpan, Aufführg.IsExtraPayLiable, 
					Aufführg.LM, Aufführg.UM, Aufführg.LC, Aufführg.UC'


	-- *** Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben, ansonsten ActivityIds in Temp
	-- *** Die "@secretfields" müssen dann "@ShowActivitiesWithoutRights" abfragen
	if (@include <> 0) 
		BEGIN
			SET @SQLQuery = 'INSERT INTO #ActivitiesNP SELECT  Aufführg.AuffNr, CASE WHEN  Ug.UserGruppeId IS NULL OR (Aufführg.Gesperrt = 1 AND ug.OptionsFlag&1 <> 1)  THEN 1	ELSE 0 END'

			SET @secretfields  =       'CASE WHEN NoPermission = 1 THEN -100 ELSE Aufführg.SNr		END	AS SNr, 
										CASE WHEN NoPermission = 1 THEN 0	 ELSE Aufführg.Art		END	AS Art, 
										CASE WHEN NoPermission = 1 THEN NULL ELSE Aufführg.Bem		END	AS Bem,
										CASE WHEN NoPermission = 1 THEN NULL ELSE Aufführg.BemKurz	END AS BemKurz,
										CASE WHEN NoPermission = 1 THEN NULL ELSE Aufführg.BemKurz2 END AS BemKurz2'
		END
	ELSE
		BEGIN
			IF (@ShowActivitiesWithoutRights = 1) 
				
				SET @secretfields  =   'CASE WHEN Ug.UserGruppeId IS NULL OR (Aufführg.Gesperrt = 1 AND ug.OptionsFlag&1 <> 1) THEN -100 ELSE Aufführg.SNr		END	AS SNr, 
										CASE WHEN Ug.UserGruppeId IS NULL OR (Aufführg.Gesperrt = 1 AND ug.OptionsFlag&1 <> 1) THEN 0	 ELSE Aufführg.Art		END	AS Art, 
										CASE WHEN Ug.UserGruppeId IS NULL OR (Aufführg.Gesperrt = 1 AND ug.OptionsFlag&1 <> 1) THEN NULL ELSE Aufführg.Bem		END	AS Bem,
										CASE WHEN Ug.UserGruppeId IS NULL OR (Aufführg.Gesperrt = 1 AND ug.OptionsFlag&1 <> 1) THEN NULL ELSE Aufführg.BemKurz	END AS BemKurz,
										CASE WHEN Ug.UserGruppeId IS NULL OR (Aufführg.Gesperrt = 1 AND ug.OptionsFlag&1 <> 1) THEN NULL ELSE Aufführg.BemKurz2 END AS BemKurz2'
			ELSE 
				SET @secretfields  =   'Aufführg.SNr,
										Aufführg.Art, 
										Aufführg.Bem, 
										Aufführg.BemKurz, 
										Aufführg.BemKurz2'

		SET @SQLQuery = 'SELECT ' + @secretfields + @fields
		END

	-- ***	Immer auf Produktionen unf Berechtigungen ***
		SET @SQLQuery =  @SQLQuery + '	 FROM  AufführgTabelle AS Aufführg
										INNER JOIN  Stücke AS p ON Aufführg.snr = p.snr '

		IF (@ShowActivitiesWithoutRights = 1) 
			SET @SQLQuery =  @SQLQuery + 'LEFT JOIN #Permissions AS UG ON UG.UserGruppeId = P.ModuleGroupId AND ug.BerechtigungsbereichID = 2'
		ELSE 
			SET @SQLQuery =  @SQLQuery + 'INNER JOIN #Permissions AS UG ON UG.UserGruppeId = P.ModuleGroupId AND ug.BerechtigungsbereichID = 2'

	-- *** Weitere Joins ***	 
		IF (@joins&1 = 1) 
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN AufführgDetails ON Aufführg.Auffnr = AufführgDetails.AuffNr '

		IF (@joins&2 = 2) 
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN PresseText AS PT ON PT.AuffNr = Aufführg.AuffNr '
			--Wenn Abfrage direkt ausgeführt wird Felder für oder Joinen hinzufügen. Ggf auch bei Abfrge unten prüfen
		IF (@joins&4 = 4 OR (@include = 0 AND CHARINDEX('zr.', @order) > 0 )) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN Zr ON Aufführg.ZrNr = Zr.ZrNr '

		IF (@joins&8 = 8 OR (@include = 0 AND CHARINDEX('AuffTypen.', @order) > 0 )) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN AuffTypen ON Aufführg.Art = AuffTypen.AuffTNr '

		IF (@joins&16 = 16) 
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN StückeDetails ON Aufführg.Snr = StückeDetails.Snr '

		IF (@joins&32 = 32) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN Gruppe ON p.ModuleGroupId = Gruppe.GruppeID '
			
		SET @SQLQuery = @SQLQuery + ' WHERE Aufführg.Datum BETWEEN ''' + CAST(@start AS VARCHAR(MAX)) + '''  AND ''' + CAST(@end AS VARCHAR(MAX)) + ''''
		
			--Wenn in allen Besitzergruppe gesperrte Aktivitäten gelesen werden können ist keine Prüfung auf gesperrt erforderlich
		IF (EXISTS(SELECT * FROM #Permissions WHERE BerechtigungsbereichId = 2 AND OptionsFlag&1 <> 1)) 
		BEGIN
			
			IF (@ShowActivitiesWithoutRights = 0) 
					SET @SQLQuery = @SQLQuery  + ' AND (Aufführg.Gesperrt = 0 OR ug.OptionsFlag&1 = 1)'
		END

		 IF (@condition IS NOT NULL AND @condition <> '')
			 SET @SQLQuery = @SQLQuery + ' AND ' + @condition 

		if (@include = 0 AND @order IS NOT NULL) 
			SET @SQLQuery = @SQLQuery + @order 


		EXECUTE sp_Executesql @SQLQuery 
	
	IF (@include <> 0) --Wenn keine weiteren Daten mitgeladen werden wurde das Ergebnis bereits zurückgeben
		BEGIN
			SET @SQLQuery = 'SELECT '+ @secretfields+ @fields +' FROM Aufführgtabelle AS Aufführg 
																	INNER JOIN  #ActivitiesNP ON Aufführg.auffnr = #ActivitiesNP.ActivityId'

			If (@order IS NOT NULL)
			BEGIN
				--Prüfen ob Tabellen für Sortierungen gejoint werden müßen, ggf. auch bei Direktabfragen "@include =0" prüfen

				IF (CHARINDEX('zr.', @order) > 0) BEGIN
					SET @SQLQuery = @SQLQuery + ' INNER JOIN Zr ON Aufführg.ZrNr = Zr.ZrNr '
				END
				IF (CHARINDEX('Titel', @order) > 0) BEGIN
					SET @SQLQuery = @SQLQuery + ' INNER JOIN  Stücke AS p ON Aufführg.snr = p.snr '
				END
				IF (CHARINDEX('AuffTypen', @order) > 0) BEGIN
					SET @SQLQuery = @SQLQuery + ' INNER JOIN AuffTypen ON Aufführg.Art = AuffTypen.AuffTNr '
				END
				SET @SQLQuery = @SQLQuery + @order 

			END

			EXECUTE sp_Executesql  @SQLQuery

		END

-- *** Wenn Aktivitäten ohne Berechtigungen mitgeladen wurden für diese keine Abhängigen Daten laden
	IF (@ShowActivitiesWithoutRights = 1 AND @include <> 0) 
		DELETE FROM #ActivitiesNP WHERE NoPermission = 1

	IF (@include&1 = 1) 
		SELECT NULL AS [#1], AufführgDetails.* 
		FROM AufführgDetails 
			INNER JOIN #ActivitiesNP On AufführgDetails.AuffNr = #ActivitiesNP.ActivityId

	IF (@include&2 = 2) 
		SELECT NULL AS [#2], PresseText.* 
		FROM PresseText 
			INNER JOIN #ActivitiesNP ON PresseText.AuffNr = #ActivitiesNP.ActivityId

	IF (@include&4 = 4) 
		SELECT NULL AS [#4], Aufr.*, Ring.ZuAbo 
		FROM Aufr 
			INNER JOIN Ring ON AufR.AboNr = Ring.AboNr
			INNER JOIN #ActivitiesNP ON Aufr.AuffNr = #ActivitiesNP.ActivityId

	IF (@include&8 = 8) 
		SELECT NULL AS [#8], B.Id, B.RolleId, CASE WHEN B.Gesperrt = 1 AND ug.OptionsFlag&1 <> 1 THEN -1 ELSE b.PersNr END AS PersNr, B.AuffNr, B.DiffVon, B.DiffBis, B.BesBem, B.Druck, B.LM, B.UM, B.LC, B.UC, B.Gesperrt, B.BesSort, B.CastStatusId, 
					B.AgencyId, B.IsCover, B.IsCanceled, B.Creditable, B.BackColorArgb, B.IsReplacement, B.ContractId
		FROM BesetzungTabelle AS B 
			INNER JOIN #ActivitiesNP ON B.AuffNr = #ActivitiesNP.ActivityId
			INNER JOIN BesetzungStd ON BesetzungStd.Id = B.RolleID
			INNER JOIN #Permissions AS UG ON UG.UserGruppeId  = BesetzungStd.Besitzer AND  ug.BerechtigungsbereichID = 4 AND (@ShowActivitiesWithoutRights = 1 OR B.Gesperrt = 0 OR ug.OptionsFlag&1 = 1)	
			
	IF (@include&16 = 16) 
	BEGIN
		DECLARE @changeSince  DATETIME
		SET @changeSince = GETDATE() - 21 
		SELECT NULL AS [#16],ax.*
		FROM  XHDelAufführg AS ax
			INNER JOIN #ActivitiesNP ON ax.AuffNr = #ActivitiesNP.ActivityId
			LEFT JOIN (SELECT xhid FROM KenntnisDel WHERE tabl = 'Aufführg' AND uc = @userId) AS d ON ax.xhID = d.xhid 
		WHERE d.xhId IS NULL AND ax.uc <> @userId AND ax.lm >= @changeSince AND ax.xhRelevant = 1 
		ORDER BY ax.lc DESC
	END

	IF (@include&32 = 32) 
		SELECT NULL AS [#32], AuffDienstplanArten.* 
		FROM AuffDienstplanArten 
			INNER JOIN #ActivitiesNP ON AuffDienstplanArten.AuffNr = #ActivitiesNP.ActivityId
						
	IF (@include&256 = 256) 
		SELECT NULL AS [#256], ActivityScenes.* 
		FROM ActivityScenes 
			INNER JOIN #ActivitiesNP ON ActivityScenes.ActivityId = #ActivitiesNP.ActivityId
			
	IF (@include&512 = 512) 
		SELECT NULL AS [#512], AuffTechAufgabe.* 
		FROM AuffTechAufgabe 
			INNER JOIN #ActivitiesNP ON AuffTechAufgabe.AuffNr = #ActivitiesNP.ActivityId

		IF (@include <> 0) DROP TABLE #ActivitiesNP
END

GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetCastByActivityIdInternal2')) DROP PROCEDURE dbo.GetCastByActivityIdInternal2 
GO
CREATE PROCEDURE dbo.GetCastByActivityIdInternal2
	@ActivityId VARCHAR(MAX),
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@userId INT,
	@ShowCastWithoutRights BIT 
	WITH EXECUTE AS 'dbo'
AS
BEGIN

	SET NOCOUNT ON;
	DECLARE @SQLQuery AS NVARCHAR(MAX)

	if (@include <> 0)  CREATE TABLE #Cast (CastId INT NOT NULL, NoPermission BIT NOT NULL)

	CREATE TABLE #Permissions (UserGruppeId INT NOT NULL, BerechtigungsbereichId INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #Permissions SELECT UserGruppe.GruppeId, UserGruppe.BerechtigungsbereichID, OptionsFlag  FROM UserGruppe WHERE UserId = @userId AND BerechtigungsbereichId IN (1,4)


	DECLARE @fields VARCHAR(MAX) --<
	DECLARE @secretfields VARCHAR(MAX)
	SET @fields  = ', B.Id, B.RolleId, B.AuffNr, B.DiffVon, B.DiffBis, B.BesBem, B.Druck, B.LM, B.UM, B.LC, B.UC, B.Gesperrt, B.BesSort,  
					B.AgencyId, B.IsCover, B.IsCanceled, B.Creditable, B.BackColorArgb, B.IsReplacement'

	--Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben
	if (@include <> 0) 
		BEGIN
			SET @secretfields  =       'CASE WHEN NoPermission = 1 THEN -1 ELSE B.PersNr END AS PersNr,
									    CASE WHEN NoPermission = 1 THEN -1 ELSE B.ContractId END AS ContractId,
										CASE WHEN NoPermission = 1 THEN 0  ELSE B.CastStatusId END AS CastStatusId '

			SET @SQLQuery = 'INSERT INTO #Cast SELECT b.Id, CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN 1 ELSE 0 END '
		END	
	ELSE
		BEGIN
			SET @secretfields  =   'CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN -1 ELSE B.PersNr END AS PersNr,
									CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN -1 ELSE B.ContractId END AS ContractId,
									CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN  0 ELSE B.CastStatusId END AS CastStatusId '
			
			SET @SQLQuery = 'SELECT ' + @secretfields + @fields
		END		
				
		SET @SQLQuery =  @SQLQuery + '	 FROM  BesetzungTabelle AS B
											INNER JOIN BesetzungStd	AS ro ON b.RolleID = ro.ID
											LEFT JOIN #Permissions AS ugC ON ugC.UserGruppeId  = ro.Besitzer AND ugC.BerechtigungsbereichId = 4'
		
		IF (@joins&1 = 1) 
			SET @SQLQuery = @SQLQuery + 'INNER JOIN (SELECT * FROM ContractDates WHERE IsCanceled = 0) AS cd ON b.ID	= cd.CastID  '

		SET @SQLQuery = @SQLQuery + ' WHERE b.Auffnr IN (' + @ActivityId + ')'
		 
		
		IF (@ShowCastWithoutRights = 0) 
		BEGIN
			SET @SQLQuery = @SQLQuery  + ' AND (b.Gesperrt = 0 OR ugc.OptionsFlag&1 = 1)'
		END
		
		 IF (@condition IS NOT NULL  AND @condition <> '')
			 SET @SQLQuery = @SQLQuery + ' AND ' + @condition 

		EXECUTE sp_Executesql @SQLQuery 

	IF (@include <> 0) --Wenn keine weiteren Daten mitgeladen werden wurde das Ergebnis bereits zurückgeben
		BEGIN
			SET @SQLQuery = 'SELECT ' + @secretfields + @fields +' FROM BesetzungTabelle AS b 
														INNER JOIN  #Cast ON b.id = #cast.CastId'

			EXECUTE sp_Executesql  @SQLQuery
		END
	
	IF (@include&1 = 1) 
		SELECT NULL AS [#1], CastBonus.* 
		FROM CastBonus 
			INNER JOIN #Cast ON CastBonus.CastId = #Cast.CastId
	
	IF (@include&2 = 2) 
	BEGIN
    		-- contractdates mit berechtigung laden
		CREATE TABLE #ContractDates (ContractDateId INT NOT NULL, ReplacementContractDateId INT NULL)

		INSERT INTO #ContractDates (ContractDateId, ReplacementContractDateId)
			SELECT cd.ContractDateId, cd.ReplacementContractDateId FROM ContractDates cd
				INNER JOIN VertragRolle vr ON cd.ContractRoleId = vr.VRID
				INNER JOIN Vertrag v ON vr.VertragsNr = v.VertragsNr
				INNER JOIN #Permissions p ON p.BerechtigungsbereichId = 1 AND p.UserGruppeId = v.ModulGruppeID

		--abfrage über tabelle mit join auf die ids mit berechtigungen
		SELECT NULL AS [#2], cd.*, rcd_temp.ContractDateId AS ReplacedContractDateId 
			FROM ContractDates AS cd
				INNER JOIN #ContractDates cd_temp ON cd.ContractDateId = cd_temp.ContractDateId
				LEFT JOIN  #ContractDates rcd_temp ON cd.ContractDateId = rcd_temp.ReplacementContractDateId
				INNER JOIN #Cast ON cd.CastId = #Cast.CastId
				WHERE #Cast.NoPermission = 0
	END
END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetCastByActivityId2')) DROP PROCEDURE dbo.GetCastByActivityId2 
GO
CREATE PROCEDURE dbo.GetCastByActivityId2
	@ActivityId VARCHAR(MAX),
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowCastWithoutRights BIT 
AS
BEGIN

	SET NOCOUNT ON;
	DECLARE @userId INT
	SELECT @userId = UserId FROM UserPW WHERE UserName  = CURRENT_USER
	EXECUTE GetCastByActivityIdInternal2 @ActivityId, @condition, @joins, @include, @userId, @ShowCastWithoutRights
END
GO
GRANT EXECUTE ON GetCastByActivityId2 TO public

GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetCastByPeriodInternal2')) DROP PROCEDURE dbo.GetCastByPeriodInternal2 
GO
CREATE PROCEDURE dbo.GetCastByPeriodInternal2
	@start DATETIME,
	@end DATETIME,
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@userId INT,
	@ShowCastWithoutRights BIT 
	WITH EXECUTE AS 'dbo'
AS
BEGIN

	SET NOCOUNT ON;
	DECLARE @SQLQuery AS NVARCHAR(MAX)
	DECLARE @permissionPeriodStart DATETIME
	DECLARE @permissionPeriodEnd DATETIME

	SELECT @permissionPeriodStart = MIN(s.SpzStart), @permissionPeriodEnd = MAX(s.SpzEnde)
	FROM Spielzeittabelle AS s
		INNER JOIN UserForAccess AS us	ON s.spznr = us.spznr
	WHERE us.UserId = @userId AND s.SpzNr <> 0

	if (@permissionPeriodStart IS NULL)
		BEGIN 
			SELECT @start = '30000101'
			SELECT @end = '30000101'
		END
	ELSE
		BEGIN
			IF (@start < @permissionPeriodStart)	BEGIN SELECT @start = @permissionPeriodStart END
			IF (@end > @permissionPeriodEnd)		BEGIN SELECT @end = @permissionPeriodEnd END
		END

	if (@include <> 0)  CREATE TABLE #Cast (CastId INT NOT NULL, NoPermission BIT NOT NULL)

	CREATE TABLE #Permissions (UserGruppeId INT NOT NULL, BerechtigungsbereichId INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #Permissions SELECT UserGruppe.GruppeId, UserGruppe.BerechtigungsbereichID, OptionsFlag  FROM UserGruppe WHERE UserId = @userId AND BerechtigungsbereichId IN (1,2,4)


	DECLARE @fields VARCHAR(MAX)
	DECLARE @secretfields VARCHAR(MAX)
	SET @fields  = ', B.Id, B.RolleId, B.AuffNr, B.DiffVon, B.DiffBis, B.BesBem, B.Druck, B.LM, B.UM, B.LC, B.UC, B.Gesperrt, B.BesSort,
					B.AgencyId, B.IsCover, B.IsCanceled, B.Creditable, B.BackColorArgb, B.IsReplacement '

	--Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben
	if (@include <> 0) 
		BEGIN

			SET @secretfields  =       'CASE WHEN NoPermission = 1 THEN -1 ELSE B.PersNr END AS PersNr,
									    CASE WHEN NoPermission = 1 THEN -1 ELSE B.ContractId END AS ContractId,
										CASE WHEN NoPermission = 1 THEN 0  ELSE B.CastStatusId END AS CastStatusId '

			SET @SQLQuery = ' INSERT INTO #Cast SELECT b.Id, CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN 1 ELSE 0 END '
		END	
	ELSE
		BEGIN
			SET @secretfields  =   'CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN -1 ELSE B.PersNr END AS PersNr,
									CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN -1 ELSE B.ContractId END AS ContractId,
									CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN  0 ELSE B.CastStatusId END AS CastStatusId '
			SET @SQLQuery = 'SELECT ' + @secretfields + @fields
		END	
					
	 SET @SQLQuery =  @SQLQuery + 
	 'FROM  BesetzungTabelle		AS B
		INNER JOIN BesetzungStd		AS ro	ON b.RolleID = ro.ID
		INNER JOIN AufführgTabelle	AS A	ON B.AuffNr = A.Auffnr
		INNER JOIN Stücke			AS p	ON A.snr = p.snr
		INNER JOIN #Permissions		AS ugA	ON ugA.UserGruppeId  = P.ModuleGroupId AND ugA.BerechtigungsbereichID = 2
		LEFT JOIN #Permissions		AS ugC	ON ugC.UserGruppeId  = ro.Besitzer AND ugC.BerechtigungsbereichID = 4'
				 
		IF (@joins&1 = 1) 
			SET @SQLQuery = @SQLQuery + 'INNER JOIN (SELECT * FROM ContractDates WHERE IsCanceled = 0) AS cd ON b.ID = cd.CastID '	

		IF (@joins&4 = 4) 
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN StückeDetails ON A.Snr = StückeDetails.Snr '

		IF (@joins&8 = 8) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN AuffTypen AS AT ON A.art = AT.AufftNr '
			
		SET @SQLQuery = @SQLQuery + ' WHERE A.Datum BETWEEN ''' + CAST(@start AS VARCHAR(MAX)) + '''  AND ''' + CAST(@end AS VARCHAR(MAX)) + ''''
		 
		--Wenn in allen Besitzergruppe gesperrte Aktivitäten gelesen werden können ist keine Prüfung auf gesperrt erforderlich
		IF (EXISTS(SELECT * FROM #Permissions WHERE BerechtigungsbereichId = 2 AND OptionsFlag&1 <> 1)) 
		BEGIN
			SET @SQLQuery = @SQLQuery  + ' AND (a.Gesperrt = 0 OR uga.OptionsFlag&1 = 1)'
		END

		IF (@ShowCastWithoutRights = 0) 
		BEGIN
			SET @SQLQuery = @SQLQuery  + ' AND (b.Gesperrt = 0 OR ugc.OptionsFlag&1 = 1)'
		END

		 IF (@condition IS NOT NULL)
			 SET @SQLQuery = @SQLQuery + ' AND ' + @condition 

		EXECUTE sp_Executesql @SQLQuery 

	IF (@include <> 0) --Wenn keine weiteren Daten mitgeladen werden wurde das Ergebnis bereits zurückgeben
		BEGIN
			SET @SQLQuery = 'SELECT ' + @secretfields + @fields +' FROM BesetzungTabelle AS b 
														INNER JOIN  #Cast ON b.id = #cast.CastId'
		print @SQLQuery
			EXECUTE sp_Executesql  @SQLQuery
			
		END
		
	IF (@include&1 = 1) 
		SELECT NULL AS [#1], CastBonus.* 
		FROM CastBonus 
			INNER JOIN #Cast ON CastBonus.CastId = #Cast.CastId

	IF (@include&2 = 2) 
	BEGIN
    		-- contractdates mit berechtigung laden
		CREATE TABLE #ContractDates (ContractDateId INT NOT NULL, ReplacementContractDateId INT NULL)

		INSERT INTO #ContractDates (ContractDateId, ReplacementContractDateId)
		SELECT cd.ContractDateId, cd.ReplacementContractDateId FROM ContractDates cd
		INNER JOIN VertragRolle vr ON cd.ContractRoleId = vr.VRID
		INNER JOIN Vertrag v ON vr.VertragsNr = v.VertragsNr
		INNER JOIN #Permissions p ON p.BerechtigungsbereichId = 1 AND p.UserGruppeId = v.ModulGruppeID

		--abfrage über tabelle mit join auf die ids mit berechtigungen
		SELECT NULL AS [#2], cd.*, rcd_temp.ContractDateId AS ReplacedContractDateId 
		FROM ContractDates AS cd
		INNER JOIN #ContractDates cd_temp ON cd.ContractDateId = cd_temp.ContractDateId
		LEFT JOIN #ContractDates rcd_temp ON cd.ContractDateId = rcd_temp.ReplacementContractDateId
		INNER JOIN #Cast ON cd.CastId = #Cast.CastId
		WHERE #Cast.NoPermission = 0
	END
END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetCastByPeriod2')) 
	BEGIN DROP PROCEDURE dbo.GetCastByPeriod2  
END
GO
CREATE PROCEDURE dbo.GetCastByPeriod2
	@start DATETIME,
	@end DATETIME,
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowCastWithoutRights BIT 
AS
BEGIN

	SET NOCOUNT ON;
	DECLARE @userId INT
	SELECT @userId = UserId FROM UserPW WHERE UserName  = CURRENT_USER
	EXECUTE GetCastByPeriodInternal2 @start, @end, @condition, @joins, @include, @userId, @ShowCastWithoutRights

END
GO
GRANT EXECUTE ON GetCastByPeriod2 TO public
GO

ALTER VIEW [dbo].[AbBesetzungStdSoli]
	AS
	SELECT s.BesetzungStdSoliID, s.RolleId, s.SpzNr, s.BesSort, s.UnderstudyPosition,
		CASE WHEN (S.Gesperrt = 0 AND s.IsPerson1Locked = 0) OR (Ug.OptionsFlag&1 = 1) THEN s.PersNr1 ELSE -1 END AS PersNr1,
		CASE WHEN (S.Gesperrt = 0 AND s.IsPerson2Locked = 0) OR (Ug.OptionsFlag&1 = 1) THEN s.PersNr2 ELSE -1 END AS PersNr2,
		CASE WHEN (S.Gesperrt = 0 AND s.IsPerson3Locked = 0) OR (Ug.OptionsFlag&1 = 1) THEN s.PersNr3 ELSE -1 END AS PersNr3,
		CASE WHEN (S.Gesperrt = 0 AND s.IsPerson4Locked = 0) OR (Ug.OptionsFlag&1 = 1) THEN s.PersNr4 ELSE -1 END AS PersNr4,
		 s.Gesperrt, s.IsPerson1Locked, s.IsPerson2Locked, s.IsPerson3Locked, s.IsPerson4Locked,
		 s.Note, s.LM, s.UM, s.LC, s.UC

	FROM  BesetzungStdSoliTabelle AS S 
		INNER JOIN BesetzungStd AS R ON S.RolleID = R.Id
		INNER JOIN Gruppe AS G ON R.Besitzer = G.GruppeID
		LEFT JOIN (SELECT GruppeID, OptionsFlag 
					FROM  UserGruppe AS Ug 
						INNER JOIN UserPW ON Ug.Userid = UserPW.Userid 
					WHERE   BerechtigungsbereichID = 4 AND UserPW.Username = CURRENT_USER) AS ug 
			ON G.GruppeID = Ug.GruppeID  
				
GO
--#endregion

--#region DH 20170410 Kontaktmergeprozedur
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].MergeDoubletten'))
BEGIN
	DROP PROCEDURE dbo.MergeDoubletten 
END
go

CREATE PROCEDURE dbo.MergeDoubletten
	@PersId int, 
	@DoubletteId int
	WITH EXECUTE AS 'dbo'
AS
BEGIN

UPDATE Besetzungtabelle SET PersNr = @PersId WHERE PersNr = @DoubletteId
UPDATE BesetzungstdSoli  SET PersNr1 = @PersId WHERE PersNr1=@DoubletteId 
UPDATE BesetzungstdSoli  SET PersNr2 = @PersId WHERE PersNr2=@DoubletteId
UPDATE BesetzungstdSoli  SET PersNr3 = @PersId WHERE PersNr3=@DoubletteId 
UPDATE BesetzungstdSoli  SET PersNr4 = @PersId WHERE PersNr4=@DoubletteId 

UPDATE StatusZeitR   SET PersNr=@PersId WHERE PersNr=@DoubletteId
UPDATE Vertrag  SET PersNr=@PersId WHERE PersNr=@DoubletteId
UPDATE CashCommand  SET PersonId=@PersId WHERE PersonId=@DoubletteId
UPDATE PersAgentur  SET PersNr=@PersId WHERE PersNr=@DoubletteId
UPDATE PersAgentur  SET childPersNr=@PersId WHERE childPersNr=@DoubletteId
DELETE FROM BesRepertoire WHERE PersNr = @DoubletteId AND RolleID IN (SELECT RolleID FROM BesRepertoire WHERE PersNr = @PersId)
UPDATE BesRepertoire  SET PersNr=@PersId WHERE PersNr=@DoubletteId
UPDATE PersonalNotizen  SET PersNr=@PersId WHERE PersNr=@DoubletteId
UPDATE PersZusatzDaten  SET PersNr=@PersId  WHERE PersNr=@DoubletteId
IF EXISTS 
	(SELECT * 
	 FROM dbo.sysobjects 
	 WHERE id = OBJECT_ID('dbo.OrchBesetzung') AND OBJECTPROPERTY(id, 'IsUserTable') = 1)
Begin
	Delete from OrchBesetzung  WHERE PersNr=@DoubletteId
End
UPDATE Personal_Instrumente  SET PersNr=@PersId  WHERE PersNr=@DoubletteId
IF EXISTS 
	(SELECT * 
	 FROM dbo.sysobjects 
	 WHERE id = OBJECT_ID('dbo.Planstellen_Personal') AND OBJECTPROPERTY(id, 'IsUserTable') = 1)
Begin
	Delete from Planstellen_Personal  WHERE PersNr=@DoubletteId
End
UPDATE BodyMeasurements  SET PersonId=@PersId  WHERE PersonId=@DoubletteId
UPDATE PersZusatzDaten  SET PersNr=@PersId  WHERE PersNr=@DoubletteId
UPDATE Qualification_Person  SET PersonId=@PersId  WHERE PersonId=@DoubletteId
UPDATE XHDelBasicCast SET PersonNewId=@PersId WHERE PersonNewId=@DoubletteId

DELETE FROM BankAccount WHERE PersID = @DoubletteId
DELETE FROM PersonModulGroupPermission WHERE PersonId = @DoubletteId
DELETE FROM PersKom WHERE PersNr = @DoubletteId
DELETE FROM PersAdresse WHERE PersNr = @DoubletteId
--DELETE FROM PersMasse WHERE PersNr = @DoubletteId
DELETE FROM PersonalDetails WHERE Pnr = @DoubletteId
DELETE FROM PersonalHonorar WHERE PersNr = @DoubletteId
DELETE FROM Produktionsplan WHERE PNr = @DoubletteId
DELETE FROM PersEmployee WHERE PersonId = @DoubletteId
DELETE FROM PersH WHERE PersNr = @DoubletteId
END
GO
grant execute on MergeDoubletten to public
go

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[SOUNDEX_GER]'))
BEGIN
	DROP Function dbo.[SOUNDEX_GER] 
END
go

CREATE FUNCTION [dbo].[SOUNDEX_GER] (@strWord NVARCHAR(1000))
RETURNS NVARCHAR(1000) AS
BEGIN

DECLARE
       @Word NVARCHAR(1000),
       @WordLen int,
       @Code NVARCHAR(1000) = '',
       @PhoneticCode NVARCHAR(1000) = '',
       @index int,
       @RegEx NVARCHAR(50),
       @previousCharval nvarchar(1) = '|',
       @Charval nvarchar(1)

   SET @Word = lower(@strWord);
   IF len(@Word) < 1
      RETURN 0;

    ---- Umwandlung:
    ---- v->f, w->f, j->i, y->i, ph->f, ä->a, ö->o, ü->u, ß->ss, é->e, è->e, à->a, ç->c

  SET @Word = REPLACE(
                    REPLACE(
                            REPLACE(
                                    REPLACE(
                                            REPLACE(
                                                REPLACE(
                                                        REPLACE(
                                                                REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                    REPLACE(
                                                                                            REPLACE(
                                                                                                REPLACE(
                                                                                                        REPLACE(
                                                                                                                REPLACE(@Word,'v','f'),
                                                                                                        'w','f'),
                                                                                                'j','i'),
                                                                                            'y','i'),
                                                                                    'ä','a'),
                                                                            'ö','o'),
                                                                        'ü','u'),                                                                                                 
                                                                'é','e'),
                                                        'è','e'),
                                                'ê','e'),
                                            'à','a'),
                                    'á','a'),
                            'ç','c'),
                        'ph', 'f'),
                    'ß', 'ss');


      -- Zahlen und Sonderzeichen entfernen

       SET @RegEx = '%[^a-z]%';
       WHILE PatIndex(@RegEx, @Word) > 0
           SET @Word = Stuff(@Word, PatIndex(@RegEx, @Word), 1, '');


     -- Bei Strings der Länge 1 wird ein Leerzeichen angehängt, um die Anlautprüfung auf den zweiten Buchstaben zu ermöglichen.

    SET @WordLen = LEN(@Word);
    IF @WordLen = 1
        SET @Word += ' '; 

    -- Sonderfälle am Wortanfang

    IF (substring(@Word,1,1) = 'c')
   BEGIN
  -- vor a,h,k,l,o,q,r,u,x
            SET @Code =
                  CASE
                      WHEN substring(@Word,2,1) IN ('a','h','k','l','o','q','r','u','x')
                         THEN '4'
                         ELSE '8'
                   END;
           SET @index = 2
       END
   ELSE
      SET @index = 1;

	  
   -- Codierung    

   WHILE @index <= @WordLen
   BEGIN 
        SET @Code = 
           CASE
              WHEN substring(@Word,@index,1) in ('a','e','i','o','u')
                  THEN @Code + '0'
              WHEN substring(@Word,@index,1) = 'b'
                  THEN @Code + '1'
              WHEN substring(@Word,@index,1) = 'p'
                  THEN case 
						when ( @index < @WordLen ) 
							then case
								 when(substring(@Word,@index+1,1) = 'h')
									then @Code+'3'
								else @Code+'1' 
								End
							else @Code+'1'
					end
              WHEN substring(@Word,@index,1) in ('d','t')
                  THEN CASE 
						WHEN (@index < @WordLen)
							THEN CASE 
								WHEN (substring(@Word,@index+1,1) in ('c','s','z'))
								 THEN @Code+'8' ELSE @Code+'2'
								 END
							ELSE @Code+'2'
					END
              WHEN substring(@Word,@index,1) = 'f'
                  THEN @Code + '3'
              WHEN substring(@Word,@index,1) in ('g','k','q')
                  THEN @Code + '4'
              WHEN substring(@Word,@index,1) = 'c'
                  THEN 
					CASE WHEN (@index < @WordLen) 
						THEN CASE WHEN (substring(@Word,@index+1,1) in ('a','h','k','o','q','u','x'))
							THEN CASE WHEN (substring(@Word,@index-1,1) = 's' or substring(@Word,@index-1,1) = 'z') 
								THEN @Code+'8'
								ELSE @Code+'4' END
							ELSE @Code+'8' END
					ELSE @Code+'8' END
              WHEN substring(@Word,@index,1) = 'x'
                  THEN CASE WHEN (@index > 1) THEN CASE WHEN (substring(@Word,@index-1,1) in ('c','k','x')) 
						THEN @Code+'8' 
						ELSE @Code+'48'END 
					ELSE @Code+'48' END
              WHEN substring(@Word,@index,1) = 'l'
                  THEN @Code + '5'
              WHEN substring(@Word,@index,1) = 'm' or substring(@Word,@index,1) = 'n'
                  THEN @Code + '6'
              WHEN substring(@Word,@index,1) = 'r'
                  THEN @Code + '7'
              WHEN substring(@Word,@index,1) = 's' or substring(@Word,@index,1) = 'z'
                  THEN @Code + '8'
              ELSE @Code
         END;
         SET @index += 1;
     END


   -- die mehrfachen Codes entfernen und erst dann die „0'' eliminieren
   -- Am Wortanfang bleiben „0''-Codes erhalten

   SET @index = 0;
   WHILE @index < LEN(@code) 
   BEGIN 
      SET @charval = SUBSTRING(@code, @index+1, 1);
      IF @charval <> @previousCharval 
      BEGIN 
         IF @charval <> '0' OR @index = 0 
         BEGIN  
             SET @PhoneticCode += @charval;
         END   
     END 
     SET @previousCharval = @charval;
     SET @index += 1;
   END  
 RETURN @PhoneticCode;

 END;
 go
grant execute on dbo.[SOUNDEX_GER] to PUBLIC
GO
--#endregion

--#endregion (4.171.x)

--#region ----------- 4.171.x Release Übertrag ----------------

--#region TK 20170329 Adressplan

 UPDATE [AdressPlan] SET [PlanSettings] = '
<ts_DataAddressPlanSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <TableBorderStyle>None</TableBorderStyle>
  <TableBorderWidth>0</TableBorderWidth>
  <CellBorderStyle>None</CellBorderStyle>
  <CellBorderWidth>0</CellBorderWidth>
  <Sortings />
  <ActiveInactiveFilter>AllPersons</ActiveInactiveFilter>
  <ShowGenderFilter>false</ShowGenderFilter>
  <ShowContractTypeFilter>true</ShowContractTypeFilter>
  <ShowContactTypeFilter>true</ShowContactTypeFilter>
  <Modul>undef</Modul>
  <ContractTypeNodeNames />
  <OwnerGroups />
  <HideSecretComEntries>false</HideSecretComEntries>
  <FontInfo>
    <Size />
    <Bold>Default</Bold>
    <Italic>Default</Italic>
    <Underline>Default</Underline>
    <Capitalized>Default</Capitalized>
    <Strikeout>Default</Strikeout>
  </FontInfo>
  <NoDoublePersonInContractList>false</NoDoublePersonInContractList>
  <SexFilter>both</SexFilter>
  <GroupBy>None</GroupBy>
  <FilterProductionteam>' + CASE Produktionsteam WHEN -1 THEN 'BasicCast'  WHEN 1 THEN 'ActivityCast'  WHEN 2 THEN 'ActorSeason'  WHEN 3 THEN 'Contracts' ELSE 'ALL' END +  '</FilterProductionteam>
  <PageSettings>
    <PaperKind>PaperKind.A4</PaperKind>
    <LandScape>' + CASE WHEN QFormat = 1 THEN 'true' ELSE 'false' END + '</LandScape>
  </PageSettings>
</ts_DataAddressPlanSettings>' WHERE [PlanSettings] IS NULL
GO

IF NOT EXISTS (SELECT * FROM [PLAN] WHERE PlanArt = 200)
BEGIN
Print 'Import  Addressplan'
	SET IDENTITY_INSERT [PLAN] ON
	INSERT INTO [Plan] (PlanID, Bez, T1, Sort, OwnerId, PlanArt, Settings) 
		SELECT AdressPlanID + 10000, Bez, Kopf, CASE WHEN Sort> 250 THEN 250 ELSE Sort END, 1, 200, PlanSettings
			FROM AdressPlan
	SET IDENTITY_INSERT [PLAN] OFF

	SET IDENTITY_INSERT PlanSpalte ON
	INSERT INTO PlanSpalte (SpalteID, PlanID,Sort,Ueberschrift, Breite,ColumnSettings ) 
		SELECT AdressSpalteID + 10000, AdressSpalte.AdressPlanID + 10000, AdressSpalte.Sort, ub, Breite,CASE WHEN NOT Schrift IS NULL THEN '<?xml version="1.0" encoding="utf-16"?>
				<PlanSpalteSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IsColumnWithoutActivities="false" AllPersons="false" MergeRows="false" AppointmentSeperator="\n" VerticalAlign="Top" OrderByStage="false" FilterStyle="AdditionalPersons" Indention="0">
				  <PrintSum>false</PrintSum>
				  <FontInfo>
					<Size>' + cast(Schrift as varchar(10)) + '</Size>
					<Bold>Default</Bold>
					<Italic>Default</Italic>
					<Underline>Default</Underline>
					<Capitalized>Default</Capitalized>
					<Strikeout>Default</Strikeout>
				  </FontInfo>
				  <StagesFromXML>true</StagesFromXML>
				</PlanSpalteSettings>' ELSE NULL END
							FROM AdressSpalte 
								INNER JOIN AdressPlan ON AdressSpalte.AdressPlanID = AdressPlan.AdressPlanID
	SET IDENTITY_INSERT PlanSpalte OFF
	
	INSERT INTO PlanSort (SpalteID, Sort, ContentPath, ContentFormat, ContentSettings) 
		SELECT AdressAusgabe.AdressSpalteID + 10000, AdressSpalte.Sort, ContentPath, Composite, 		
						'<?xml version="1.0" encoding="utf-8"?>
				<PlanLayoutSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
				  <CharsContentAddicted>false</CharsContentAddicted>
				  <ConverterSettings>'+ Replace(Replace(CAST(ConverterSettings AS VARCHAR(MAX)),'>','&gt;'),'<','&lt;')+'</ConverterSettings>
				  <Font>
					<Bold>Default</Bold>
					<Italic>Default</Italic>
					<Underline>Default</Underline>
					<Capitalized>Default</Capitalized>
					<Strikeout>Default</Strikeout>
				  </Font>
				  <Condition />
				  <IsFooter>false</IsFooter>
				  <HorizontalAlignment>Left</HorizontalAlignment>
				</PlanLayoutSettings>' 
								FROM AdressAusgabe 
										INNER JOIN AdressSpalte ON AdressAusgabe.AdressSpalteID = AdressSpalte.AdressSpalteID 
										INNER JOIN AdressPlan ON AdressSpalte.AdressPlanID = AdressPlan.AdressPlanID
	--Im XML wurde PaperKind.A4 anstelle von nur A4 gesetzt
	UPDATE [plan] SET Settings.modify('replace value of (/ts_DataAddressPlanSettings/PageSettings/PaperKind/text())[1] with "A4"') 
		FROM [Plan] 
		WHERE  planart = 200 AND NOT [plan].Settings IS NULL
END
GO
--#endregion Adressplan

--#region TK 20170330
UPDATE ContractConfirmations SET Subject = REPLACE(Subject, 'Contract vom','Vertrag vom') WHERE NOT Subject IS NULL AND LC > '20170101' AND Subject LIKE '%Contract%'
UPDATE ContractConfirmations SET Subject = REPLACE(Subject, 'ContractCancelation vom','Vertragsauflösung vom') WHERE NOT Subject IS NULL AND LC > '20170101' AND Subject LIKE 'Contract%'
UPDATE ContractConfirmations SET Subject = REPLACE(Subject, 'ContractRequest vom','Vertragsanforderung vom') WHERE NOT Subject IS NULL AND LC > '20170101' AND Subject LIKE 'ContractCancelation%'
UPDATE ContractConfirmations SET Subject = REPLACE(Subject, 'DataConfirmation vom','Terminbestätigung vom') WHERE NOT Subject IS NULL AND LC > '20170101' AND Subject LIKE 'DataConfirmation%'
UPDATE ContractConfirmations SET Subject = REPLACE(Subject, 'NoDataConfirmation vom','Terminabsage vom') WHERE NOT Subject IS NULL AND LC > '20170101' AND Subject LIKE 'NoDataConfirmation%'
UPDATE ContractConfirmations SET Subject = REPLACE(Subject, 'PostponementDataConfirmation vom','Terminverschiebung vom') WHERE NOT Subject IS NULL AND LC > '20170101' AND Subject LIKE 'PostponementDataConfirmation%'
GO
--#endregion 

--#region DH 20170502
ALTER PROCEDURE [dbo].[GetMaxOrderNumber]
	@budgetPeriodId int,
	@OrderID int
	
	AS
	BEGIN    
		BEGIN TRY	
		SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
		SET XACT_ABORT ON
		BEGIN TRAN
		DECLARE @maxOrder INT ;
		SELECT @maxOrder = ISNULL(MAX(OrderNumber),0) FROM Orders  AS O
			INNER JOIN Budgets AS B ON B.BudgetId = O.BudgetId
			WHERE OrderNumber IS NOT NULL AND B.BudgetPeriodId = @budgetPeriodId;
	
		UPDATE Orders
			SET OrderNumber=@maxOrder +1
			WHERE Orderid=@OrderID;
		COMMIT Tran
		END TRY
		BEGIN CATCH
		IF @@TRANCOUNT>0 
			ROLLBACK TRAN
			SET @maxorder=-1
		END CATCH
		SET TRANSACTION ISOLATION LEVEL READ COMMITTED
		SELECT @maxOrder+1
	END
GO
--#endregion

--#region bm 20170502 Bugfix Spielplaneinstellungen werden u.U. nicht gespeichert.
IF EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID('dienstplanartentabelle') AND name = 'HeaderSettings' AND length = 2000)
BEGIN
	ALTER TABLE dienstplanartentabelle alter column HeaderSettings varchar(max) NULL
END
GO
--#endregion

--#endregion

--#region ----------- 4.172.x ---------------------------------
--#region DH 20170412 PublicOrders
IF EXISTS(SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID('[dbo].[AbPublicOrders]'))
BEGIN
	DROP VIEW [dbo].[AbPublicOrders]
END
GO
CREATE VIEW [dbo].[AbPublicOrders]
AS 
	select O.*,bp.Prefix as BudgetPrefix from Orders O Left join Budgets B on o.BudgetId=B.BudgetId left join BudgetPeriods bp on b.BudgetPeriodId=bp.BudgetPeriodId	
GO
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PublicOrders')
BEGIN
	EXEC sp_addrole @rolename = N'PublicOrders'
END
GO
GRANT SELECT ON [dbo].[AbPublicOrders] TO  PublicOrders
GO

IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[Orders]') AND o.Name = 'IX_Orders_CashfundID')
BEGIN
	CREATE NONCLUSTERED INDEX [IX_Orders_CashfundID]
	ON [dbo].[Orders] ([CashFundId])
	INCLUDE ([OrderId],[OrderDate],[OrderApprovalStatusId],[BudgetId],[CostTypeId],[CostCenterId],[CostUnitId],[BudgetItemId],[SupplierId],[OrderType],[SupplierAddress],[DeliveryAddress],[DelivaryUntilDate],[ConditionsOfPayment],[Note],[InternalNote],[CashDiscountPercent],[DiscountPercent],[CurrencyId],[CurrencyRate],[IsCanceled],[LM],[UM],[LC],[UC],[OrderNo],[QuoteNo],[QuoteDate],[OrderNumber],[CallOfTender],[PublicNote],[DeliveryStatus],[PaymentStatus],[IsConsistent],[NotPaid],[AccountancyPrintCount],[InvoiceFollows],[AccountancyPrintDate],[CorrectionStatus],[PaymentNote],[PayedAmount])
END
GO

--#endregion DH

--#region DH,20170421 Kurzname für Qualifikationen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ShortName' and o.id = OBJECT_ID(N'[dbo].[Qualification]'))
BEGIN
	Print 'Qualification  ShortName'
	ALTER TABLE Qualification Add ShortName varchar(15) 
END
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ShortName' and o.id = OBJECT_ID(N'[dbo].[Qualification]') AND c.length <> 15 ) -- Alte Spalte 
BEGIN
	ALTER TABLE Qualification ALTER COLUMN [ShortName] VARCHAR(15) 
END

GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ShortName' and o.id = OBJECT_ID(N'[dbo].[Qualification]')) AND EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 172 OR (Minor=172 AND Build <4)))))
	BEGIN
	Print ' UPDATE Qualifications'
		UPDATE Qualification 
			SET ShortName=rl.RolleKurz	
			FROM RollenLtg rl INNER JOIN Qualification ON rl.QualificationId=Qualification.QualificationId;

		UPDATE Qualification
		SET ShortName= LEFT([Name],4)
		WHERE ShortName is null;
		
		ALTER TABLE Qualification ALTER COLUMN [ShortName] VARCHAR(15) NOT NULL;
	END
--#endregion DH


--#region tk 20170608 Kalk. Honorar in Role_Seaon
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Fee' and o.id = OBJECT_ID(N'[dbo].[Role_Season]'))
BEGIN
	Print 'Role_Season Fee'
	ALTER TABLE Role_Season Add Fee MONEY NULL
	ALTER TABLE Role_Season Add OvernightFeeFlat MONEY NULL
	ALTER TABLE Role_Season Add TravelFeeFlat MONEY NULL
	ALTER TABLE Role_Season Add OvernightFeePerformance MONEY NULL
	ALTER TABLE Role_Season Add TravelFeePerformance MONEY NULL
	ALTER TABLE Role_Season Add EnsembleCount INT NULL CONSTRAINT DF_Role_Season_EnsembleCount DEFAULT 0 
	ALTER TABLE Role_Season Add FeeNote VARCHAR(1024)

	exec ('UPDATE Role_Season SET Role_Season.Fee = bc.Fee, Role_Season.OvernightFeeFlat = bc.OvernightFee, Role_Season.EnsembleCount = bc.EnsembleCount, Role_Season.FeeNote = bc.FeeNote   
		FROM BesetzungStdSoliTabelle AS bc 
				INNER JOIN Role_Season AS rs on bc.RolleID = rs.RoleId AND bc.SpzNr = rs.SeasonId 
		WHERE NOT bc.Fee IS NULL OR isnull(bc.EnsembleCount,0)>0')

exec ('INSERT INTO Role_Season (RoleId, SeasonId, Fee, OvernightFeeFlat, EnsembleCount, FeeNote, LC, UC, LM, UM) 
	SELECT DISTINCT bc.RolleID, bc.SpzNr, bc.Fee, bc.OvernightFee, bc.EnsembleCount,bc.FeeNote, ''19000101'', -1, ''19000101'', -1
	FROM BesetzungStdSoliTabelle AS bc  LEFT JOIN Role_Season AS rs ON bc.RolleID = rs.RoleId AND bc.SpzNr = rs.SeasonId  
WHERE bc.BesSort = 1 AND rs.Role_SeasonId IS NULL AND (NOT bc.Fee IS NULL OR  ISNULL(bc.EnsembleCount,0) > 0)')
END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbRole_Season'))	DROP VIEW dbo.AbRole_Season
GO

CREATE VIEW dbo.AbRole_Season
	AS
	SELECT      s.Role_SeasonId, s.RoleId, s.SeasonId, s.Note, s.LC, s.UC, s.LM, s.UM, s.RoleNotNeeded,
		CASE WHEN p.GruppeId IS NULL THEN -1 ELSE Fee END AS Fee,
		CASE WHEN p.GruppeId IS NULL THEN -1 ELSE OvernightFeeFlat END AS OvernightFeeFlat,
		CASE WHEN p.GruppeId IS NULL THEN -1 ELSE TravelFeeFlat END AS TravelFeeFlat,
		CASE WHEN p.GruppeId IS NULL THEN -1 ELSE OvernightFeePerformance END AS OvernightFeePerformance,
		CASE WHEN p.GruppeId IS NULL THEN -1 ELSE EnsembleCount END AS EnsembleCount,
		CASE WHEN p.GruppeId IS NULL THEN NULL ELSE FeeNote END AS TravelFeePerformance

	FROM        Role_Season AS S 
						INNER JOIN  BesetzungStd AS R ON s.RoleId = r.ID
						LEFT JOIN  ( SELECT ug.* FROM UserGruppe AS Ug  
										INNER JOIN UserPW ON Ug.Userid  = UserPW.Userid 	
										WHERE ug.BerechtigungsbereichID = 1 AND ug.Schreiben = 1  AND UserPW.Username = CURRENT_USER) AS p
						ON r.Besitzer = p.GruppeID  
GO

GRANT SELECT ON AbRole_Season TO [public]
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CalculationValue' and o.id = OBJECT_ID(N'[dbo].[Kosten_Stück]'))
BEGIN
	ALTER TABLE Kosten_Stück ALTER COLUMN BetragPlan MONEY NULL
	ALTER TABLE Kosten_Aufführg ALTER COLUMN BetragPlan MONEY NULL
	ALTER TABLE Kosten_Stück Add CalculationValue MONEY NULL
	ALTER TABLE Kosten_Aufführg Add CalculationValue MONEY NULL
	ALTER TABLE Kosten_Stück Add Note VARCHAR (1024) NULL
	ALTER TABLE Kosten_Aufführg Add Note VARCHAR (1024) NULL
END

--#endregion

--#endregion (4.172)

--#region ----------- 4.172.x Release Übertrag ----------------

--#region 2017-05-31 sh DF_Fahrplan_Diff
 IF NOT EXISTS (SELECT * FROM dbo.sysobjects so WHERE so.id = OBJECT_ID(N'[dbo].[DF_Fahrplan_Diff]'))
 BEGIN
	ALTER TABLE dbo.Fahrplan ADD CONSTRAINT DF_Fahrplan_Diff DEFAULT 0 FOR Diff
 END
 GO
--#endregion

--#region 2017-06-16 Wurde als NOT NULL angelegt
ALTER TABLE CountDown ALTER COLUMN AuffTNr INT NULL 
GO
--#endregion

--#endregion

--#region ----------- 4.173.x ---------------------------------

--#region DH 20170509 DutyEntryNoteColorSystem
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'NoteBackColor1' and o.id = OBJECT_ID(N'[dbo].[Dienstplan]'))
BEGIN
	Print 'Dienstplan Add NoteBackColor1'
	ALTER TABLE Dienstplan Add NoteBackColor1 int NOT NULL Constraint DF_Dienstplan_NoteBackColor1 Default 0 
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'NoteBackColor2' and o.id = OBJECT_ID(N'[dbo].[Dienstplan]'))
BEGIN
	Print 'Dienstplan Add NoteBackColor2'
	ALTER TABLE Dienstplan Add NoteBackColor2 int NOT NULL Constraint DF_Dienstplan_NoteBackColor2 Default 0  
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'NoteBackColor3' and o.id = OBJECT_ID(N'[dbo].[Dienstplan]'))
BEGIN
	Print 'Dienstplan Add NoteBackColor3'
	ALTER TABLE Dienstplan Add NoteBackColor3 int NOT NULL Constraint DF_Dienstplan_NoteBackColor3 Default 0 
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'NoteForeColor1' and o.id = OBJECT_ID(N'[dbo].[Dienstplan]'))
BEGIN
	Print 'Dienstplan Add NoteForeColor1'
	ALTER TABLE Dienstplan Add NoteForeColor1 int NOT NULL Constraint DF_Dienstplan_NoteForeColor1 Default 0 
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'NoteForeColor2' and o.id = OBJECT_ID(N'[dbo].[Dienstplan]'))
BEGIN
	Print 'Dienstplan Add NoteForeColor2'
	ALTER TABLE Dienstplan Add NoteForeColor2 int NOT NULL Constraint DF_Dienstplan_NoteForeColor2 Default 0  
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'NoteForeColor3' and o.id = OBJECT_ID(N'[dbo].[Dienstplan]'))
BEGIN
	Print 'Dienstplan Add NoteForeColor3'
	ALTER TABLE Dienstplan Add NoteForeColor3 int NOT NULL Constraint DF_Dienstplan_NoteForeColor3 Default 0 
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BackColor' and o.id = OBJECT_ID(N'[dbo].[VertragPerso]'))
BEGIN
	ALTER TABLE VertragPerso Add BackColor int NOT NULL Constraint DF_VertragPerso_BackColor Default 0 
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ForeColor' and o.id = OBJECT_ID(N'[dbo].[VertragPerso]'))
BEGIN
	ALTER TABLE VertragPerso Add ForeColor int NOT NULL Constraint DF_VertragPerso_ForeColor Default 0 
END
GO
--#endregion DutyEntryNoteColorSystem

--#region Rollenkurzbezeichnung erweitern
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'RolleKurz' and c.length=15   and o.id = OBJECT_ID(N'[dbo].[BesetzungStd]')) 
BEGIN
	ALTER TABLE [dbo].BesetzungStd ALTER COLUMN RolleKurz  NVARCHAR(150) NULL 
END
GO
--#endregion Rollenkurzbezeichnung erweitern

--#region StageDetails 20170609 DH
IF NOT EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TemplateName' and o.id = OBJECT_ID(N'[dbo].[RollenLtg]'))
BEGIN
	ALTER TABLE RollenLtg ADD TemplateName NVARCHAR(150) NULL
END
GO
UPDATE RollenLtg
	SET TemplateName=RolleKurz
	WHERE TemplateName is Null 
GO
IF NOT EXISTS 
	(SELECT * 
	 FROM dbo.sysobjects 
	 WHERE id = OBJECT_ID('dbo.StageDetails') AND OBJECTPROPERTY(id, 'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[StageDetails](
	[ZRNr] [int] NOT NULL,
	StageFlooringType int NULL,
	AuditoriumFlooringType int null,
	AuditoriumFloorFlatnessType int null,
	StageRoomType int null,
	[IsOpenAir] bit Constraint df_StageDetails_IsOpenAir  DEFAULT 0 NOT NULL,
	
	
	
	PreStageWidth Int Constraint df_StageDetails_PreStageWidth  DEFAULT 0 Not  NUll,
	PreStageHeight Int Constraint df_StageDetails_PreStageHeight  DEFAULT 0 Not  NUll,
	PreStageLength Int Constraint df_StageDetails_PreStageLength  DEFAULT 0 Not  NUll,
	
	StagePortalWidth Int Constraint df_StageDetails_StagePortalWidth  DEFAULT 0 Not  NUll,
	StagePortalHeight Int Constraint df_StageDetails_StagePortalHeight  DEFAULT 0 Not  NUll,
	StagePortalLength Int Constraint df_StageDetails_StagePortalLength  DEFAULT 0 Not  NUll,
	
	StageWidth Int Constraint df_StageDetails_StageWidth  DEFAULT 0 Not  NUll,
	StageHeight Int Constraint df_StageDetails_StageHeight  DEFAULT 0 Not  NUll,
	StageLength Int Constraint df_StageDetails_StageLength  DEFAULT 0 Not  NUll,
	StageGroundlevel Int Constraint df_StageDetails_StageGroundlevel  DEFAULT 0 Not  NUll, 
	StageRestrictions varchar(1000) NULL,
	StageAccess varchar(1000) NULL,
	StageNote varchar(1000) Null,
	StageElectricalConnection varchar(50) NULL,
	StageMapsExist BIT Constraint df_StageDetails_StageMapsExist  DEFAULT 0 NOT NULL,
	
	MinWidthStage Int Constraint df_StageDetails_MinWidthStage  DEFAULT 0 Not  NUll,
	MinHeightStage Int Constraint df_StageDetails_MinHeightStage  DEFAULT 0 Not  NUll,
	MinLengthStage Int Constraint df_StageDetails_MinLengthStage  DEFAULT 0 Not  NUll,
	
	AuditoriumWidth Int Constraint df_StageDetails_AuditoriumWidth  DEFAULT 0 Not  NUll,
	AuditoriumHeight Int Constraint df_StageDetails_AuditoriumHeight  DEFAULT 0 Not  NUll,
	AuditoriumLength Int Constraint df_StageDetails_AuditoriumLength  DEFAULT 0 Not  NUll,
	AuditoriumRestrictions varchar(1000) NULL,
	AuditoriumDistractions varchar(1000) null,
	AuditoriumNote varchar(1000) null,
	AuditoriumLightNote varchar(1000) null,
	AuditoriumSeatWidth int null,
	AuditoriumLightDimmable bit null,
	AuditoriumBlackOutPossible bit null,

	WardrobeStageAccess bit Constraint df_StageDetails_WardrobeStageAccess  DEFAULT 0 NOT NULL,
	WardrobeAuditoriumAccess bit Constraint df_StageDetails_WardrobeAuditoriumAccess  DEFAULT 0 NOT NULL,
	WardrobeNote varchar(1000) null,

	FoyerAvailable bit Constraint df_StageDetails_FoyerAvailable  DEFAULT 0 NOT NULL,
	FoyerNote varchar(1000),
	GeneralNote varchar(1000),
	CableReelNecessary BIT Constraint df_StageDetails_CableReelNecessary  DEFAULT 0 NOT NULL,
	TrolleyPossible BIT Constraint df_StageDetails_TrolleyPossible  DEFAULT 0 NOT NULL,	

	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,	
	CONSTRAINT [PK_ZRNR] PRIMARY KEY CLUSTERED ([ZRNr] ASC),
	CONSTRAINT [FK_StageDetails_ZR] FOREIGN KEY([ZRNr]) REFERENCES [dbo].[ZR] ([ZRNr]) on delete cascade)	
ON [PRIMARY]
END
GO

GRANT SELECT ON StageDetails TO [public]
GRANT DELETE, INSERT, UPDATE ON StageDetails TO dispoadmin
GO


--#endregion StageDetails

--#region TK 20170329 Adressplan
 UPDATE [AdressPlan] SET [PlanSettings] = '
<ts_DataAddressPlanSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <TableBorderStyle>None</TableBorderStyle>
  <TableBorderWidth>0</TableBorderWidth>
  <CellBorderStyle>None</CellBorderStyle>
  <CellBorderWidth>0</CellBorderWidth>
  <Sortings />
  <ActiveInactiveFilter>AllPersons</ActiveInactiveFilter>
  <ShowGenderFilter>false</ShowGenderFilter>
  <ShowContractTypeFilter>true</ShowContractTypeFilter>
  <ShowContactTypeFilter>true</ShowContactTypeFilter>
  <Modul>undef</Modul>
  <ContractTypeNodeNames />
  <OwnerGroups />
  <HideSecretComEntries>false</HideSecretComEntries>
  <FontInfo>
    <Size />
    <Bold>Default</Bold>
    <Italic>Default</Italic>
    <Underline>Default</Underline>
    <Capitalized>Default</Capitalized>
    <Strikeout>Default</Strikeout>
  </FontInfo>
  <NoDoublePersonInContractList>false</NoDoublePersonInContractList>
  <SexFilter>both</SexFilter>
  <GroupBy>None</GroupBy>
  <FilterProductionteam>' + CASE Produktionsteam WHEN -1 THEN 'BasicCast'  WHEN 1 THEN 'ActivityCast'  WHEN 2 THEN 'ActorSeason'  WHEN 3 THEN 'Contracts' ELSE 'ALL' END +  '</FilterProductionteam>
  <PageSettings>
    <PaperKind>PaperKind.A4</PaperKind>
    <LandScape>' + CASE WHEN QFormat = 1 THEN 'true' ELSE 'false' END + '</LandScape>
  </PageSettings>
</ts_DataAddressPlanSettings>' WHERE [PlanSettings] IS NULL


IF NOT EXISTS (SELECT * FROM [PLAN] WHERE PlanArt = 200)
BEGIN
	SET IDENTITY_INSERT [PLAN] ON
	INSERT INTO [Plan] (PlanID, Bez, T1, Sort, OwnerId, PlanArt, Settings) 
		SELECT AdressPlanID + 10000, Bez, Kopf, CASE WHEN Sort> 250 THEN 250 ELSE Sort END, 1, 200, PlanSettings
			FROM AdressPlan
	SET IDENTITY_INSERT [PLAN] OFF

	SET IDENTITY_INSERT PlanSpalte ON
	INSERT INTO PlanSpalte (SpalteID, PlanID,Sort,Ueberschrift, Breite,ColumnSettings ) 
		SELECT AdressSpalteID + 10000, AdressSpalte.AdressPlanID + 10000, AdressSpalte.Sort, ub, Breite,CASE WHEN NOT Schrift IS NULL THEN '<?xml version="1.0" encoding="utf-16"?>
				<PlanSpalteSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IsColumnWithoutActivities="false" AllPersons="false" MergeRows="false" AppointmentSeperator="\n" VerticalAlign="Top" OrderByStage="false" FilterStyle="AdditionalPersons" Indention="0">
				  <PrintSum>false</PrintSum>
				  <FontInfo>
					<Size>' + cast(Schrift as varchar(10)) + '</Size>
					<Bold>Default</Bold>
					<Italic>Default</Italic>
					<Underline>Default</Underline>
					<Capitalized>Default</Capitalized>
					<Strikeout>Default</Strikeout>
				  </FontInfo>
				  <StagesFromXML>true</StagesFromXML>
				</PlanSpalteSettings>' ELSE NULL END
							FROM AdressSpalte 
								INNER JOIN AdressPlan ON AdressSpalte.AdressPlanID = AdressPlan.AdressPlanID
	SET IDENTITY_INSERT PlanSpalte OFF
	
	INSERT INTO PlanSort (SpalteID, Sort, ContentPath, ContentFormat, ContentSettings) 
		SELECT AdressAusgabe.AdressSpalteID + 10000, AdressSpalte.Sort, ContentPath, Composite, 		
						'<?xml version="1.0" encoding="utf-8"?>
				<PlanLayoutSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
				  <CharsContentAddicted>false</CharsContentAddicted>
				  <ConverterSettings>'+ Replace(Replace(CAST(ConverterSettings AS VARCHAR(MAX)),'>','&gt;'),'<','&lt;')+'</ConverterSettings>
				  <Font>
					<Bold>Default</Bold>
					<Italic>Default</Italic>
					<Underline>Default</Underline>
					<Capitalized>Default</Capitalized>
					<Strikeout>Default</Strikeout>
				  </Font>
				  <Condition />
				  <IsFooter>false</IsFooter>
				  <HorizontalAlignment>Left</HorizontalAlignment>
				</PlanLayoutSettings>' 
								FROM AdressAusgabe 
										INNER JOIN AdressSpalte ON AdressAusgabe.AdressSpalteID = AdressSpalte.AdressSpalteID 
										INNER JOIN AdressPlan ON AdressSpalte.AdressPlanID = AdressPlan.AdressPlanID
	--Im XML wurde PaperKind.A4 anstelle von nur A4 gesetzt
	UPDATE [plan] SET Settings.modify('replace value of (/ts_DataAddressPlanSettings/PageSettings/PaperKind/text())[1] with "A4"') 
		FROM [Plan] 
		WHERE  planart = 200 AND NOT [plan].Settings IS NULL
END
GO
--#endregion Adressplan


--#region TK 20170330
UPDATE ContractConfirmations SET Subject = REPLACE(Subject, 'Contract vom','Vertrag vom') WHERE NOT Subject IS NULL AND LC > '20170101' AND Subject LIKE '%Contract%'
UPDATE ContractConfirmations SET Subject = REPLACE(Subject, 'ContractCancelation vom','Vertragsauflösung vom') WHERE NOT Subject IS NULL AND LC > '20170101' AND Subject LIKE 'Contract%'
UPDATE ContractConfirmations SET Subject = REPLACE(Subject, 'ContractRequest vom','Vertragsanforderung vom') WHERE NOT Subject IS NULL AND LC > '20170101' AND Subject LIKE 'ContractCancelation%'
UPDATE ContractConfirmations SET Subject = REPLACE(Subject, 'DataConfirmation vom','Terminbestätigung vom') WHERE NOT Subject IS NULL AND LC > '20170101' AND Subject LIKE 'DataConfirmation%'
UPDATE ContractConfirmations SET Subject = REPLACE(Subject, 'NoDataConfirmation vom','Terminabsage vom') WHERE NOT Subject IS NULL AND LC > '20170101' AND Subject LIKE 'NoDataConfirmation%'
UPDATE ContractConfirmations SET Subject = REPLACE(Subject, 'PostponementDataConfirmation vom','Terminverschiebung vom') WHERE NOT Subject IS NULL AND LC > '20170101' AND Subject LIKE 'PostponementDataConfirmation%'
GO
--#endregion

--#region DH 20170502
ALTER PROCEDURE [dbo].[GetMaxOrderNumber]
	@budgetPeriodId int,
	@OrderID int
	
	AS
	BEGIN    
		BEGIN TRY	
		SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
		SET XACT_ABORT ON
		BEGIN TRAN
		DECLARE @maxOrder INT ;
		SELECT @maxOrder = ISNULL(MAX(OrderNumber),0) FROM Orders  AS O
			INNER JOIN Budgets AS B ON B.BudgetId = O.BudgetId
			WHERE OrderNumber IS NOT NULL AND B.BudgetPeriodId = @budgetPeriodId;
	
		UPDATE Orders
			SET OrderNumber=@maxOrder +1
			WHERE Orderid=@OrderID;
		COMMIT Tran
		END TRY
		BEGIN CATCH
		IF @@TRANCOUNT>0 
			ROLLBACK TRAN
			SET @maxorder=-1
		END CATCH
		SET TRANSACTION ISOLATION LEVEL READ COMMITTED
		SELECT @maxOrder+1
	END
GO
--#endregion

--#region bm 20170502 Bugfix Spielplaneinstellungen werden u.U. nicht gespeichert.
IF EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID('dienstplanartentabelle') AND name = 'HeaderSettings' AND length = 2000)
BEGIN
	ALTER TABLE dienstplanartentabelle ALTER COLUMN HeaderSettings VARCHAR(MAX) NULL
END
GO
--#endregion

--#region tk 20170510 Pfad übertragen
 IF NOT EXISTS (  SELECT * FROM Settings WHERE Form = 'Path' AND Control = 'Templates'	)
	INSERT INTO Settings (Form, Control, WertText, LM, UM, LC, UC, IsGlobalSetting) SELECT 'Path','Templates',Pfade,LM, UM, LC, UC, 1 FROM AblagePfade WHERE PfadID = 1
GO
--#endregion

--#region TK 20170427 Settings auf VARCHAR(MAX)
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'WertText' AND o.id = OBJECT_ID(N'[dbo].Settings') AND c.prec <= 8000  AND c.prec > -1)
BEGIN	
	ALTER TABLE Settings ALTER COLUMN WertText VARCHAR(MAX)
END
GO
--#endregion

--#region TK 20170516
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DayOffCount' and o.id = OBJECT_ID(N'dbo.Dienstplan'))
BEGIN

--Relation AZTypen / DienstplanGruppen
	UPDATE AZTypen SET IsInactive = 1, DPGruppenID = null from AZTypen Where inDienstplan IS NULL  AND DPGruppenID NOT IN (SELECT DienstplanGruppen.DienstplanGruppenID FROM DienstplanGruppen)
	UPDATE AZTypen SET  DPGruppenID = null from AZTypen Where   DPGruppenID NOT IN (SELECT DienstplanGruppen.DienstplanGruppenID FROM DienstplanGruppen)

	ALTER TABLE dbo.AZTypen  WITH CHECK ADD  CONSTRAINT FK_ShiftTypes_DepartmentGroups FOREIGN KEY(DPGruppenID)
	REFERENCES dbo.DienstplanGruppen (DienstplanGruppenID) 
	ALTER TABLE dbo.AZTypen CHECK CONSTRAINT FK_ShiftTypes_DepartmentGroups
	
	ALTER TABLE Dienstplan ADD IsDayOffCountManual BIT NOT NULL CONSTRAINT DF_Dienstplan_IsDayOffCountManual DEFAULT 0
	ALTER TABLE Dienstplan ADD DayOffCount REAL NOT NULL CONSTRAINT DF_Dienstplan_DayOffCount DEFAULT 0
	
DECLARE @deactivateDayOffCountForPartialContractWeeks BIT
DECLARE @sql VARCHAR(MAX)
DECLARE @freeIds VARCHAR(MAX)
DECLARE @freeCountIds VARCHAR(MAX)

IF EXISTS (SELECT  settings from Zeitkonten  WHERE Formel = 3050 AND CONVERT(VARCHAR(MAX), Settings) LIKE '%<DeactivateDayOffCountingForPartialContractStartWeeks>true%')
	SET @deactivateDayOffCountForPartialContractWeeks = 1

 SELECT @freeIds = ISNULL((select (', ' + CAST(ZeitKtoNr AS VARCHAR(10))) FROM Zeitkonten WHERE Formel = 3050 for xml path ( '' )),'')

 SET @freeIds = '-1' + @freeIds
 SET @freeCountIds = ''

 IF EXISTS (SELECT  settings from Zeitkonten  WHERE Formel = 3050 AND CONVERT(VARCHAR(MAX), Settings) LIKE '%KontoKrank%')
	 SELECT @freeCountIds =  @freeCountIds + ISNULL((select (', ' + CAST(ZeitKtoNr AS VARCHAR(10))) FROM Zeitkonten WHERE Formel = 3011 for xml path ( '' )),'')

 IF EXISTS (SELECT  settings from Zeitkonten  WHERE Formel = 3050 AND CONVERT(VARCHAR(MAX), Settings) LIKE '%KontoUrlaub%')
	 SELECT @freeCountIds = @freeCountIds + ISNULL((select (', ' + CAST(ZeitKtoNr AS VARCHAR(10))) FROM Zeitkonten WHERE Formel = 3010 for xml path ( '' )),'')

 IF EXISTS (SELECT  settings from Zeitkonten  WHERE Formel = 3050 AND CONVERT(VARCHAR(MAX), Settings) LIKE '%KontoJubiläum%')
	 SELECT @freeCountIds = @freeCountIds + ISNULL((select (', ' + CAST(ZeitKtoNr AS VARCHAR(10))) FROM Zeitkonten WHERE Formel = 3013 for xml path ( '' )),'')
	 
 IF EXISTS (SELECT  settings from Zeitkonten  WHERE Formel = 3050 AND CONVERT(VARCHAR(MAX), Settings) LIKE '%Zeitkonto%')
	 SELECT @freeCountIds = @freeCountIds + ISNULL((select (', ' + CAST(ZeitKtoNr AS VARCHAR(10))) FROM Zeitkonten WHERE Formel = 3000 for xml path ( '' )),'')
	 	 
 IF EXISTS (SELECT  settings from Zeitkonten  WHERE Formel = 3050 AND CONVERT(VARCHAR(MAX), Settings) LIKE '%KontoMutterschutz%')
	 SELECT @freeCountIds = @freeCountIds + ISNULL((select (', ' + CAST(ZeitKtoNr AS VARCHAR(10))) FROM Zeitkonten WHERE Formel = 3018 for xml path ( '' )),'')

IF EXISTS (SELECT  settings from Zeitkonten  WHERE Formel = 3050 AND CONVERT(VARCHAR(MAX), Settings) LIKE '%KontoAKTageBerlin%')
	 SELECT @freeCountIds = @freeCountIds + ISNULL((select (', ' + CAST(ZeitKtoNr AS VARCHAR(10))) FROM Zeitkonten WHERE Formel = 3020 for xml path ( '' )),'')

IF EXISTS (SELECT  settings from Zeitkonten  WHERE Formel = 3050 AND CONVERT(VARCHAR(MAX), Settings) LIKE '%ShortFree%')
	 SELECT @freeCountIds = @freeCountIds + ISNULL((select (', ' + CAST(ZeitKtoNr AS VARCHAR(10))) FROM Zeitkonten WHERE Formel = 3051 for xml path ( '' )),'')
 SET @freeCountIds = '-1' + @freeCountIds

	SET @sql = 'UPDATE dienstplan SET DayOffCount = CASE 
					WHEN ((Azt1.ZeitktoNr IN (' + @freeIds + ') OR (Azt1.ZeitktoNr IN (' + @freeCountIds + ') AND AZ1 = 0)) OR AztNr1 = 0) AND 
						  ((Azt2.ZeitktoNr IN (' + @freeIds + ') OR (Azt2.ZeitktoNr IN (' + @freeCountIds + ') AND AZ2 = 0)) OR AztNr2 = 0) 
							AND
							V1 IS NULL AND V2 IS NULL AND V3 IS NULL Then 1 ELSE 0.5 END '
	SET @sql = @sql + '
					FROM  dienstplan as dp 
							INNER JOIN Aztypen AS azt1 ON dp.AztNr1 = azt1.AztNr
							INNER JOIN Aztypen AS azt2 ON dp.AztNr2 = azt2.AztNr' 
IF (@deactivateDayOffCountForPartialContractWeeks = 1) 
	SET @sql = @sql + ' INNER JOIN Vertrag AS v ON dp.VertragsNr = v.VertragsNr '
							
	SET @sql = @sql + ' 
					WHERE  (azt1.ZeitktoNr IN (' + @freeIds + ')  OR azt2.ZeitktoNr IN (' + @freeIds + ') 
							    OR (AZ1 = 0 AND azt1.ZeitktoNr IN (' + @freeCountIds + '))  
								OR (AZ2 = 0 AND azt2.ZeitktoNr IN (' + @freeCountIds + ')))'
							               

IF (@deactivateDayOffCountForPartialContractWeeks = 1) 
	SET @sql = @sql + ' AND dp.Datum >= (SELECT
									CASE
										WHEN v.vVon IS NULL OR v.VVon <= dp.Datum THEN dp.Datum --vertragsbeginn vor oder mit zeitraumsbeginn
										WHEN (((@@datefirst-1) + datepart(weekday, v.vVon)) % 7) = 1 THEN dp.datum --wochentag ist montag
										ELSE DATEADD(DAY, (DATEDIFF(DAY, 0, v.vVon) / 7) * 7 + 7, 0) --nächster montag
									END
							) '
exec (@sql)

END
GO
--#endregion

--#region Zusatzdaten

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ParentPersZusatzDatenId' and o.id = OBJECT_ID(N'[dbo].[PersZusatzDaten]'))
BEGIN
	ALTER TABLE PersZusatzDaten ADD ParentPersZusatzDatenId INT NULL
														
	ALTER TABLE PersZusatzDaten  WITH CHECK ADD  CONSTRAINT FK_PersZusatzDate_PersZusatzDate FOREIGN KEY(ParentPersZusatzDatenId)
	REFERENCES PersZusatzDaten (PersZusatzDatenId)
	ALTER TABLE PersZusatzDaten CHECK CONSTRAINT FK_PersZusatzDate_PersZusatzDate

	ALTER TABLE PersZusatzDatenTyp ADD ParentPersZDTypId INT NULL

	ALTER TABLE PersZusatzDatenTyp   WITH CHECK ADD  CONSTRAINT FK_PersZusatzDatenTyp_PersZusatzDatenTyp FOREIGN KEY(ParentPersZDTypId)
	REFERENCES PersZusatzDatenTyp (PersZDTypId)
	ALTER TABLE PersZusatzDatenTyp  CHECK CONSTRAINT FK_PersZusatzDatenTyp_PersZusatzDatenTyp
	IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[PersZusatzDatenTyp]') AND o.Name = 'UQ_PersZusatzDatenTyp_Bezeichnung')
	BEGIN
	DROP INDEX PersZusatzDatenTyp.UQ_PersZusatzDatenTyp_Bezeichnung
	END
	ALTER TABLE PersZusatzDatenTyp ADD Settings XML
END
go
--Alle mit Schreibrecht	
ALTER VIEW [dbo].[AbPersZusatzDaten_Update]
AS 		
SELECT zd.PersZusatzDatenID, zd.PersNr, zd.PersZDTypID, zd.ParentPersZusatzDatenId, zd.ZDText, zd.ZDInt, zd.ZDDate, zd.LM, zd.UM, zd.LC, zd.UC 
FROM			PersZusatzDaten				AS zd 
WHERE zd.PersZusatzDatenID  IN 
		(SELECT PersZusatzDatenID FROM PersZusatzDaten
			INNER JOIN	PersZusatzDatenTyp			AS zdt	ON zd.PersZDTypID = zdt.PersZDTypID
			LEFT  JOIN	PersonModulGroupPermission	AS gp	ON zd.PersNr = gp.PersonId
			INNER JOIN  UserGruppe					AS ug	ON zdt.Besitzer = ug.GruppeID
			INNER JOIN	UserPW								ON ug.Userid = UserPW.Userid 
		WHERE 
			ug.BerechtigungsbereichID = 0 AND UserPW.Username = current_user AND gp.HasWritePermission = 1 AND ug.Schreiben = 1 )
GO

--Alle nicht gesperrten und alle Kontakte auf die min. Kontaktdaten lesen
ALTER VIEW [dbo].[AbPersZusatzDaten]
AS 
SELECT PersZusatzDatenID, zd.PersNr, zd.PersZDTypID, zd.ParentPersZusatzDatenId, zd.ZDText, zd.ZDInt, zd.ZDDate, zd.LM, zd.UM, zd.LC, zd.UC 
FROM			PersZusatzDaten				AS zd 
WHERE zd.PersZusatzDatenID  IN 
		(SELECT PersZusatzDatenID FROM PersZusatzDaten
			INNER JOIN	PersZusatzDatenTyp			AS zdt	ON zd.PersZDTypID = zdt.PersZDTypID
			LEFT  JOIN	PersonModulGroupPermission	AS gp	ON zd.PersNr = gp.PersonId
			INNER JOIN  UserGruppe					AS ug	ON zdt.Besitzer = ug.GruppeID
			INNER JOIN	UserPW								ON ug.Userid = UserPW.Userid 
		WHERE 
			zdt.gesperrt = 0 OR 
			(ug.BerechtigungsbereichID = 0 AND UserPW.Username = current_user))
GO

ALTER VIEW [dbo].[AbPersZusatzDatenTyp]
AS 
 SELECT  PersZusatzDatenTyp.* 
 FROM  PersZusatzDatenTyp  LEFT  JOIN 
		(SELECT GruppeID 
		 FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		 WHERE  BerechtigungsbereichID=0 AND  Username = CURRENT_USER) UG ON (PersZusatzDatenTyp.Besitzer = UG.GruppeID )
WHERE PersZusatzDatenTyp.Gesperrt =0 or not  UG.GruppeID IS NULL
GO
--#endregion	
		
--#region tk 20170704 
IF NOT EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PrintName' and o.id = OBJECT_ID(N'[dbo].[Status]'))
BEGIN
	ALTER TABLE [Status] ADD PrintName VARCHAR(20) NULL
	ALTER TABLE [Status] ADD PrintCode VARCHAR(2) NULL
	UPDATE PersZusatzDatenTyp SET Bezeichnung = '--' WHERE Bezeichnung IS NULL
	ALTER TABLE PersZusatzDatenTyp ALTER COLUMN Bezeichnung VARCHAR(30) NOT NULL
END
GO
--#endregion 

--#region tk 20170703 
IF NOT EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsExportable' and o.id = OBJECT_ID(N'[dbo].[TourValidationStatus]'))
BEGIN
	ALTER TABLE TourValidationStatus ADD IsExportable BIT CONSTRAINT DF_TourValidationStatus_IsExportable NOT NULL DEFAULT  (0)
END
GO
--#endregion Exportable Tourstatus

--#region tk 20170706
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Settings' and o.id = OBJECT_ID(N'dbo.ContractFieldTypes'))
BEGIN
	EXECUTE PrepareUniqueColumnIndex N'PersZusatzDatenTyp',N'Bezeichnung',N'PersZDTypID',N'nvarchar(30)';
	CREATE UNIQUE NONCLUSTERED INDEX IX_PersZusatzDatenTyp_Name_ParentPersZDTypId ON PersZusatzDatenTyp (Bezeichnung, ParentPersZDTypId) ON [PRIMARY]
	ALTER TABLE ContractFieldTypes ADD Settings XML NULL
	ALTER TABLE ContractFieldTypes ADD GroupName VARCHAR(100) NULL
	ALTER TABLE ContractFieldTypes ALTER COLUMN NOTE VARCHAR(MAX)
END
GO
--#endregion

--#endregion (4.173.x)

--#region ----------- 4.173.x Release Übertrag ----------------

--#region 2017-08-28 sh BallettAdmin fehlende Stammdatenberechtigungen zuordnen
GRANT INSERT, UPDATE, DELETE ON AB TO BallettAdmin
GRANT INSERT, UPDATE, DELETE ON BonusDefaultAmounts TO BallettAdmin
GRANT INSERT, UPDATE, DELETE ON ContractType_Department TO BallettAdmin
GRANT INSERT, UPDATE, DELETE ON ContractTypes_ContractFieldTypes TO BallettAdmin
GRANT INSERT, UPDATE, DELETE ON ContractTypes_Templates TO BallettAdmin
GRANT INSERT, UPDATE, DELETE ON PersoParameter TO BallettAdmin
GRANT INSERT, UPDATE, DELETE ON ContractTrackingWorkflow TO BallettAdmin
GRANT INSERT, UPDATE, DELETE ON ContractTrackingFlowsheets TO BallettAdmin
GRANT INSERT, UPDATE, DELETE ON ActivityType_Update TO BallettAdmin, OrchesterAdmin, ChorAdmin
GRANT INSERT, UPDATE, DELETE ON DepartmentCollectives TO BallettAdmin
GO
--#endregion 2017-08-28 sh

--#region 20170830 bm Abteilungsbezogene Aktivitätsinformationen mit View-Berechtigungen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbAuffDienstplanArten'))	DROP VIEW [dbo].AbAuffDienstplanArten
GO

CREATE VIEW [dbo].AbAuffDienstplanArten
AS 
SELECT S.*
	FROM AuffDienstplanArten AS S 
	WHERE S.AuffDienstplanArtenID IN(
		SELECT S.AuffDienstplanArtenID FROM AuffDienstplanArten
		INNER JOIN DienstplanArtenTabelle AS a ON a.DienstplanArtenID = s.DienstplanArtenID 
		INNER JOIN Gruppe AS G ON a.ModulGruppeID = G.GruppeID
		INNER JOIN UserGruppe AS Ug ON G.GruppeID = Ug.GruppeID   
		INNER JOIN UserPW ON Ug.Userid  = UserPW.Userid 
		WHERE ug.BerechtigungsbereichID = 5 AND UserPW.Username = CURRENT_USER
		)
GO

GRANT SELECT,DELETE, INSERT, UPDATE ON AbAuffDienstplanArten TO [public]
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbAuffDienstplanArten_Update'))	DROP VIEW [dbo].AbAuffDienstplanArten_Update
GO

CREATE VIEW [dbo].AbAuffDienstplanArten_Update
AS 
SELECT S.*
	FROM AuffDienstplanArten AS S 
	WHERE S.AuffDienstplanArtenID IN(
		SELECT S.AuffDienstplanArtenID FROM AuffDienstplanArten
		INNER JOIN DienstplanArtenTabelle AS a ON a.DienstplanArtenID = s.DienstplanArtenID 
		INNER JOIN Gruppe AS G ON a.ModulGruppeID = G.GruppeID
		INNER JOIN UserGruppe AS Ug ON G.GruppeID = Ug.GruppeID   
		INNER JOIN UserPW ON Ug.Userid  = UserPW.Userid 
		WHERE ug.BerechtigungsbereichID = 5 AND ug.Schreiben = 1 AND UserPW.Username = CURRENT_USER
		)

	WITH CHECK OPTION
GO

GRANT SELECT,DELETE, INSERT, UPDATE ON AbAuffDienstplanArten_Update TO [public]
GO

REVOKE SELECT,DELETE, INSERT, UPDATE ON AuffDienstplanArten TO [public]
GO

-- Bugfix Orchester Arbeitsbereiche anlegen DH-20170920
GRANT DELETE, INSERT, UPDATE ON AB TO OrchesterAdmin
--#endregion

--#endregion

--#region ----------- 4.174.x ---------------------------------

--#region 2017-07-31 sh pressetext ändern für productions

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.[ProductionsDetails_Update]'))
	DROP VIEW dbo.[ProductionsDetails_Update]
GO

CREATE VIEW [dbo].[ProductionsDetails_Update]
AS 
SELECT * FROM StückeDetails WHERE Snr IN (
	SELECT p.SNr
	FROM UserGruppe ug
	INNER JOIN UserPW u ON ug.Userid = u.Userid
	INNER JOIN Stücke p ON p.ModuleGroupId = ug.GruppeID
	WHERE u.Username = CURRENT_USER
	      AND ug.BerechtigungsbereichID = 3
	      AND (ug.Schreiben = 1 OR ug.OptionsFlag & 1 = 1)
)
WITH CHECK OPTION
GO

GRANT SELECT, INSERT, UPDATE, DELETE ON [dbo].[ProductionsDetails_Update] TO [public]
GO

--Berechtigungen einmalig aktualisieren
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 174 OR (Minor=174 AND Build < 2)))))
BEGIN
	PRINT 'Updating Permissions to grant Write Presstext to users with write permission for productions...'
	UPDATE UserGruppe SET OptionsFlag = (Optionsflag | 1) WHERE BerechtigungsbereichID = 3 AND Schreiben = 1 AND (OptionsFlag & 1) <> 1
END
GO
--#endregion 2017-07-31 sh

--#region produktion für soliprobe umbenennen
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 174 OR (Minor=174 AND Build < 3)))))
BEGIN
	DECLARE @country VARCHAR(20)
	SELECT @country = WertText FROM Settings WHERE Form = 'Adresse' AND Control = 'Country'
	declare @title as varchar(100) = '#Soli-Probe#'
	IF @country = 'FI'
	BEGIN--Finnisch
		select @title = '#Sooloharjoitus#'
	END
	IF @country = 'EN'
	BEGIN--Englisch
		select @title = '#Soloist rehearsal#'
	END
	IF @country = 'F' OR @country = 'BE'
	BEGIN--Französisch
		select @title = '#Répétition soliste#'
	END
	IF @country = 'NL'
	BEGIN--Belgien
		select @title = '#Solirepetitie#'
	END
	UPDATE Stücke SET Titel = @title, OriginalTitel = @title WHERE SNr = -1
END
GO
--#endregion

--#region 2017-08-04 sh userfeatures und userfeaturedefaults
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.UserFeatures') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.UserFeatures (
		UserFeatureId INT IDENTITY(1,1) NOT NULL,
		UserId INT NOT NULL,
		FeatureId VARCHAR(100) NOT NULL,
		IsAvailable BIT NOT NULL CONSTRAINT DF_UserFeatures_IsAvailable DEFAULT 0,
		IsInherited BIT NOT NULL CONSTRAINT DF_UserFeatures_IsInherited DEFAULT 0,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_UserFeatures PRIMARY KEY NONCLUSTERED (UserFeatureId) ON [PRIMARY],
		CONSTRAINT FK_UserFeatures_UserPw FOREIGN KEY(UserId) REFERENCES UserPw (UserId),
	) ON [PRIMARY]
	CREATE CLUSTERED INDEX IX_UserFeatures_UserId ON UserFeatures (UserId) ON [PRIMARY]
	CREATE UNIQUE INDEX IX_UserFeatures_UserId_FeatureId ON UserFeatures (UserId, FeatureId) ON [PRIMARY]
END
GO
GRANT SELECT ON UserFeatures TO [public]
GRANT DELETE, INSERT, UPDATE ON UserFeatures TO SecurityAdmin
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.UserFeatureDefaults') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.UserFeatureDefaults (
		UserFeatureDefaultId INT IDENTITY(1,1) NOT NULL,
		UserId INT NOT NULL,
		IsAvailable BIT NOT NULL CONSTRAINT DF_UserFeatureDefaults_IsAvailable DEFAULT 0,
		IsInherited BIT NOT NULL CONSTRAINT DF_UserFeatureDefaults_IsInherited DEFAULT 0,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_UserFeatureDefaults PRIMARY KEY NONCLUSTERED (UserFeatureDefaultId) ON [PRIMARY],
		CONSTRAINT FK_UserFeatureDefaults_UserPw FOREIGN KEY(UserId) REFERENCES UserPw (UserId),
	) ON [PRIMARY]
	CREATE UNIQUE INDEX IX_UserFeatureDefaults_UserId ON UserFeatureDefaults (UserId) ON [PRIMARY]
END
GO
GRANT SELECT ON UserFeatureDefaults TO [public]
GRANT DELETE, INSERT, UPDATE ON UserFeatureDefaults TO SecurityAdmin
GO
--#endregion 2017-08-04 sh

--#region 2017-08 14 sh anpassung an der inherhit prozedure um userfeatures vererbung umzusetzen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[InherhitPermissions]'))
BEGIN
	DROP PROCEDURE dbo.[InherhitPermissions] 
END
GO
Print 'Create InherhitPermissions'
GO
-- =============================================
-- Author:			Torsten Klier
-- Create date:		2010 11 01
-- Modified date:	2011 01 24
--                  2015-03-26 sh temp table beim löschen entfernt, stattdessen usersingroups über temptabelle um alle abfragen zu beschleunigen
--                  2015-07-16 sh temp tabellen durch variablen ersetzt, ist für kleine daten besser
--                                neu anlegen von userpw eintrag hinzugefügt und auswertung bzgl windows gruppen
--                  2017-08-14 sh aufnahme von userfeatures und userfeaturesdefault in das skript, für die featureverwaltung
-- (Abteilungs-)Gruppenberechtigungen aus Datenbankrollen übernehmen
-- Wenn ein Recht aus mehreren Datenbankrollen geerbt wird, wird das "größte" übernommen 
-- =============================================
CREATE PROCEDURE [dbo].[InherhitPermissions]
AS
BEGIN   
	DECLARE @dbo BIT
	DECLARE @currentUserId INT
	DECLARE @authorizedByGroup BIT
	DECLARE @forAllUsers BIT
	
	SET @currentUserId = 0
	SET @authorizedByGroup = 0
	SET @forAllUsers = 0

	--daten für aktuellen benutzer abfragen, notfalls neu anlegen
	SELECT @currentUserId = UserId, @authorizedByGroup = IsAuthorizedByWindowsGroup FROM UserPw WHERE UserName = CURRENT_USER
	IF @currentUserId = 0 
	BEGIN
		EXEC AddCurrentUser
		SELECT @currentUserId = UserId, @authorizedByGroup = IsAuthorizedByWindowsGroup FROM UserPw WHERE UserName = CURRENT_USER
	END

	SELECT @dbo = IS_MEMBER('db_owner')
	IF @dbo = 0
		BEGIN
			Print 'User' +  cast(@currentUserId as Varchar(10))
		END  
	ELSE
		BEGIN
			SET @forAllUsers = 1
			Print 'All User'
		END

	--2015-03-26 sh
	--UsersInGroups in variable speichern, da im weiteren Verlauf viel damit gearbeitet wird und die abfragen ansonsten sehr langsam sind
	DECLARE @usersInGroups TABLE (GroupId INT, UserId INT)
	INSERT INTO @usersInGroups (GroupId, UserId)
	SELECT ugs.GroupId, ugs.UserId
	FROM UsersInGroups AS ugs

	--2015-07-16 sh
	--wenn über gruppe authorisiert, manuell benutzergruppenzugehörigkeit einfügen
	IF @authorizedByGroup = 1 
	BEGIN
		INSERT INTO @usersInGroups (GroupId, UserId)
		SELECT grp.UserID, @currentUserId
		FROM [sys].[database_principals] dp 
		INNER JOIN UserPw grp ON dp.name = grp.UserName
		WHERE dp.[type] = 'R' AND IS_MEMBER(dp.name) = 1 AND dp.name like '[_]%' 
		AND NOT EXISTS(SELECT * FROM @usersInGroups WHERE GroupId = grp.UserID AND UserId = @currentUserId)
	END

	--abfragedaten für alle benutzer die über windowsgruppen authorisiert wurden und ignoriert werden (aktueller benutzer ausgenommen)
	DECLARE @usersAuthorizedByGroup TABLE (userId INT)
	--füllen nur, wenn für alle benutzer berechtigungen erstellt werden
	IF @forAllUsers = 1
	BEGIN 
	   	INSERT INTO @usersAuthorizedByGroup
		SELECT up.UserID FROM UserPw up WHERE up.IsAuthorizedByWindowsGroup = 1 AND up.UserID <> @currentUserId
    END
	
	--neue Berechtigungen einfügen
	INSERT INTO UserGruppe (GruppeID, UserID, BerechtigungsbereichID, Schreiben, OptionsFlag, IsInherited, LM, UM, LC, UC)
	SELECT  soll.GruppeID, ugs.UserID, soll.BerechtigungsbereichID, CAST(COUNT(soll.Schreiben) AS BIT),
			 MAX(soll.OptionsFlag&1)+MAX(soll.OptionsFlag&2)+MAX(soll.OptionsFlag&4)+MAX(soll.OptionsFlag&8)+MAX(soll.OptionsFlag&16)
			 +MAX(soll.OptionsFlag&32)+MAX(soll.OptionsFlag&64)+MAX(soll.OptionsFlag&128)+MAX(soll.OptionsFlag&256)
			 +MAX(soll.OptionsFlag&512)+MAX(soll.OptionsFlag&1024), 1, MAX(soll.LM), MAX(soll.UM), MAX(soll.LC), MAX(soll.UC)
	FROM	@usersInGroups AS ugs 
		INNER JOIN	UserGruppe AS soll	ON ugs.GroupID = soll.UserID
		LEFT JOIN	UserGruppe AS ist	ON ugs.UserID = ist.UserID AND soll.GruppeID  = ist.GruppeID AND soll.BerechtigungsbereichID = ist.BerechtigungsbereichID
	WHERE  ist.UserGruppeID IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)
	GROUP BY soll.GruppeID, ugs.UserID, soll.BerechtigungsbereichID

	--Berechtigungen entfernen
	DELETE FROM UserGruppe 
	WHERE IsInherited = 1 
		AND (UserGruppe.UserId = @currentUserId OR @forAllUsers = 1)
		AND  UserGruppeID NOT IN 
				(
					SELECT  ist.UserGruppeID
					FROM			@usersInGroups AS ugs 
						INNER JOIN	UserGruppe AS soll		ON ugs.GroupId = soll.UserID
						INNER JOIN	UserGruppe as ist	ON ugs.UserID = ist.UserID AND soll.GruppeID  = ist.GruppeID AND soll.BerechtigungsbereichID = ist.BerechtigungsbereichID
				)
		AND (UserGruppe.UserID NOT IN (SELECT * FROM @usersAuthorizedByGroup))
	
	UPDATE UserGruppe SET UserGruppe.Schreiben = SollSchreiben, UserGruppe.OptionsFlag=SollOp
	FROM 
	(SELECT ugs.UserId, g.GruppeID, BerechtigungsbereichID, MAX(CAST(g.Schreiben AS INT)) AS SollSchreiben,
			 MAX(g.OptionsFlag&1)+MAX(g.OptionsFlag&2)+MAX(g.OptionsFlag&4)+MAX(g.OptionsFlag&8)+MAX(g.OptionsFlag&16)
			 +MAX(g.OptionsFlag&32)+MAX(g.OptionsFlag&64)+MAX(g.OptionsFlag&128)+MAX(g.OptionsFlag&256)
			 +MAX(g.OptionsFlag&512)+MAX(g.OptionsFlag&1024) AS SollOp 
		FROM @usersInGroups AS ugs 
			INNER JOIN UserGruppe AS G ON ugs.GroupId = G.UserID
		GROUP BY ugs.UserId , g.GruppeID, BerechtigungsbereichID) AS soll 
	INNER JOIN UserGruppe  ON 
			soll.UserId = UserGruppe.UserID AND 
			soll.GruppeID = UserGruppe.GruppeID AND 
			soll.BerechtigungsbereichID = UserGruppe.BerechtigungsbereichID
	WHERE
		(SollSchreiben <> UserGruppe.Schreiben OR SollOp <> UserGruppe.OptionsFlag)
		AND UserGruppe.IsInherited = 1
		AND (UserGruppe.UserId = @currentUserId OR @forAllUsers = 1)
		AND (UserGruppe.UserID NOT IN (SELECT * FROM @usersAuthorizedByGroup))	
	
	--Jeden User in Gruppe Kontaktdaten Jeder
	INSERT INTO UserGruppe(GruppeID ,UserID ,Schreiben, LM, UM, LC, UC, BerechtigungsbereichID, OptionsFlag)
	SELECT -1, UserPw.UserID, 0, GETDATE(), 0 ,GETDATE(), 0, 0, 0  
	FROM UserPw LEFT JOIN (SELECT * FROM UserGruppe WHERE BerechtigungsbereichID = 0 AND GruppeID = -1) AS UG on UserPW.UserID=UG.UserID WHERE UG.UserGruppeID IS NULL

	DELETE FROM UserGruppe WHERE BerechtigungsbereichID <> 0 AND GruppeID = -1
	
	INSERT INTO UserForAccess (SpzNr,UserID,IsInherited,LM,UM,LC,UC)
	SELECT DISTINCT soll.SpzNr, ugs.UserID, 1, GETDATE(), -1, GETDATE(), -1
	FROM	@usersInGroups AS ugs 
		INNER JOIN	UserForAccess AS soll	ON ugs.Groupid = soll.UserID
		LEFT JOIN	UserForAccess AS ist	ON ugs.UserID = ist.UserID AND soll.SpzNr=ist.SpzNr
	WHERE  ist.UserForAccessID IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)

	DELETE FROM UserForAccess 
	WHERE IsInherited = 1 AND  UserForAccessID NOT IN (
		SELECT      ist.UserForAccessID
		FROM        @usersInGroups          AS ugs
		INNER JOIN	UserForAccess soll      ON ugs.GroupId = soll.UserID
		INNER JOIN	UserForAccess ist       ON ugs.UserId = ist.UserID  AND soll.SpzNr=ist.SpzNr
	) AND (UserId = @currentUserId OR @forAllUsers = 1)
	AND (UserID NOT IN (SELECT * FROM @usersAuthorizedByGroup))

	--UserFeatures
	--Neue UserFeatures einfügen
	INSERT INTO UserFeatures (UserId, FeatureId, IsAvailable, IsInherited, LM, UM, LC, UC)
	SELECT ugs.UserId, soll.FeatureId, MAX(CAST(soll.IsAvailable AS INT)), 1, MAX(soll.LM), MAX(soll.UM), MAX(soll.LC), MAX(soll.UC)
	FROM @usersInGroups AS ugs 
		INNER JOIN UserFeatures AS soll ON ugs.GroupID = soll.UserID
		LEFT JOIN UserFeatures AS ist ON ugs.UserID = ist.UserID AND soll.FeatureId  = ist.FeatureId
	WHERE  ist.UserId IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)
	GROUP BY ugs.UserID, soll.FeatureId

	--Überflüssige UserFeatures entfernen
	DELETE FROM UserFeatures 
	WHERE IsInherited = 1 
		AND (UserFeatures.UserId = @currentUserId OR @forAllUsers = 1)
		AND UserFeatureId NOT IN 
				(
					SELECT  ist.UserFeatureId
					FROM			@usersInGroups AS ugs 
						INNER JOIN	UserFeatures AS soll ON ugs.GroupId = soll.UserID
						INNER JOIN	UserFeatures as ist ON ugs.UserID = ist.UserID AND soll.FeatureId  = ist.FeatureId
				)
		AND (UserFeatures.UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))
	
	--UserFeatures aktualisieren
	UPDATE UserFeatures SET UserFeatures.IsAvailable = SollIsAvailable
	FROM 
	(
		SELECT ugs.UserId, FeatureId, MAX(CAST(uf.IsAvailable AS INT)) AS SollIsAvailable
		FROM @usersInGroups AS ugs 
			INNER JOIN UserFeatures AS uf ON ugs.GroupId = uf.UserId
		GROUP BY ugs.UserId, uf.FeatureId
	) AS soll 
	INNER JOIN UserFeatures  ON 
			soll.UserId = UserFeatures.UserId AND 
			soll.FeatureId = UserFeatures.FeatureId
	WHERE
		SollIsAvailable <> UserFeatures.IsAvailable
		AND UserFeatures.IsInherited = 1
		AND (UserFeatures.UserId = @currentUserId OR @forAllUsers = 1)
		AND (UserFeatures.UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))

	--UserFeatureDefaults
	--Neue UserFeatureDefaults einfügen
	INSERT INTO UserFeatureDefaults (UserId, IsAvailable, IsInherited, LM, UM, LC, UC)
	SELECT ugs.UserId, MAX(CAST(soll.IsAvailable AS INT)), 1, MAX(soll.LM), MAX(soll.UM), MAX(soll.LC), MAX(soll.UC)
	FROM @usersInGroups AS ugs 
		INNER JOIN UserFeatureDefaults AS soll ON ugs.GroupID = soll.UserID
		LEFT JOIN UserFeatureDefaults AS ist ON ugs.UserID = ist.UserID
	WHERE  ist.UserId IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)
	GROUP BY ugs.UserID

	--Überflüssige UserFeatureDefaults entfernen
	DELETE FROM UserFeatureDefaults 
	WHERE IsInherited = 1 
		AND (UserFeatureDefaults.UserId = @currentUserId OR @forAllUsers = 1)
		AND UserFeatureDefaultId NOT IN 
				(
					SELECT  ist.UserFeatureDefaultId
					FROM			@usersInGroups AS ugs 
						INNER JOIN	UserFeatureDefaults AS soll ON ugs.GroupId = soll.UserID
						INNER JOIN	UserFeatureDefaults as ist ON ugs.UserID = ist.UserID
				)
		AND (UserFeatureDefaults.UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))
	
	--UserFeatureDefaults aktualisieren
	UPDATE UserFeatureDefaults SET UserFeatureDefaults.IsAvailable = SollIsAvailable
	FROM 
	(
		SELECT ugs.UserId, MAX(CAST(uf.IsAvailable AS INT)) AS SollIsAvailable
		FROM @usersInGroups AS ugs 
			INNER JOIN UserFeatureDefaults AS uf ON ugs.GroupId = uf.UserId
		GROUP BY ugs.UserId
	) AS soll 
	INNER JOIN UserFeatureDefaults  ON 
			soll.UserId = UserFeatureDefaults.UserId
	WHERE
		SollIsAvailable <> UserFeatureDefaults.IsAvailable
		AND UserFeatureDefaults.IsInherited = 1
		AND (UserFeatureDefaults.UserId = @currentUserId OR @forAllUsers = 1)
		AND (UserFeatureDefaults.UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))
END	
GO
GRANT EXECUTE ON InherhitPermissions TO Public
GO
--#endregion

--#region 20170810 Aufftypen
Print 'Drop AuffTypen....'
GO
DropColumn 'AuffTypen', 'Dienstplan'
GO
DropColumn 'AuffTypen', 'AuffTypenTS'
GO
DropColumn 'AuffTypen', 'defGruppeID'
GO
DropColumn 'AuffTypen', 'Probendauer'
GO
Print 'Drop RollenLtg....'
GO
DropColumn 'RollenLtg', 'RolleMann'
GO
DropColumn 'RollenLtg', 'RolleFrau'
GO
DropColumn 'RollenLtg', 'RollenLtgTS'
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_RollenLtg_Ab') AND type = 'F')
	ALTER TABLE [dbo].RollenLtg DROP CONSTRAINT [FK_RollenLtg_Ab]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.UQ_AuffTBez'))
ALTER TABLE dbo.AuffTypen DROP CONSTRAINT UQ_AuffTBez

GO
DropColumn 'RollenLtg', 'RollenLtgTS'
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'UseCountDownTypeId' and o.id = OBJECT_ID(N'dbo.AuffTypen'))

BEGIN
	Print 'AuffTypen ....UseCountDownTypeId'
	DROP INDEX IX_KatNr ON dbo.AuffTypen
	ALTER TABLE AuffTypen ALTER COLUMN KatNr SMALLINT NOT NULL
	CREATE  INDEX IX_KatNr ON dbo.AuffTypen (KatNr ASC) ON [PRIMARY]

	UPDATE AuffTypen SET AuffTKurz = '-?' WHERE AuffTKurz IS NULL
	ALTER TABLE AuffTypen ALTER COLUMN AuffTKurz VARCHAR(6) NOT NULL

	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[RollenLtg]') AND o.Name = 'PK_Rolle') DROP INDEX PK_Rolle ON dbo.RollenLtg
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[RollenLtg]') AND o.Name = 'Rolle') DROP INDEX Rolle ON dbo.RollenLtg
	ALTER TABLE RollenLtg ALTER COLUMN Rolle VARCHAR(150) NOT NULL
	CREATE NONCLUSTERED INDEX PK_Rolle ON dbo.RollenLtg	([Rolle] ASC) ON [PRIMARY]

	UPDATE RollenLtg SET PresseSort = 0 WHERE PresseSort IS NULL
	ALTER TABLE RollenLtg ALTER COLUMN Pos SMALLINT NOT NULL 

	UPDATE RollenLtg SET PresseSort = 0 WHERE PresseSort IS NULL
	ALTER TABLE RollenLtg ALTER COLUMN PresseSort SMALLINT NOT NULL 

	UPDATE RollenLtg SET Leporello = 0 WHERE Leporello IS NULL
	ALTER TABLE RollenLtg ALTER COLUMN Leporello SMALLINT NOT NULL 

	UPDATE RollenLtg SET TagesplanSpalte = 0 WHERE TagesplanSpalte IS NULL
	ALTER TABLE RollenLtg ALTER COLUMN TagesplanSpalte SMALLINT NOT NULL 

	EXEC ('UPDATE RollenLtg SET StdVs = 0 WHERE StdVs IS NULL')
	ALTER TABLE RollenLtg ALTER COLUMN StdVs TINYINT NOT NULL 

	EXEC ('UPDATE RollenLtg SET StdPro = 0 WHERE StdPro IS NULL')
	ALTER TABLE RollenLtg ALTER COLUMN StdPro BIT NOT NULL 

	UPDATE RollenLtg SET DruckStd = 0 WHERE DruckStd IS NULL
	ALTER TABLE RollenLtg ALTER COLUMN DruckStd TINYINT NOT NULL 

	ALTER TABLE RollenLtg ALTER COLUMN Rolle_EN VARCHAR(150) 
	ALTER TABLE RollenLtg ALTER COLUMN TemplateName VARCHAR(150)
		
	UPDATE AuffTypen SET AuffTBez = '-?' WHERE AuffTBez IS NULL
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.UQ_AuffTBez')) ALTER TABLE dbo.AuffTypen DROP CONSTRAINT UQ_AuffTBez
	ALTER TABLE AuffTypen ALTER COLUMN AuffTBez VARCHAR(30) NOT NULL
	ALTER TABLE dbo.AuffTypen ADD CONSTRAINT UQ_ActivityTypes_Name UNIQUE NONCLUSTERED  (AuffTBez ASC ) ON [PRIMARY]
	
	ALTER TABLE AuffTypen ADD UseCountDownTypeId INT NULL
	EXEC ('UPDATE AuffTypen SET UseCountDownTypeId = 0 WHERE KatNr = 0 OR (KatNr IN (1, -10) AND Merkmal = 1)')
	
	ALTER TABLE dbo.AuffTypen  WITH CHECK ADD  CONSTRAINT FK_ActivityTypes_CountDownTypes FOREIGN KEY(UseCountDownTypeId)
	REFERENCES dbo. CountDownArt (CountDownArtId) ON DELETE SET NULL
	ALTER TABLE dbo.AuffTypen CHECK CONSTRAINT FK_ActivityTypes_CountDownTypes
	
	ALTER TABLE AuffTypen ADD UseSetupTimes BIT NOT NULL CONSTRAINT DF_ActivityTypes_UseSetupTimes DEFAULT 0
	EXEC ('UPDATE AuffTypen SET UseSetupTimes = 1 WHERE KatNr = 0 OR (KatNr IN (1, -10) AND Merkmal = 1)')

	ALTER TABLE AuffTypen ADD CountAsStageRehearsal BIT NOT NULL CONSTRAINT DF_ActivityTypes_CountAsStageRehearsal DEFAULT 0
	EXEC ('UPDATE AuffTypen SET CountAsStageRehearsal = 1 WHERE KatNr = 1 AND Merkmal = 0')

	ALTER TABLE AuffTypen ADD UseJourneyTimetable BIT NOT NULL CONSTRAINT DF_ActivityTypes_UseJourneyTimetable DEFAULT 0
	EXEC ('UPDATE AuffTypen SET UseJourneyTimetable = 1 WHERE KatNr = 0 OR (KatNr IN (1, -10) AND Merkmal = 1)')

	ALTER TABLE BesetzungStd ADD AutoCast BIT NOT NULL CONSTRAINT DF_Role_AutoCast DEFAULT 0
	EXEC ('UPDATE BesetzungStd SET AutoCast = 1 WHERE StdVs = 2 OR StdPro = 1' )
	
	ALTER TABLE RollenLtg ADD TemplateAutoCast BIT NOT NULL CONSTRAINT DF_RoleGroup_TemplateAutoCast DEFAULT 0
	EXEC ('UPDATE RollenLtg SET TemplateAutoCast = 1 WHERE StdVs = 2 OR StdPro = 1' )
	Print 'Create ....RoleGroups_ActivityTypes'
	CREATE TABLE dbo.RoleGroups_ActivityTypes(
		RoleGroups_ActivityTypeId INT IDENTITY(1,1) NOT NULL,
		ActivityTypeId INT NOT NULL,
		RoleGroupId INT NOT NULL,	
		AutoCast BIT NOT NULL CONSTRAINT RoleGroups_ActivityTypes_AutoCast DEFAULT 0,	
		IsMandatory BIT NOT NULL CONSTRAINT RoleGroups_ActivityTypes_IsMandatory DEFAULT 0,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_RoleGroups_ActivityTypes PRIMARY KEY NONCLUSTERED (RoleGroups_ActivityTypeId) ON [PRIMARY],
		CONSTRAINT FK_RoleGroups_ActivityTypes_ActivityTypes FOREIGN KEY(ActivityTypeId) REFERENCES AuffTypen (AuffTNr) ON DELETE CASCADE,
		CONSTRAINT FK_RoleGroups_ActivityTypes_RoleGroup FOREIGN KEY(RoleGroupId) REFERENCES RollenLtg (RollenLtgId) ON DELETE CASCADE
	) ON [PRIMARY]

	CREATE UNIQUE NONCLUSTERED INDEX IX_RoleGroups_ActivityTypese_ActivityTypes_RoleGroup ON RoleGroups_ActivityTypes (ActivityTypeId, RoleGroupId) ON [PRIMARY]
	
	GRANT SELECT ON RoleGroups_ActivityTypes TO [public]
	GRANT DELETE, INSERT, UPDATE ON RoleGroups_ActivityTypes TO DispoAdmin
	GRANT DELETE, INSERT, UPDATE ON RoleGroups_ActivityTypes TO ChorAdmin
	GRANT DELETE, INSERT, UPDATE ON RoleGroups_ActivityTypes TO OrchesterAdmin
	GRANT DELETE, INSERT, UPDATE ON RoleGroups_ActivityTypes TO BallettAdmin

	--Für benötigte Aufgabenbereiche für Aktivitätstypen ermitteln 
	--Es wird das BAuto aus den Augbanenbereichen übertragen. 
	--Zusätzlich wird geprüft ab ein Aufgabenbereich in den letzen drei Jahren (1095 Tage) "vielen" Rollen gesetzt wurde. Viele sind ">10" 
	--delete  from RoleGroups_ActivityTypes
	EXEC ('INSERT INTO RoleGroups_ActivityTypes (ActivityTypeId, RoleGroupId, AutoCast,IsMandatory, LM, UM, LC, UC)
	SELECT  AuffTNr, RollenLtg.RollenLtgID,
	CASE WHEN  TagesplanSpalte >= 100 OR (
	 (KatNr = 0 AND (StdVs > 1 OR (SELECT COUNT(*) FROM BesetzungStd WHERE	BesetzungStd.RollenLtgID = RollenLtg.RollenLtgID AND 
																					BesetzungStd.StdVs = 2 AND 
																					BesetzungStd.LM > GETDATE()-1095)
								 >(SELECT COUNT(*) FROM BesetzungStd 	WHERE	BesetzungStd.RollenLtgID = RollenLtg.RollenLtgID AND 
																					BesetzungStd.LM > GETDATE()-1095)/2
	 ))  --VSt
					 	 OR (KatNr = 1 AND Merkmal = 1 AND (StdVs > 1 OR StdPro = 1 
									OR (SELECT COUNT(*) FROM BesetzungStd 	WHERE	BesetzungStd.RollenLtgID = RollenLtg.RollenLtgID AND 
																					BesetzungStd.StdPro = 1 AND 
																					BesetzungStd.LM > GETDATE()-1095) 
									> (SELECT COUNT(*) FROM BesetzungStd 	WHERE	BesetzungStd.RollenLtgID = RollenLtg.RollenLtgID AND 
																					BesetzungStd.LM > GETDATE()-1095) /2) )  --Endproben 
						 OR (KatNr = 1 AND Merkmal = 0 AND (StdPro = 1 
									OR (SELECT COUNT(*) FROM BesetzungStd WHERE	BesetzungStd.RollenLtgID = RollenLtg.RollenLtgID AND 
																					BesetzungStd.StdPro = 1 AND 
																					BesetzungStd.LM > GETDATE()-1095) 
									> (SELECT COUNT(*) FROM BesetzungStd WHERE	BesetzungStd.RollenLtgID = RollenLtg.RollenLtgID AND 
																					BesetzungStd.LM > GETDATE()-1095) / 2))  --Proben
	 
	) THEN 1 ELSE 0 END,CASE WHEN (TagesplanSpalte = 0  AND KatNr = 0)
					OR  (TagesplanSpalte = 100 AND (MitOrch = 1 OR KatNr = 0))
					OR (TagesplanSpalte = 110 AND (MitChor = 1 OR KatNr = 0))
					OR (TagesplanSpalte = 120 AND (MitBallett = 1 OR KatNr = 0))
					OR (TagesplanSpalte = 130 AND KatNr = 0)THEN 1 ELSE 0 END
	 
	 , GETDATE(), -1, GETDATE(), -1 
		FROM  RollenLtg CROSS JOIN AuffTypen 
		WHERE rollenltg.Module = 1 AND AuffTNr > 0 AND RollenLtgID >= 0  AND KatNr IN (-10,0,1)
		AND (
				(TagesplanSpalte < 100 AND 
					(
							(KatNr = 0 AND StdVs > 0)  --VSt
					 	 OR (KatNr = 1 AND Merkmal = 1)  --Endproben 
						 OR (KatNr = 1 AND Merkmal = 0 AND (TagesplanSpalte = 0 OR StdPro = 1 OR (SELECT COUNT(*) FROM BesetzungStd 
																			WHERE	BesetzungStd.RollenLtgID = RollenLtg.RollenLtgID AND 
																					StdPro = 1 AND 
																					LM > GETDATE()-1095) 
																			> 10))  --Proben
					)
				)	OR (TagesplanSpalte = 100 AND (MitOrch = 1 OR KatNr = 0))
					OR (TagesplanSpalte = 110 AND (MitChor = 1 OR KatNr = 0))
					OR (TagesplanSpalte = 120 AND (MitBallett = 1 OR KatNr = 0))
					OR (TagesplanSpalte = 130 AND KatNr = 0)
			)')

END


go
--#endregion

--#region 20170830 TK  doppelte Formel eFormula_CashValue umgeschrieben 
Print 'CashValue...'
UPDATE Zeitkonten SET Formel = 1350 , Settings = '<?xml version="1.0" encoding="utf-8"?>  <CalculatedSalaryOfDaySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">    <OnlyPresentTime>true</OnlyPresentTime>    <RoundUp>true</RoundUp>  </CalculatedSalaryOfDaySettings>'
WHERE Formel = 10
GO
--#endregion

--#region 20170920 TK Function zum Abschneiden des Logs ab einem Datum
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].TruncateUpdateLog'))DROP PROCEDURE dbo.TruncateUpdateLog 
GO
CREATE PROCEDURE dbo.TruncateUpdateLog
	@fromDate DATETIME 
AS
BEGIN
	BEGIN TRY

		BEGIN TRANSACTION;
		DECLARE @treuncatedrows INT
		SELECT @treuncatedrows = Count(*) FROM updateLog WHERE LC <= @fromDate
		IF (@treuncatedrows < 10000)
		BEGIN
			DELETE FROM dbo.updateLog WHERE LC <= @fromDate
		END
		ELSE
		BEGIN
			CREATE TABLE [#updateLogTEMP](
				[updateLogID] INT NOT NULL,
				[WinUser] VARCHAR(100) NOT NULL,
				[LogText] VARCHAR(MAX) NOT NULL,
				[LogArt] TINYINT NOT NULL,
				[LC] DATETIME NULL,
				[UC] INT NULL,
				[Logtable] VARCHAR(100) NOT NULL,
				[PKValue] INT NULL,
				[PKField] VARCHAR(100) NULL,
				[TransactionId] INT NULL)
			
			INSERT INTO [#updateLogTEMP]([updateLogID],[WinUser],[LogText],[LogArt],[LC],[UC],[Logtable],[PKValue],[PKField],[TransactionId])
			SELECT						 [updateLogID],[WinUser],[LogText],[LogArt],[LC],[UC],[Logtable],[PKValue],[PKField],[TransactionId]
			FROM [dbo].[updateLog] WHERE [LC] > @fromDate

			TRUNCATE TABLE [updateLog]
			
			SET IDENTITY_INSERT [updateLog] ON
				INSERT INTO [updateLog]  ([updateLogID],[WinUser],[LogText],[LogArt],[LC],[UC],[Logtable],[PKValue],[PKField],[TransactionId])
				SELECT					[updateLogID],[WinUser],[LogText],[LogArt],[LC],[UC],[Logtable],[PKValue],[PKField],[TransactionId]
				FROM [dbo].[#updateLogTEMP] 
			SET IDENTITY_INSERT [updateLog] OFF
		
			DROP TABLE [#updateLogTEMP]
		END
		 COMMIT TRANSACTION;
	Print  'Truncated rows ' + Cast( @treuncatedrows AS VARCHAR(100))
	END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION;
		Print 'Error'
	END CATCH;
END

GO
print 'TruncateUpdateLog...'
DECLARE @fromDate DATETIME
SELECT @fromDate = GETDATE()-1095
EXEC TruncateUpdateLog @fromDate
GO
--#endregion

--#region 20170920 TK updateLog Datentypen
Print 'updateLog...WinUser'
ALTER TABLE [updateLog]  ALTER COLUMN [WinUser] VARCHAR(100) NOT NULL
Print 'updateLog...LogText'
ALTER TABLE [updateLog]  ALTER COLUMN [LogText] VARCHAR(MAX) NOT NULL
Print 'updateLog...LogArt'
ALTER TABLE [updateLog]  ALTER COLUMN [LogArt] TINYINT NOT NULL
Print 'updateLog...Logtable'
ALTER TABLE [updateLog]  ALTER COLUMN [Logtable] VARCHAR(100) NOT NULL
Print 'updateLog...PKField'
ALTER TABLE [updateLog]  ALTER COLUMN [PKField] VARCHAR(100) NULL
GO
--#endregion

--#region 20170921 TK PersId 260 entfernen 
--Und nicht mehr verwendete Tabelle entfernen

IF EXISTS (SELECT * FROM PersH WHERE PersNr = 260)
BEGIN
	Print 'Remove 260 ...'
	DELETE FROM CastBonus WHERE CastId IN (SELECT Id FROM BesetzungTabelle WHERE Persnr  = 260)
	DELETE FROM BesetzungTabelle WHERE Persnr  = 260
	DELETE  FROM VertragRolle WHERE Vertragsnr IN(SELECT Vertragsnr FROM Vertrag WHERE Persnr  = 260)
	DELETE  FROM Vertrag WHERE Persnr  = 260
	UPDATE Zr SET AdressPersNr = NULL WHERE  AdressPersNr = 260
	UPDATE DienstplanArtenTabelle SET HeadOfDepartmentId = NULL WHERE  HeadOfDepartmentId = 260
	DELETE FROM BesRepertoire WHERE PersNr = 260
	DELETE FROM PersonalDetails WHERE Pnr = 260
	DELETE FROM PersAdresse WHERE PersNr = 260
	DELETE FROM PersKom WHERE PersNr = 260
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PersMasse]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) DELETE FROM PersMasse WHERE PersNr = 260
	DELETE FROM StatusZeitR WHERE PersNr = 260
	DELETE FROM OrderTravelers WHERE TravelerId = 260
	DELETE FROM PersAgentur WHERE PersNr = 260
	DELETE FROM PersAgentur WHERE ChildPersNr = 260
	DELETE FROM PersonalHonorar WHERE Persnr = 260
	DELETE FROM PersH WHERE PersNr = 260
	Print 'Basiccast...'
	UPDATE BesetzungStdSoliTabelle SET PersNr1 = NULL WHERE  PersNr1 NOT IN (SELECT Persnr FROM PersH) 
	UPDATE BesetzungStdSoliTabelle SET PersNr2 = NULL WHERE  PersNr2 NOT IN (SELECT Persnr FROM PersH) 
	UPDATE BesetzungStdSoliTabelle SET PersNr3 = NULL WHERE  PersNr3 NOT IN (SELECT Persnr FROM PersH)
	UPDATE BesetzungStdSoliTabelle SET PersNr4 = NULL WHERE  PersNr4 NOT IN (SELECT Persnr FROM PersH)

	UPDATE BesetzungStdSoliTabelle SET PersNr1 = NULL WHERE  PersNr1 = 0
	UPDATE BesetzungStdSoliTabelle SET PersNr2 = NULL WHERE  PersNr2 = 0
	UPDATE BesetzungStdSoliTabelle SET PersNr3 = NULL WHERE  PersNr3 = 0
	UPDATE BesetzungStdSoliTabelle SET PersNr4 = NULL WHERE  PersNr4 = 0
END
GO
--#endregion

--#region 20170921 TK Bugfix: Standardbesetzungen können ohne Leserechte gelesen werden. Nach RELEASE übertragen 
ALTER VIEW [dbo].[AbBesetzungStdSoli]
	AS
	SELECT s.BesetzungStdSoliID, s.RolleId, s.SpzNr, s.BesSort, s.UnderstudyPosition,
		CASE WHEN ((S.Gesperrt = 0 AND s.IsPerson1Locked = 0) OR (Ug.OptionsFlag&1 = 1)) AND NOT Ug.GruppeID IS NULL  THEN s.PersNr1 ELSE -1 END AS PersNr1,
		CASE WHEN ((S.Gesperrt = 0 AND s.IsPerson2Locked = 0) OR (Ug.OptionsFlag&1 = 1)) AND NOT Ug.GruppeID IS NULL  THEN s.PersNr2 ELSE -1 END AS PersNr2,
		CASE WHEN ((S.Gesperrt = 0 AND s.IsPerson3Locked = 0) OR (Ug.OptionsFlag&1 = 1)) AND NOT Ug.GruppeID IS NULL  THEN s.PersNr3 ELSE -1 END AS PersNr3,
		CASE WHEN ((S.Gesperrt = 0 AND s.IsPerson4Locked = 0) OR (Ug.OptionsFlag&1 = 1)) AND NOT Ug.GruppeID IS NULL  THEN s.PersNr4 ELSE -1 END AS PersNr4,
		 s.Gesperrt, s.IsPerson1Locked, s.IsPerson2Locked, s.IsPerson3Locked, s.IsPerson4Locked,
		 s.Note, s.LM, s.UM, s.LC, s.UC

	FROM  BesetzungStdSoliTabelle AS S 
		INNER JOIN BesetzungStd AS R ON S.RolleID = R.Id
		INNER JOIN Gruppe AS G ON R.Besitzer = G.GruppeID
		LEFT JOIN (SELECT GruppeID, OptionsFlag 
					FROM  UserGruppe AS Ug 
						INNER JOIN UserPW ON Ug.Userid = UserPW.Userid 
					WHERE   BerechtigungsbereichID = 4 AND UserPW.Username = CURRENT_USER) AS ug 
			ON G.GruppeID = Ug.GruppeID  
--#endregion

--#region 20170921 TK Besetzung auf neue Datentypen umstellen, nicht verwendete Felder entfernen
GO
DropColumn 'BesetzungTabelle', 'NoCount'
GO
IF EXISTS (SELECT * FROM dbo.sysobjects so LEFT JOIN dbo.syscomments sm ON sm.id = so.id WHERE so.id = OBJECT_ID(N'dbo.FK_BesetzungTabelle_AuffTechAufgabe'))	ALTER TABLE [dbo].BesetzungTabelle DROP CONSTRAINT FK_BesetzungTabelle_AuffTechAufgabe
GO
DropColumn 'BesetzungTabelle', 'AuffTechAufgabeID'
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.DF_BesetzungTabelle_BesSort'))
BEGIN
	Print 'Cast...'
	ALTER TABLE BesetzungTabelle DROP CONSTRAINT DF_BesetzungTabelle_BesSort
	ALTER TABLE BesetzungTabelle ALTER COLUMN BesSort SMALLINT NOT NULL 
	ALTER TABLE BesetzungTabelle ADD CONSTRAINT DF_Cast_Sort DEFAULT 0 FOR BesSort
	ALTER TABLE BesetzungTabelle ALTER COLUMN Druck TINYINT NULL 
	ALTER TABLE BesetzungTabelle ALTER COLUMN BesBem VARCHAR(250) SPARSE NULL
	ALTER TABLE BesetzungTabelle ALTER COLUMN AgencyId INT SPARSE NULL
	ALTER TABLE BesetzungTabelle ALTER COLUMN BackColorArgb INT SPARSE NULL
	Print 'Cast...1'
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[BesetzungTabelle]') AND o.Name = 'IX_Cast_ActivityId') DROP INDEX IX_Cast_ActivityId ON dbo.BesetzungTabelle
	CREATE CLUSTERED INDEX IX_Cast_ActivityId ON dbo.BesetzungTabelle (AuffNr) WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	Print 'Cast...2'
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[BesetzungStd]') AND o.Name = 'IX_Roles_ProductionId') DROP INDEX IX_Roles_ProductionId ON dbo.BesetzungStd
	CREATE CLUSTERED INDEX IX_Roles_ProductionId ON dbo.BesetzungStd (Snr) WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	Print 'Cast...3'
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[AufR]') AND o.Name = 'IX_AuffNr') DROP INDEX IX_AuffNr ON dbo.AufR
	Print 'AufR...4'
	CREATE CLUSTERED INDEX IX_AuffNr ON dbo.AufR (Auffnr) WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END
GO
--#endregion

--#region 20170921 TK Dienstpla auf neue Datentypen umstellen, nicht verwendete Felder entfernen
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.Dienstplan') AND o.Name = 'IX_DutyRoster_Date')
 BEGIN
 	Print 'DutyRoster...IX'
	IF EXISTS (SELECT * FROM dbo.sysobjects so LEFT JOIN dbo.syscomments sm ON sm.id = so.id WHERE so.id = OBJECT_ID(N'dbo.FK_ZulagenDienstplan_Dienstplan'))	ALTER TABLE [dbo].ZulagenDienstplan DROP CONSTRAINT FK_ZulagenDienstplan_Dienstplan
	IF EXISTS (SELECT * FROM dbo.sysobjects so LEFT JOIN dbo.syscomments sm ON sm.id = so.id WHERE so.id = OBJECT_ID(N'dbo.FK_DutyRosterBonus_DutyRoster'))	ALTER TABLE [dbo].ZulagenDienstplan DROP CONSTRAINT FK_DutyRosterBonus_DutyRoster
	IF EXISTS (SELECT * FROM dbo.sysobjects so LEFT JOIN dbo.syscomments sm ON sm.id = so.id WHERE so.id = OBJECT_ID(N'dbo.FK_CostUnitWorkingTime_ShiftDay'))	ALTER TABLE [dbo].CostUnitWorkingTime DROP CONSTRAINT FK_CostUnitWorkingTime_ShiftDay
	
	ALTER TABLE [dbo].[Dienstplan] DROP CONSTRAINT [PK_Dienstplan]
	ALTER TABLE [dbo].[Dienstplan]  ADD CONSTRAINT PK_Dienstplan PRIMARY KEY NONCLUSTERED (DienstplanID) ON [PRIMARY]
	IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[Dienstplan]') AND o.Name = 'iVertragsNrDatumDienstplanEintragArtId')  DROP INDEX  Dienstplan.iVertragsNrDatumDienstplanEintragArtId
	IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[Dienstplan]') AND o.Name = 'iDatum') DROP INDEX  Dienstplan.iDatum
	ALTER TABLE Dienstplan ALTER COLUMN Datum DATE NOT NULL
	CREATE INDEX IX_DutyRoster_Date ON [Dienstplan] (Datum) ON [PRIMARY]
	CREATE UNIQUE CLUSTERED INDEX IX_DutyRoster_DateArtContract ON [Dienstplan] (Datum, DienstplanEintragArtId, VertragsNr) ON [PRIMARY]

	ALTER TABLE dbo.ZulagenDienstplan  WITH CHECK ADD  CONSTRAINT FK_DutyRosterBonus_DutyRoster FOREIGN KEY(DienstplanId)
	REFERENCES dbo.Dienstplan (DienstplanId) ON DELETE CASCADE
	ALTER TABLE dbo.ZulagenDienstplan CHECK CONSTRAINT FK_DutyRosterBonus_DutyRoster


	ALTER TABLE dbo.CostUnitWorkingTime  WITH CHECK ADD  CONSTRAINT FK_CostUnitWorkingTime_ShiftDay FOREIGN KEY(ShiftDayId)
	REFERENCES dbo.Dienstplan (DienstplanId) ON DELETE CASCADE
	ALTER TABLE dbo.CostUnitWorkingTime CHECK CONSTRAINT FK_CostUnitWorkingTime_ShiftDay

END

exec DeleteConstraint 'Dienstplan', 'BackColor1'
exec DeleteConstraint 'Dienstplan', 'BackColor2'
exec DeleteConstraint 'Dienstplan', 'BackColor3'
exec DeleteConstraint 'Dienstplan', 'ForeColor1'
exec DeleteConstraint 'Dienstplan', 'ForeColor2'
exec DeleteConstraint 'Dienstplan', 'ForeColor3'
exec DropColumn 'Dienstplan', 'Farbe'
exec DropColumn 'Dienstplan', 'Status'

 IF EXISTS (SELECT * FROM dbo.sysobjects so LEFT JOIN dbo.syscomments sm ON sm.id = so.id WHERE so.id = OBJECT_ID(N'dbo.DF_Dienstplan_NoteForeColor3') )
 BEGIN
	Print 'DutyRoster...'
	ALTER TABLE Dienstplan ALTER COLUMN Datum DATE NULL

	ALTER TABLE Dienstplan ALTER COLUMN V1 SMALLDATETIME NULL
	ALTER TABLE Dienstplan ALTER COLUMN B1 SMALLDATETIME NULL
	ALTER TABLE Dienstplan ALTER COLUMN V2 SMALLDATETIME NULL
	ALTER TABLE Dienstplan ALTER COLUMN B2 SMALLDATETIME NULL
	ALTER TABLE Dienstplan ALTER COLUMN V3 SMALLDATETIME SPARSE NULL
	ALTER TABLE Dienstplan ALTER COLUMN B3 SMALLDATETIME SPARSE NULL

	ALTER TABLE Dienstplan ALTER COLUMN Ft REAL SPARSE NULL

	ALTER TABLE Dienstplan ALTER COLUMN Bemerkung VARCHAR(100) SPARSE NULL
	ALTER TABLE Dienstplan ALTER COLUMN ShiftNote2 VARCHAR(100) SPARSE NULL
	ALTER TABLE Dienstplan ALTER COLUMN ShiftNote3 VARCHAR(100) SPARSE NULL
	ALTER TABLE Dienstplan ALTER COLUMN Anmerkung VARCHAR(100) SPARSE NULL

	ALTER TABLE Dienstplan ALTER COLUMN BackColor1 INT NULL 
	ALTER TABLE Dienstplan ALTER COLUMN BackColor2 INT NULL 
	ALTER TABLE Dienstplan ALTER COLUMN BackColor3 INT SPARSE NULL

	ALTER TABLE Dienstplan ALTER COLUMN ForeColor1 INT SPARSE NULL 
	ALTER TABLE Dienstplan ALTER COLUMN ForeColor2 INT SPARSE NULL 
	ALTER TABLE Dienstplan ALTER COLUMN ForeColor3 INT SPARSE NULL

  	ALTER TABLE [dbo].Dienstplan DROP CONSTRAINT DF_Dienstplan_NoteBackColor1
	ALTER TABLE Dienstplan ALTER COLUMN NoteBackColor1 INT SPARSE NULL 
 	ALTER TABLE [dbo].Dienstplan DROP CONSTRAINT DF_Dienstplan_NoteBackColor2
	ALTER TABLE Dienstplan ALTER COLUMN NoteBackColor2 INT SPARSE NULL 
	ALTER TABLE [dbo].Dienstplan DROP CONSTRAINT DF_Dienstplan_NoteBackColor3
	ALTER TABLE Dienstplan ALTER COLUMN NoteBackColor3 INT SPARSE NULL

 	ALTER TABLE [dbo].Dienstplan DROP CONSTRAINT DF_Dienstplan_NoteForeColor1
	ALTER TABLE Dienstplan ALTER COLUMN NoteForeColor1 INT SPARSE NULL 
 	ALTER TABLE [dbo].Dienstplan DROP CONSTRAINT DF_Dienstplan_NoteForeColor2
	ALTER TABLE Dienstplan ALTER COLUMN NoteForeColor2 INT SPARSE NULL 
	ALTER TABLE [dbo].Dienstplan DROP CONSTRAINT DF_Dienstplan_NoteForeColor3
	ALTER TABLE Dienstplan ALTER COLUMN NoteForeColor3 INT SPARSE NULL 
END
GO
--#endregion

--#region 20170921 TK Nicht verwendete Aktivitätssichten entfernen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[PersonalOrchester]'))	DROP VIEW [dbo].PersonalOrchester
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AufführgVariante]'))	DROP VIEW [dbo].AufführgVariante
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AufführgNr]'))	DROP VIEW [dbo].AufführgNr
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AufführgA]'))	DROP VIEW [dbo].AufführgA
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AufführgB]'))	DROP VIEW [dbo].AufführgB
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AufführgC]'))	DROP VIEW [dbo].AufführgC
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AufführgFullUpdate]'))	DROP VIEW [dbo].AufführgFullUpdate
GO
--#endregion

--#region 20170921 TK Aktivitäten auf neue Datentypen umstellen, nicht verwendete Felder entfernen
IF  EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'GruppeID' and o.id = OBJECT_ID(N'dbo.AufführgTabelle'))
BEGIN
	Print 'Activities...'
	UPDATE Aufführgtabelle SET UhrBeg = '19000101 ' + CONVERT(varchar(5), UhrBeg, 108) FROM Aufführgtabelle  WHERE UhrBeg < '19000101'
	UPDATE Aufführgtabelle SET UhrEnde = '19000101 ' + CONVERT(varchar(5), UhrEnde, 108) FROM Aufführgtabelle  WHERE UhrEnde < '19000101'

	DROP INDEX  AufführgTabelle.IX_Activities_Date
	ALTER TABLE AufführgTabelle ALTER COLUMN Datum DATE NOT NULL
	CREATE CLUSTERED INDEX IX_Activities_Date ON AufführgTabelle (Datum) ON [PRIMARY]
	ALTER TABLE AufführgTabelle ALTER COLUMN UhrBeg SMALLDATETIME NOT NULL
	ALTER TABLE AufführgTabelle ALTER COLUMN UhrEnde SMALLDATETIME NOT NULL
	ALTER TABLE AufführgTabelle ALTER COLUMN BemKurz VARCHAR(256) SPARSE NULL
	ALTER TABLE AufführgTabelle ALTER COLUMN BemKurz2 VARCHAR(256) SPARSE NULL
	ALTER TABLE AufführgTabelle ALTER COLUMN Bem VARCHAR(MAX) SPARSE NULL
	ALTER TABLE AufführgTabelle ALTER COLUMN ZuAuffNr INT SPARSE NULL

	ALTER TABLE dbo.AufführgDetails	DROP CONSTRAINT PK_AufführgDetails
	ALTER TABLE dbo.AufführgDetails ADD CONSTRAINT PK_ActivityDetails_ActivityId PRIMARY KEY CLUSTERED (AuffNr) WITH(PAD_INDEX = OFF, FILLFACTOR = 90, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

	ALTER TABLE AufführgTabelle DROP COLUMN Doppel
	ALTER TABLE AufführgTabelle DROP COLUMN GruppeID
	ALTER TABLE AufführgTabelle DROP COLUMN Mandant
	ALTER TABLE AufführgTabelle DROP COLUMN AufführgTS
	ALTER TABLE AufführgTabelle DROP COLUMN Exid
END
GO
--#endregion

--#region 20170921 TK Nicht verwendete Personal Sichten entfernen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[Personal]'))	DROP VIEW [dbo].Personal
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[Personaltechnik]'))	DROP VIEW [dbo].Personaltechnik
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPersKontakt]'))	DROP VIEW [dbo].AbPersKontakt
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPersD]'))	DROP VIEW [dbo].AbPersD
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[Abperskat_Update]'))	DROP VIEW [dbo].Abperskat_Update
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPersKomAlle]'))	DROP VIEW [dbo].AbPersKomAlle
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[Ab_VB_Auff]'))	DROP PROCEDURE [dbo].Ab_VB_Auff
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[Ab_VB_Auff_Alle]'))	DROP PROCEDURE [dbo].Ab_VB_Auff_Alle
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[Ab_VB_AuffNr]'))	DROP PROCEDURE [dbo].Ab_VB_AuffNr
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[Ab_VB_AuffNr_Alle]'))	DROP PROCEDURE [dbo].Ab_VB_AuffNr_Alle
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbBQ]'))	DROP PROCEDURE [dbo].AbBQ
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPlan]'))	DROP PROCEDURE [dbo].AbPlan
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[bq]'))	DROP PROCEDURE [dbo].bq
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[SP_Besetzung]'))	DROP PROCEDURE [dbo].SP_Besetzung
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[sp_Besetzung_Del]'))	DROP PROCEDURE [dbo].sp_Besetzung_Del
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[sp_Besetzung_Edit]'))	DROP PROCEDURE [dbo].sp_Besetzung_Edit
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[sp_Besetzung_New]'))	DROP PROCEDURE [dbo].sp_Besetzung_New
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[sp_NeueRolle]'))	DROP PROCEDURE [dbo].sp_NeueRolle
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[sp_NeuSoli]'))	DROP PROCEDURE [dbo].sp_NeuSoli
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[sp_NeuWerk]'))	DROP PROCEDURE [dbo].sp_NeuWerk
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[sp_PersDelete]'))	DROP PROCEDURE [dbo].sp_PersDelete
GO
--#endregion

--#region 20170921 TK Persh  bereinigen
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.CK_PersH') AND type = 'C') 
	ALTER TABLE dbo.PersH	DROP CONSTRAINT CK_PersH
GO


IF  EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PersHTS' and o.id = OBJECT_ID(N'dbo.PersH'))
BEGIN
	Print 'Personal...'

	DROP INDEX  PersH.IX_PersKatNr
	UPDATE PersH SET PersKatNr = (select top 1 PersKatNr from PersKat) WHERE PersKatNr IS NULL
	ALTER TABLE PersH ALTER COLUMN PersKatNr INT NOT NULL
	CREATE  INDEX IX_PersKatNr ON PersH (PersKatNr) ON [PRIMARY]

	DROP INDEX  PersH.IX_Besitzer
	ALTER TABLE PersH ALTER COLUMN Besitzer INT NOT NULL
	CREATE  INDEX IX_Besitzer ON PersH (Besitzer) ON [PRIMARY]

	ALTER TABLE PersH DROP CONSTRAINT DF_Personal_inactive
	ALTER TABLE PersH ALTER COLUMN alt BIT NOT NULL
	ALTER TABLE PersH ADD CONSTRAINT DF_Personal_IsInactive DEFAULT 0 FOR alt

	ALTER TABLE PersH ALTER COLUMN VornKurz VARCHAR(5) SPARSE NULL
	ALTER TABLE PersH ALTER COLUMN PTitel VARCHAR(20) SPARSE NULL
	ALTER TABLE PersH ALTER COLUMN Ansprache VARCHAR(100) SPARSE NULL
	ALTER TABLE PersH ALTER COLUMN PFunktion VARCHAR(80) SPARSE NULL
	
	ALTER TABLE PersH DROP COLUMN PersHTS
END
GO
--#endregion

--#region 20170921 TK CLUSTERED Index für Persh.Persnr 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.aaaaaPersH_PK') AND type = 'K') 
BEGIN
	Print 'Personal...IX'
	DELETE FROM VertragRolle WHERE NOT EXISTS(SELECT * FROM Persh INNER JOIN Vertrag ON Persh.Persnr = Vertrag.PersNr WHERE VertragRolle.VertragsNr = Vertrag.VertragsNr)
	DELETE FROM Vertrag WHERE NOT EXISTS(SELECT * FROM Persh WHERE Vertrag.PersNr = Persh.persNr)
	DELETE FROM PersonalNotizen WHERE NOT EXISTS(SELECT * FROM Persh WHERE PersonalNotizen.PersNr = Persh.persNr)
	DELETE FROM PersonalDetails WHERE PNr not in (SELECT Persnr FROM persh)
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonAttachments_Person') AND type = 'F') ALTER TABLE dbo.PersonAttachments DROP CONSTRAINT FK_PersonAttachments_Person
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_OrderTravelers_Persons') AND type = 'F') ALTER TABLE dbo.OrderTravelers	DROP CONSTRAINT FK_OrderTravelers_Persons
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Orders_Suppliers') AND type = 'F') ALTER TABLE dbo.Orders DROP CONSTRAINT FK_Orders_Suppliers
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonalHonorar_PersH') AND type = 'F') ALTER TABLE dbo.PersonalHonorar DROP CONSTRAINT FK_PersonalHonorar_PersH
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_BankAccount_Personal2') AND type = 'F') ALTER TABLE dbo.BankAccount	DROP CONSTRAINT FK_BankAccount_Personal2
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Person_HealthInsurance') AND type = 'F') ALTER TABLE dbo.PersonalDetails	DROP CONSTRAINT FK_Person_HealthInsurance
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ABGruppe_Person_Persh') AND type = 'F') ALTER TABLE dbo.ABGruppe_Person	DROP CONSTRAINT FK_ABGruppe_Person_Persh
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Person_TaxOffice') AND type = 'F') ALTER TABLE dbo.PersonalDetails	DROP CONSTRAINT FK_Person_TaxOffice
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Location_Contact') AND type = 'F') ALTER TABLE dbo.ZR	DROP CONSTRAINT FK_Location_Contact
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_DienstplanArtenTabelle_Persons') AND type = 'F') ALTER TABLE dbo.DienstplanArtenTabelle	DROP CONSTRAINT FK_DienstplanArtenTabelle_Persons
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersAgentur_Persh') AND type = 'F') ALTER TABLE dbo.PersAgentur	DROP CONSTRAINT FK_PersAgentur_Persh
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersAgentur_Persh_Child') AND type = 'F') ALTER TABLE dbo.PersAgentur	DROP CONSTRAINT FK_PersAgentur_Persh_Child
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersAgentur_PersH1') AND type = 'F') ALTER TABLE dbo.PersAgentur	DROP CONSTRAINT FK_PersAgentur_PersH1
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ResourceObjectBorrows_Persons') AND type = 'F') ALTER TABLE dbo.ResourceObjectBorrows	DROP CONSTRAINT FK_ResourceObjectBorrows_Persons
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_BodyMeasurements_PersH') AND type = 'F') ALTER TABLE dbo.BodyMeasurements	DROP CONSTRAINT FK_BodyMeasurements_PersH
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ResourceObjects_Person') AND type = 'F') ALTER TABLE dbo.ResourceObjects	DROP CONSTRAINT FK_ResourceObjects_Person
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Qualification_Person_PersH') AND type = 'F') ALTER TABLE dbo.Qualification_Person	DROP CONSTRAINT FK_Qualification_Person_PersH
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersAdresse_PersH_PersNr') AND type = 'F') ALTER TABLE dbo.PersAdresse	DROP CONSTRAINT FK_PersAdresse_PersH_PersNr
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_WorkCreators_Persons') AND type = 'F') ALTER TABLE dbo.WorkCreators	DROP CONSTRAINT FK_WorkCreators_Persons
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_CashCommand_PersH_PersonId') AND type = 'F') ALTER TABLE dbo.CashCommand	DROP CONSTRAINT FK_CashCommand_PersH_PersonId
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_CashCommand_PersH_AgencyId') AND type = 'F') ALTER TABLE dbo.CashCommand	DROP CONSTRAINT FK_CashCommand_PersH_AgencyId
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_WorkVersions_Persons') AND type = 'F') ALTER TABLE dbo.WorkVersions	DROP CONSTRAINT FK_WorkVersions_Persons
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersEmployee_Persh') AND type = 'F') ALTER TABLE dbo.PersEmployee	DROP CONSTRAINT FK_PersEmployee_Persh
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Besetzung_PersH') AND type = 'F') ALTER TABLE dbo.BesetzungTabelle	DROP CONSTRAINT FK_Besetzung_PersH
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_BesRepertoire_PersH') AND type = 'F') ALTER TABLE dbo.BesRepertoire	DROP CONSTRAINT FK_BesRepertoire_PersH
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_CheckListItemTemplate_Person') AND type = 'F')  ALTER TABLE dbo.CheckListItemTemplate	DROP CONSTRAINT FK_CheckListItemTemplate_Person
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersKom_PersH_PersNr') AND type = 'F') ALTER TABLE dbo.PersKom	DROP CONSTRAINT FK_PersKom_PersH_PersNr
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersMasse_PersH_PersNr') AND type = 'F') ALTER TABLE dbo.PersMasse	DROP CONSTRAINT FK_PersMasse_PersH_PersNr
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ResourceObjectInsurances_InsuredPersonId') AND type = 'F') ALTER TABLE dbo.ResourceObjectInsurances	DROP CONSTRAINT FK_ResourceObjectInsurances_InsuredPersonId
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonalNotizen_PersH_PersNr') AND type = 'F') ALTER TABLE dbo.PersonalNotizen	DROP CONSTRAINT FK_PersonalNotizen_PersH_PersNr
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersZusatzDaten_PersH_PersNr') AND type = 'F') ALTER TABLE dbo.PersZusatzDaten	DROP CONSTRAINT FK_PersZusatzDaten_PersH_PersNr
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_CheckListItem_Person') AND type = 'F') ALTER TABLE dbo.CheckListItem	DROP CONSTRAINT FK_CheckListItem_Person
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_StatusZeitR_PersH') AND type = 'F') ALTER TABLE dbo.StatusZeitR	DROP CONSTRAINT FK_StatusZeitR_PersH
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Vertrag_PersH') AND type = 'F') ALTER TABLE dbo.Vertrag	DROP CONSTRAINT FK_Vertrag_PersH
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersDataCategoryData_PersH') AND type = 'F') ALTER TABLE dbo.PersDataCategoryData	DROP CONSTRAINT FK_PersDataCategoryData_PersH
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_WorkVersionRoles_Repertoire_Persons_PersonId') AND type = 'F') ALTER TABLE dbo.WorkVersionRoles_Repertoire	DROP CONSTRAINT FK_WorkVersionRoles_Repertoire_Persons_PersonId
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_WorkVersionRoles_Repertoire_Persons_TheaterId') AND type = 'F') ALTER TABLE dbo.WorkVersionRoles_Repertoire	DROP CONSTRAINT FK_WorkVersionRoles_Repertoire_Persons_TheaterId
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_MailingListEntries_Persons') AND type = 'F') ALTER TABLE dbo.MailingListEntries	DROP CONSTRAINT FK_MailingListEntries_Persons
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_DepartmentCollectives_Personal') AND type = 'F') ALTER TABLE dbo.DepartmentCollectives	DROP CONSTRAINT FK_DepartmentCollectives_Personal
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_XHDelBasicCast_PersH_PersonOldId') AND type = 'F') ALTER TABLE dbo.XHDelBasicCast	DROP CONSTRAINT FK_XHDelBasicCast_PersH_PersonOldId
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_XHDelBasicCast_PersH_PersonNewId') AND type = 'F') ALTER TABLE dbo.XHDelBasicCast	DROP CONSTRAINT FK_XHDelBasicCast_PersH_PersonNewId
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonModulGroupPermission_Person') AND type = 'F') ALTER TABLE dbo.PersonModulGroupPermission	DROP CONSTRAINT FK_PersonModulGroupPermission_Person
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonalDetails_Personal') AND type = 'F') ALTER TABLE dbo.PersonalDetails	DROP CONSTRAINT FK_PersonalDetails_Personal
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonalDetails_PersH') AND type = 'F') ALTER TABLE dbo.PersonalDetails	DROP CONSTRAINT FK_PersonalDetails_PersH
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Travels_Person') AND type = 'F') ALTER TABLE dbo.Travels	DROP CONSTRAINT FK_Travels_Person

	ALTER TABLE dbo.PersH	DROP CONSTRAINT aaaaaPersH_PK
	ALTER TABLE dbo.PersH ADD CONSTRAINT PK_Persons_PersonId PRIMARY KEY CLUSTERED (PersNr) WITH(PAD_INDEX = OFF, FILLFACTOR = 90, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	ALTER TABLE dbo.PersonModulGroupPermission ADD CONSTRAINT FK_PersonModulGroupPermission_Person FOREIGN KEY 	(PersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE 
	ALTER TABLE dbo.XHDelBasicCast ADD CONSTRAINT FK_XHDelBasicCast_PersH_PersonOldId FOREIGN KEY (PersonOldId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  SET NULL 
	ALTER TABLE dbo.XHDelBasicCast ADD CONSTRAINT FK_XHDelBasicCast_PersH_PersonNewId FOREIGN KEY (PersonNewId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.DepartmentCollectives ADD CONSTRAINT FK_DepartmentCollectives_Personal FOREIGN KEY (PersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.MailingListEntries ADD CONSTRAINT FK_MailingListEntries_Persons FOREIGN KEY	(PersonId) REFERENCES dbo.PersH	(PersNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE 
	ALTER TABLE dbo.WorkVersionRoles_Repertoire ADD CONSTRAINT 	FK_WorkVersionRoles_Repertoire_Persons_PersonId FOREIGN KEY	(PersonId) REFERENCES dbo.PersH	(PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.WorkVersionRoles_Repertoire ADD CONSTRAINT	FK_WorkVersionRoles_Repertoire_Persons_TheaterId FOREIGN KEY (TheaterId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.PersDataCategoryData ADD CONSTRAINT	FK_PersDataCategoryData_PersH FOREIGN KEY (PersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE 
	ALTER TABLE dbo.Vertrag ADD CONSTRAINT 	FK_Vertrag_PersH FOREIGN KEY (PersNr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION ON DELETE  NO ACTION 
	ALTER TABLE dbo.StatusZeitR ADD CONSTRAINT 	FK_StatusZeitR_PersH FOREIGN KEY (PersNr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.CheckListItem ADD CONSTRAINT FK_CheckListItem_Person FOREIGN KEY (PersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE SET NULL 
	ALTER TABLE dbo.PersZusatzDaten ADD CONSTRAINT FK_PersZusatzDaten_PersH_PersNr FOREIGN KEY (PersNr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION  
	ALTER TABLE dbo.PersonalNotizen ADD CONSTRAINT FK_PersonalNotizen_PersH_PersNr FOREIGN KEY (PersNr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.ResourceObjectInsurances ADD CONSTRAINT	FK_ResourceObjectInsurances_InsuredPersonId FOREIGN KEY	(InsuredPersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.PersKom ADD CONSTRAINT 	FK_PersKom_PersH_PersNr FOREIGN KEY (PersNr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.CheckListItemTemplate ADD CONSTRAINT FK_CheckListItemTemplate_Person FOREIGN KEY (PersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  SET NULL 
	ALTER TABLE dbo.BesRepertoire ADD CONSTRAINT FK_BesRepertoire_PersH FOREIGN KEY	(PersNr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.BesetzungTabelle ADD CONSTRAINT FK_Besetzung_PersH FOREIGN KEY (PersNr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION 	 ON DELETE  NO ACTION 
	ALTER TABLE dbo.PersEmployee ADD CONSTRAINT FK_PersEmployee_Persh FOREIGN KEY (PersonId)  REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE 
	ALTER TABLE dbo.WorkVersions ADD CONSTRAINT FK_WorkVersions_Persons FOREIGN KEY	(PublisherId) REFERENCES dbo.PersH	(PersNr) ON UPDATE  NO ACTION 	 ON DELETE  NO ACTION 
	ALTER TABLE dbo.CashCommand ADD CONSTRAINT 	FK_CashCommand_PersH_PersonId FOREIGN KEY (PersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.CashCommand ADD CONSTRAINT 	FK_CashCommand_PersH_AgencyId FOREIGN KEY (AgencyId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.WorkCreators ADD CONSTRAINT FK_WorkCreators_Persons FOREIGN KEY (PersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION ON DELETE  NO ACTION 
	ALTER TABLE dbo.PersAdresse ADD CONSTRAINT 	FK_PersAdresse_PersH_PersNr FOREIGN KEY	(PersNr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE
	ALTER TABLE dbo.Qualification_Person ADD CONSTRAINT FK_Qualification_Person_PersH FOREIGN KEY (PersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE 
	ALTER TABLE dbo.ResourceObjects ADD CONSTRAINT 	FK_ResourceObjects_Person FOREIGN KEY (PersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.BodyMeasurements ADD CONSTRAINT FK_BodyMeasurements_PersH FOREIGN KEY (PersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE 
	ALTER TABLE dbo.ResourceObjectBorrows ADD CONSTRAINT FK_ResourceObjectBorrows_Persons FOREIGN KEY (PersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.PersAgentur ADD CONSTRAINT 	FK_PersAgentur_Persh FOREIGN KEY (PersNr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.PersAgentur ADD CONSTRAINT 	FK_PersAgentur_Persh_Child FOREIGN KEY	(ChildPersNr) REFERENCES dbo.PersH	(PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.DienstplanArtenTabelle ADD CONSTRAINT 	FK_DienstplanArtenTabelle_Persons FOREIGN KEY (HeadOfDepartmentId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  SET NULL 
	ALTER TABLE dbo.ZR ADD CONSTRAINT FK_Location_Contact FOREIGN KEY (AdressPersNr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  SET NULL 
	ALTER TABLE dbo.ABGruppe_Person ADD CONSTRAINT 	FK_ABGruppe_Person_Persh FOREIGN KEY (PersNr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION ON DELETE  CASCADE 
	ALTER TABLE dbo.PersonalDetails ADD CONSTRAINT FK_Person_HealthInsurance FOREIGN KEY (HealthInsuranceId) REFERENCES dbo.PersH (PersNr) ON UPDATE NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.PersonalDetails ADD CONSTRAINT FK_Person_TaxOffice FOREIGN KEY (TaxOfficeId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION ON DELETE  NO ACTION 
	ALTER TABLE dbo.BankAccount ADD CONSTRAINT FK_BankAccount_Personal2 FOREIGN KEY (PersID) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE 
	ALTER TABLE dbo.PersonalHonorar ADD CONSTRAINT FK_PersonalHonorar_PersH FOREIGN KEY (Persnr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION ON DELETE  CASCADE 
	ALTER TABLE dbo.Orders ADD CONSTRAINT FK_Orders_Suppliers FOREIGN KEY (SupplierId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.OrderTravelers ADD CONSTRAINT FK_OrderTravelers_Persons FOREIGN KEY	(TravelerId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.PersonAttachments ADD CONSTRAINT FK_PersonAttachments_Person FOREIGN KEY (PersonId) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.PersonalDetails ADD CONSTRAINT FK_PersonalDetails_Personal FOREIGN KEY (Pnr) REFERENCES dbo.PersH (PersNr) ON UPDATE  NO ACTION   ON DELETE  CASCADE 
END
GO
--#endregion

--#region 20170921 TK StatusZeitR bereinigen

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Bem' AND o.id = OBJECT_ID(N'[dbo].StatusZeitR') AND c.xtype =  35)
BEGIN
	Print 'Status...'
	UPDATE StatusZeitR SET UhrBeginn = '19000101 ' + CONVERT(varchar(5), UhrBeginn, 108) FROM StatusZeitR  WHERE NOT UhrBeginn IS NULL AND  UhrBeginn < '19000101'
	UPDATE StatusZeitR SET UhrEnde = '19000101 ' + CONVERT(varchar(5), UhrEnde, 108) FROM StatusZeitR  WHERE NOT UhrEnde IS NULL AND  UhrEnde < '19000101'

	ALTER TABLE StatusZeitR  ALTER COLUMN Bem VARCHAR(MAX) NULL
	ALTER TABLE StatusZeitR ALTER COLUMN  UhrBeginn SMALLDATETIME NULL
	ALTER TABLE StatusZeitR ALTER COLUMN  UhrEnde SMALLDATETIME NULL
	DELETE FROM StatusZeitR WHERE von IS NULL OR Bis IS NULL

	IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[StatusZeitR]') AND o.Name = 'IX_Von')  DROP INDEX  [StatusZeitR].IX_Von
	IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[StatusZeitR]') AND o.Name = 'IX_Bis') DROP INDEX  [StatusZeitR].IX_Bis
	ALTER TABLE [dbo].[StatusZeitR]  DROP CONSTRAINT [CK_StatusZeitR_Period]
	
	ALTER TABLE StatusZeitR ALTER COLUMN  Von DATE NOT NULL
	ALTER TABLE StatusZeitR ALTER COLUMN  Bis DATE NOT NULL

	ALTER TABLE [dbo].[StatusZeitR]  WITH CHECK ADD  CONSTRAINT [CK_StatusZeitR_Period] CHECK  (([Von]<=[Bis]))
	ALTER TABLE [dbo].[StatusZeitR] CHECK CONSTRAINT [CK_StatusZeitR_Period]
	CREATE  INDEX IX_Von ON [StatusZeitR] (Von) 
	CREATE  INDEX IX_Bis ON [StatusZeitR] (Bis)
	DELETE FROM StatusZeitR WHERE StatusID is null
	IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[StatusZeitR]') AND o.Name = 'IX_StatusID') DROP INDEX  [StatusZeitR].IX_StatusID
	ALTER TABLE StatusZeitR ALTER COLUMN  StatusID INT NOT NULL
	CREATE  INDEX IX_StatusId ON [StatusZeitR] (StatusID) 

	DELETE FROM StatusZeitR WHERE PersNr is null
	IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[StatusZeitR]') AND o.Name = 'IX_PersNr') DROP INDEX  [StatusZeitR].IX_PersNr
	ALTER TABLE StatusZeitR ALTER COLUMN  PersNr INT NOT NULL
	CREATE  INDEX IX_PersNr ON [StatusZeitR] (PersNr) 
	
	IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[StatusZeitR]') AND o.Name = 'IX_Status') DROP INDEX  [StatusZeitR].IX_Status
	ALTER TABLE StatusZeitR ALTER COLUMN [Status] TINYINT NOT NULL
	CREATE  INDEX IX_Status ON [StatusZeitR] ([Status]) 

	ALTER TABLE StatusZeitR ALTER COLUMN  DateOfRequest DATE  NULL
END
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.aaaaaStückeDetails_PK') AND type = 'K') 
BEGIN
	ALTER TABLE dbo.StückeDetails DROP CONSTRAINT aaaaaStückeDetails_PK
	ALTER TABLE dbo.StückeDetails ADD CONSTRAINT PK_Productions_ProductionId PRIMARY KEY CLUSTERED  (Snr) WITH( PAD_INDEX = OFF, FILLFACTOR = 90, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]


	ALTER TABLE Stücke DROP CONSTRAINT CK_Stücke
	ALTER TABLE Stücke DROP CONSTRAINT DF_Productions_inactive
	UPDATE Stücke SET alt = 0 WHERE Alt IS NULL
	ALTER TABLE Stücke ALTER COLUMN Alt BIT NOT NULL
	ALTER TABLE Stücke ADD CONSTRAINT DF_Productions_isInactive DEFAULT 0 FOR alt
END
GO
--#endregion

--#region 20170921 TK CLUSTERED Index für Vertrag.VertragsNr 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.aaaaaVertrag_PK') AND type = 'K') 
BEGIN
	Print 'Contracts...IX'
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_VertragRolle_Vertrag') AND type = 'F') ALTER TABLE dbo.VertragRolle DROP CONSTRAINT FK_VertragRolle_Vertrag
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Tours_Contracts_Contracts') AND type = 'F') ALTER TABLE dbo.Tours_Contracts DROP CONSTRAINT FK_Tours_Contracts_Contracts
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_CastCredits_Contract') AND type = 'F') ALTER TABLE dbo.CastCredits DROP CONSTRAINT FK_CastCredits_Contract
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ContractConfirmations_Vertrag') AND type = 'F') ALTER TABLE dbo.ContractConfirmations DROP CONSTRAINT FK_ContractConfirmations_Vertrag
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ContractBonus_Contact') AND type = 'F') ALTER TABLE dbo.ContractBonus DROP CONSTRAINT FK_ContractBonus_Contact
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ZeitkontenMonat_Vertrag') AND type = 'F') ALTER TABLE dbo.ZeitkontenMonat DROP CONSTRAINT FK_ZeitkontenMonat_Vertrag
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ContractDetails_Contract') AND type = 'F') ALTER TABLE dbo.VertragDetails 	DROP CONSTRAINT FK_ContractDetails_Contract
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ContractFields_PersContract') AND type = 'F') ALTER TABLE dbo.ContractFields 	DROP CONSTRAINT FK_ContractFields_PersContract
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_VertragPerso_Vertrag') AND type = 'F') ALTER TABLE dbo.VertragPerso 	DROP CONSTRAINT FK_VertragPerso_Vertrag
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ContractSeasonInformation_Contract') AND type = 'F') ALTER TABLE dbo.ContractSeasonInformation DROP CONSTRAINT FK_ContractSeasonInformation_Contract
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Contract_Qualification_Person_Contract') AND type = 'F') ALTER TABLE dbo.Contract_Qualification_Person 	DROP CONSTRAINT FK_Contract_Qualification_Person_Contract
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Cast_Contract2') AND type = 'F') ALTER TABLE dbo.BesetzungTabelle DROP CONSTRAINT FK_Cast_Contract2
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Tours_InventoryItems_Vertrag') AND type = 'F') ALTER TABLE dbo.Tours_InventoryItems 	DROP CONSTRAINT FK_Tours_InventoryItems_Vertrag
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_RosterContract') AND type = 'F') ALTER TABLE dbo.Dienstplan 	DROP CONSTRAINT FK_RosterContract
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ContractPartTimePeriods_Contract') AND type = 'F') ALTER TABLE dbo.ContractPartTimePeriods 	DROP CONSTRAINT FK_ContractPartTimePeriods_Contract
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_TimeAccountUsage_VertragPerso') AND type = 'F') ALTER TABLE dbo.TimeAccountUsage 	DROP CONSTRAINT FK_TimeAccountUsage_VertragPerso
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Travels_Contracts') AND type = 'F') ALTER TABLE dbo.Travels 	DROP CONSTRAINT FK_Travels_Contracts

	ALTER TABLE dbo.Vertrag DROP CONSTRAINT aaaaaVertrag_PK

	ALTER TABLE dbo.Vertrag ADD CONSTRAINT 	PK_Contract_PersonId PRIMARY KEY CLUSTERED  (VertragsNr) WITH( PAD_INDEX = OFF, FILLFACTOR = 90, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

	ALTER TABLE dbo.TimeAccountUsage ADD CONSTRAINT FK_TimeAccountUsage_VertragPerso FOREIGN KEY (ContractId) REFERENCES dbo.Vertrag (VertragsNr) ON UPDATE  NO ACTION   ON DELETE  CASCADE 
	ALTER TABLE dbo.ContractPartTimePeriods ADD CONSTRAINT 	FK_ContractPartTimePeriods_Contract FOREIGN KEY (ContractId) REFERENCES dbo.Vertrag (VertragsNr) ON UPDATE  NO ACTION   ON DELETE  CASCADE 
	ALTER TABLE dbo.Dienstplan ADD CONSTRAINT 	FK_RosterContract FOREIGN KEY 	(VertragsNr) REFERENCES dbo.Vertrag	(VertragsNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.Tours_InventoryItems ADD CONSTRAINT 	FK_Tours_InventoryItems_Vertrag FOREIGN KEY (ContractId) REFERENCES dbo.Vertrag	(VertragsNr) ON UPDATE  NO ACTION 	 ON DELETE  NO ACTION 
	ALTER TABLE dbo.Contract_Qualification_Person ADD CONSTRAINT 	FK_Contract_Qualification_Person_Contract FOREIGN KEY (ContractId) REFERENCES dbo.Vertrag (VertragsNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE 
	ALTER TABLE dbo.ContractSeasonInformation ADD CONSTRAINT FK_ContractSeasonInformation_Contract FOREIGN KEY (ContractId) REFERENCES dbo.Vertrag (VertragsNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE 
	ALTER TABLE dbo.VertragPerso ADD CONSTRAINT FK_VertragPerso_Vertrag FOREIGN KEY	(VertragsNr) REFERENCES dbo.Vertrag	(VertragsNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 	
	ALTER TABLE dbo.ContractFields ADD CONSTRAINT 	FK_ContractFields_PersContract FOREIGN KEY (PersContractId) REFERENCES dbo.Vertrag (VertragsNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE 
	ALTER TABLE dbo.VertragDetails ADD CONSTRAINT FK_ContractDetails_Contract FOREIGN KEY (VertragsNr) REFERENCES dbo.Vertrag (VertragsNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE 
	ALTER TABLE dbo.ZeitkontenMonat ADD CONSTRAINT 	FK_ZeitkontenMonat_Vertrag FOREIGN KEY (VertragsNr) REFERENCES dbo.Vertrag (VertragsNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.ContractBonus ADD CONSTRAINT FK_ContractBonus_Contact FOREIGN KEY (ContractId) REFERENCES dbo.Vertrag (VertragsNr) ON UPDATE  NO ACTION  ON DELETE  CASCADE 
	ALTER TABLE dbo.ContractConfirmations WITH NOCHECK ADD CONSTRAINT FK_ContractConfirmations_Vertrag FOREIGN KEY (ContractId) REFERENCES dbo.Vertrag (VertragsNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.CastCredits ADD CONSTRAINT	FK_CastCredits_Contract FOREIGN KEY	(ContractId) REFERENCES dbo.Vertrag	(VertragsNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 	
	ALTER TABLE dbo.Tours_Contracts ADD CONSTRAINT FK_Tours_Contracts_Contracts FOREIGN KEY	(ContractId) REFERENCES dbo.Vertrag	(VertragsNr) ON UPDATE  NO ACTION  ON DELETE  NO ACTION 
	ALTER TABLE dbo.VertragRolle ADD CONSTRAINT	FK_VertragRolle_Vertrag FOREIGN KEY	(VertragsNr) REFERENCES dbo.Vertrag	(VertragsNr) ON UPDATE  NO ACTION 	 ON DELETE  NO ACTION 

	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[Vertrag]') AND o.Name = 'IX_vVon') DROP INDEX  Vertrag.IX_vVon
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[Vertrag]') AND o.Name = 'IX_vBis') DROP INDEX  Vertrag.IX_vBis
	ALTER TABLE Vertrag ALTER COLUMN  vVon DATE NULL
	ALTER TABLE Vertrag ALTER COLUMN  vBis DATE NULL

	CREATE  INDEX IX_StartDate ON Vertrag (VVon) ON [PRIMARY]
	CREATE  INDEX IX_EndDate ON Vertrag (vBis) ON [PRIMARY]
	
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[Vertrag]') AND o.Name = 'IX_PersNr')  DROP INDEX  Vertrag.IX_PersNr
	ALTER TABLE Vertrag ALTER COLUMN  PersNr INT NOT NULL
	CREATE  INDEX IX_PersonId ON Vertrag (PersNr) ON [PRIMARY]

	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[Vertrag]') AND o.Name = 'IX_VorlagenID')  DROP INDEX  Vertrag.IX_VorlagenID
	IF EXISTS (SELECT * FROM VERTRAG WHERE VORLAGENID IS NULL)
	BEGIN
		INSERT INTO VERTRAGSVORLAGEN (PERSOPARAMETERID,MODULE,VORLGENBEZ,RAPPORTID ) VALUES((SELECT MIN(PERSOPARAMETER.PERSOPARAMETERID) FROM PERSOPARAMETER),1,'BEREINIGEN',(SELECT MIN(RAPPORT.RID) FROM RAPPORT))
		UPDATE VERTRAG SET VORLAGENID=(SELECT MAX(VERTRAGSVORLAGEN.VORLAGENID) FROM VERTRAGSVORLAGEN) WHERE VorlagenID IS NULL	
	END

	ALTER TABLE Vertrag ALTER COLUMN  VorlagenID INT NOT NULL
	CREATE  INDEX IX_ContractTypeId ON Vertrag (VorlagenID) ON [PRIMARY]

	ALTER TABLE Vertrag ALTER COLUMN  BJBGenPos VARCHAR(MAX)  SPARSE NULL
	ALTER TABLE Vertrag ALTER COLUMN  ContractDescription VARCHAR(100)  SPARSE NULL
END
GO
--#endregion

--#region 20170921 TK Nicht mehr verwendete Felder entfernen

exec DropColumn 'Vertrag', 'VertragTS'
GO
exec DropColumn 'Vertrag', 'VBez'
GO
exec DropColumn 'Vertrag', 'VSNr'
GO
exec DropColumn 'PersH', 'FestGast'
GO
exec DropColumn 'PersH', 'Anrede'
GO
exec DropColumn 'Vertrag', 'Waehrung'
Go
exec DropColumn 'StückeDetails', 'ZRNr_s'
Go
exec DropColumn 'StückeDetails', 'KstNr'
Go
exec DropColumn 'BesetzungTabelle', 'GruppeID'
GO
exec DropColumn 'PersH', 'PrimKTyp'
GO
exec DropColumn 'PersonalDetails', 'RepetiSoliProSort'
GO
exec DropColumn 'PersonalDetails', 'RepetiSoliProZr'
GO
exec DropColumn 'PersonalDetails', 'InTrs'
GO
exec DropColumn 'PersonalDetails', 'Adressplan'
GO
exec DropColumn 'PersonalDetails', 'PreviousNationality'
GO
exec DropColumn 'PersonalDetails', 'NameOfFather'
GO
exec DropColumn 'PersonalDetails', 'LandOfBirth'
GO
exec DropColumn 'PersonalDetails', 'Job'
GO
exec DropColumn 'PersKat', 'PersKatTS'
GO
exec DropColumn 'PersKat', 'Fax'
GO
exec DropColumn 'PersKat', 'Leitung'
GO
exec DropColumn 'PersKat', 'nichtTagesplanAlph'
GO
exec DropColumn 'PersKat', 'DienstplanArtenID'
GO
exec DropColumn 'PersKat', 'Module'
GO
exec DropColumn 'TYP', 'Farbe' 
GO
exec DropColumn 'Userpw', 'Userpw' 
GO
exec DropColumn 'Userpw', 'UserpwTS' 
GO
exec DropColumn 'Userpw', 'tempUserID' 
GO
exec DropColumn 'Vorlagen', 'IsBookmarkType'
GO
exec DropColumn 'Vorlagen', 'VorlagenTS'
GO
exec DropColumn 'VertragsVorlagen', 'Dateiname'
GO
exec DropColumn 'VertragsVorlagen', 'VertragsVorlagenTS'
GO
exec DropColumn 'VertragsVorlagen', 'TemplateId'
GO
exec DropColumn 'VertragsVorlagen', 'AZSA'
GO
exec DropColumn 'VertragsVorlagen', 'AZFR'
GO
exec DropColumn 'VertragsVorlagen', 'AZDO'
GO
exec DropColumn 'VertragsVorlagen', 'AZMI'
GO
exec DropColumn 'VertragsVorlagen', 'AZDI'
GO
exec DropColumn 'VertragsVorlagen', 'AZMO'
GO
exec DropColumn 'VertragsVorlagen', 'AZSO'
GO
exec DropColumn 'DienstplanArtenTabelle', 'Printer'
GO
exec DropColumn 'DienstplanArtenTabelle', 'WoAbrechnung'
GO
exec DropColumn 'DienstplanArtenTabelle', 'cNew'
GO
exec DropColumn 'DienstplanArtenTabelle', 'cEdit'
GO
exec DropColumn 'DienstplanArtenTabelle', 'cDel'
GO
exec DropColumn 'DienstplanArtenTabelle', 'Hintergrund'
GO
exec DropColumn 'DienstplanArtenTabelle', 'KopfZeilen'
GO
exec DropColumn 'DienstplanArtenTabelle', 'ZeitenOben'
GO
exec DropColumn 'DienstplanArtenTabelle', 'ZeitenOben'
GO
exec DropColumn 'DienstplanArtenTabelle', 'TransportBez'
GO
exec DropColumn 'DienstplanArtenTabelle', 'BemIn1Zeile'
GO
exec DropColumn 'VertragRolle', 'Ausstattungskosten'
GO
exec DropColumn 'VertragRolle', 'BonusFee'
GO
exec DropColumn 'VertragRolle', 'HonorarIst'
GO
exec DropColumn 'VertragDetails', 'HonorarUeberspiel'
GO
exec DropColumn 'VertragDetails', 'VertragDetailsTS'
GO
exec DropColumn 'VertragRolle', 'VertragRolleTS'
GO
exec DropColumn 'StückeDetails', 'Verlag'
GO
exec DropColumn 'StückeDetails', 'Tantieme'
GO
--#endregion

--#region 20170927 PersKat

IF  EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Bem' and o.id = OBJECT_ID(N'dbo.PersKat'))
BEGIN

	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[persKat]') AND o.Name = '_1CA611A6_BD03_11D2_BA7D_00400')  DROP INDEX  persKat._1CA611A6_BD03_11D2_BA7D_00400
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[persKat]') AND o.Name = 'Sparte')  DROP INDEX  persKat.Sparte
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[persKat]') AND o.Name = 'PK_PersKat')  DROP INDEX  persKat.PK_PersKat
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[persKat]') AND o.Name = 'IX_ContactCategory_ShortName')  DROP INDEX  persKat.IX_ContactCategory_ShortName
	IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.FK_PersKat_Sparte') AND type = 'F') ALTER TABLE dbo.persKat DROP CONSTRAINT FK_PersKat_Sparte
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[persKat]') AND o.Name = 'PersKat')  DROP INDEX persKat.PersKat
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[persKat]') AND o.Name = 'zaehler')  DROP INDEX persKat.zaehler

	ALTER TABLE persKat ALTER COLUMN PersKat VARCHAR(32) NOT NULL
	ALTER TABLE persKat ALTER COLUMN PersKatLang VARCHAR(60) NOT NULL
	ALTER TABLE persKat ALTER COLUMN AdressArt TINYINT NOT NULL
	CREATE UNIQUE INDEX IX_ContactCategory_ShortName ON PersKat (PersKat) ON [PRIMARY]
	ALTER TABLE persKat DROP COLUMN Bem
END
GO
exec DropColumn 'persKat', 'SparteID'
GO
--#endregion

--#region 20170927 Typ
IF  EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Sonderveranstaltungen' and o.id = OBJECT_ID(N'dbo.Typ'))
BEGIN

	IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[Typ]') AND o.Name = '_1CA611A7_BD03_11D2_BA7D_00400')  DROP INDEX  Typ._1CA611A7_BD03_11D2_BA7D_00400
	IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[Typ]') AND o.Name = 'PK_Typbez')  DROP INDEX  Typ.PK_Typbez
	IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[Typ]') AND o.Name = 'SparteID')  DROP INDEX  Typ.SparteID
	IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[Typ]') AND o.Name = 'IX_Typ_Name')  DROP INDEX  Typ.IX_Typ_Name

	UPDATE Typ SET TypBez = '##' WHERE TypID = 0
	UPDATE Typ SET TypBez = 'ohne Name #' + CONVERT(VARCHAR(MAX),TypID)  WHERE TypBez IS NULL
	ALTER TABLE Typ ALTER COLUMN TypBez VARCHAR(32) NOT NULL
	CREATE UNIQUE INDEX IX_Typ_Name ON Typ (TypBez) ON [PRIMARY]
	
	UPDATE Typ SET Sonderveranstaltung = 0 WHERE Sonderveranstaltung IS NULL
	ALTER TABLE Typ ALTER COLUMN Sonderveranstaltung BIT NOT NULL
	ALTER TABLE dbo.Typ ADD CONSTRAINT DF_Typ_IsSpecialeEvent DEFAULT 0 FOR Sonderveranstaltung
	ALTER TABLE Typ ALTER COLUMN FormatSettings VARCHAR(MAX)  NULL

	ALTER TABLE Typ ALTER COLUMN SparteId INT NOT NULL
	CREATE  INDEX IX_Typ_GenreId ON Typ (SparteID) ON [PRIMARY]

	ALTER TABLE Typ DROP COLUMN AlleMandanten
	ALTER TABLE Typ DROP COLUMN TypTS
	ALTER TABLE Typ DROP COLUMN Sonderveranstaltungen
END
--#endregion

--#region 20171004 AbPersP
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.[AbPersP]'))	DROP VIEW dbo.[AbPersP]
GO

CREATE VIEW [dbo].[AbPersP]
AS
SELECT PNr, InWeb, MemoExtern_en, MemoExtern, UM, LM, LC, UC
FROM PersonalDetails
GO
GRANT SELECT ON [AbPersP] TO [public]
GO

ALTER PROCEDURE [dbo].[DeleteCast] 
	@CastId INT
AS
BEGIN
SET NOCOUNT ON
 
DECLARE @UserGroupId INT 
			
--BesitzerId der Rolle
SELECT @UserGroupId = Besitzer
	FROM BesetzungStd AS R INNER JOIN BesetzungTabelle AS C ON r.id = c.RolleID
	WHERE c.Id = @CastId

IF (dbo.GetCurrentPermission(@UserGroupId, 4) < 2) 
	BEGIN
		SELECT 1 AS Attribut, 'No Permission' AS MSG
	END
ELSE
	BEGIN 
		DELETE FROM CashCommandPos_Cast WHERE CastId = @CastId
		DELETE FROM CastCredits WHERE ServiceCastId = @CastId
		DELETE FROM CastCredits WHERE ReplacementCastId = @CastId
		DELETE FROM CastBonus WHERE CastId = @CastId
		UPDATE ContractDates SET  CastId = NULL WHERE CastId = @CastId
		DELETE FROM BesetzungTabelle WHERE Id = @CastId
	END
END	
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PersMasse]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE PersMasse
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Texte]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE Texte
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SpzBeTagesplan]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE SpzBeTagesplan
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[VertragsStammdaten]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE VertragsStammdaten
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UserZrAccess]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE UserZrAccess
GO
--#endregion

--#region 20171004 TK Account in ContractDateMaturities
IF  NOT EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'AccountId' and o.id = OBJECT_ID(N'dbo.ContractDateMaturities')) ALTER TABLE ContractDateMaturities ADD AccountId INT  --Später Not Null
GO

IF  NOT EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 4020)
BEGIN

IF EXISTS (SELECT * FROM ContractDateMaturities WHERE CostType = 0 AND AccountId IS NULL) 
	BEGIN
	  IF NOT EXISTS (SELECT * FROM Zeitkonten WHERE Formel = 4006) 
		BEGIN
			INSERT INTO Zeitkonten (Formel, Bez, Module, YearCloseTypeId) VALUES (4006, 'Sonstige Kosten', 307, (SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))
		END

		UPDATE ContractDateMaturities
		SET AccountId = (SELECT MIN(ZeitKtoNr) FROM Zeitkonten WHERE Formel = 4006 AND Module <> 0 AND Zeitkonten.Module&Gruppe.Modul = Gruppe.Modul)
		FROM ContractDateMaturities
			INNER JOIN ContractDates AS CD ON ContractDateMaturities.ContractDateId = cd.ContractDateId 
			INNER JOIN VertragRolle AS vr ON cd.ContractRoleId = vr.Vrid
			INNER JOIN Vertrag AS v ON vr.VertragsNr = v.Vertragsnr 
			INNER JOIN Gruppe ON V.ModulGruppeID = Gruppe.GruppeId
		WHERE ContractDateMaturities.CostType = 0 AND ContractDateMaturities.AccountId IS NULL

		UPDATE ContractDateMaturities
		SET AccountId = (SELECT MIN(ZeitKtoNr) FROM Zeitkonten WHERE Formel = 4006)
		FROM ContractDateMaturities
			INNER JOIN ContractDates AS CD ON ContractDateMaturities.ContractDateId = cd.ContractDateId 
			INNER JOIN VertragRolle AS vr ON cd.ContractRoleId = vr.Vrid
			INNER JOIN Vertrag AS v ON vr.VertragsNr = v.Vertragsnr 
			INNER JOIN Gruppe ON V.ModulGruppeID = Gruppe.GruppeId
		WHERE ContractDateMaturities.CostType = 0 AND ContractDateMaturities.AccountId IS NULL
	END
		UPDATE Zeitkonten SET [Formel] = 4020 , Settings =   
		  '<?xml version="1.0" encoding="utf-8"?>
		<FeeAndSalarySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
		  <MaturityCostType>MiscellaneousCosts</MaturityCostType>
		</FeeAndSalarySettings>'   WHERE Formel = 4006

	IF EXISTS (SELECT * FROM ContractDateMaturities WHERE CostType = 5  AND AccountId IS NULL) 
	BEGIN
	  IF NOT EXISTS (SELECT * FROM Zeitkonten WHERE Formel = 4005) 
		BEGIN
			INSERT INTO Zeitkonten (Formel, Bez, Module, YearCloseTypeId) VALUES (4005, 'Überspielhonorar',307, (SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))
		END

		UPDATE ContractDateMaturities
		SET AccountId = (SELECT MIN(ZeitKtoNr) FROM Zeitkonten WHERE Formel = 4005 AND Module <> 0 AND Zeitkonten.Module&Gruppe.Modul = Gruppe.Modul)
		FROM ContractDateMaturities
			INNER JOIN ContractDates AS CD ON ContractDateMaturities.ContractDateId = cd.ContractDateId 
			INNER JOIN VertragRolle AS vr ON cd.ContractRoleId = vr.Vrid
			INNER JOIN Vertrag AS v ON vr.VertragsNr = v.Vertragsnr 
			INNER JOIN Gruppe ON V.ModulGruppeID = Gruppe.GruppeId
		WHERE ContractDateMaturities.CostType = 5 AND ContractDateMaturities.AccountId IS NULL

		UPDATE ContractDateMaturities
		SET AccountId = (SELECT MIN(ZeitKtoNr) FROM Zeitkonten WHERE Formel = 4005)
		FROM ContractDateMaturities
			INNER JOIN ContractDates AS CD ON ContractDateMaturities.ContractDateId = cd.ContractDateId 
			INNER JOIN VertragRolle AS vr ON cd.ContractRoleId = vr.Vrid
			INNER JOIN Vertrag AS v ON vr.VertragsNr = v.Vertragsnr 
			INNER JOIN Gruppe ON V.ModulGruppeID = Gruppe.GruppeId
		WHERE ContractDateMaturities.CostType = 5 AND ContractDateMaturities.AccountId IS NULL

  END
	UPDATE Zeitkonten SET [Formel] = 4020 , Settings =   
		'<?xml version="1.0" encoding="utf-8"?>
	<FeeAndSalarySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
		<MaturityCostType>ExtraFee</MaturityCostType>
	</FeeAndSalarySettings>'
	WHERE Formel = 4005


  IF EXISTS (SELECT * FROM ContractDateMaturities WHERE CostType = 4 AND AccountId IS NULL) 
  BEGIN

	  IF NOT EXISTS (SELECT * FROM Zeitkonten WHERE Formel = 4004) 
		BEGIN
			INSERT INTO Zeitkonten (Formel, Bez, Module, YearCloseTypeId) VALUES (4004, 'Übernachtungskosten', 307, (SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))
		END

		UPDATE ContractDateMaturities
		SET AccountId = (SELECT MIN(ZeitKtoNr) FROM Zeitkonten WHERE Formel = 4004 AND Module <> 0 AND Zeitkonten.Module&Gruppe.Modul = Gruppe.Modul)
		FROM ContractDateMaturities
			INNER JOIN ContractDates AS CD ON ContractDateMaturities.ContractDateId = cd.ContractDateId 
			INNER JOIN VertragRolle AS vr ON cd.ContractRoleId = vr.Vrid
			INNER JOIN Vertrag AS v ON vr.VertragsNr = v.Vertragsnr 
			INNER JOIN Gruppe ON V.ModulGruppeID = Gruppe.GruppeId
		WHERE ContractDateMaturities.CostType = 4 AND ContractDateMaturities.AccountId IS NULL

		UPDATE ContractDateMaturities
		SET AccountId = (SELECT MIN(ZeitKtoNr) FROM Zeitkonten WHERE Formel = 4004)
		FROM ContractDateMaturities
			INNER JOIN ContractDates AS CD ON ContractDateMaturities.ContractDateId = cd.ContractDateId 
			INNER JOIN VertragRolle AS vr ON cd.ContractRoleId = vr.Vrid
			INNER JOIN Vertrag AS v ON vr.VertragsNr = v.Vertragsnr 
			INNER JOIN Gruppe ON V.ModulGruppeID = Gruppe.GruppeId
		WHERE ContractDateMaturities.CostType = 4 AND ContractDateMaturities.AccountId IS NULL
  END
	UPDATE Zeitkonten SET [Formel] = 4020 , Settings =   
			'<?xml version="1.0" encoding="utf-8"?>
		<FeeAndSalarySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
			<MaturityCostType>AccommodationCosts</MaturityCostType>
		</FeeAndSalarySettings>'
		WHERE Formel =4004

IF EXISTS (SELECT * FROM ContractDateMaturities WHERE CostType = 3 AND AccountId IS NULL) 
  BEGIN
	  IF NOT EXISTS (SELECT * FROM Zeitkonten WHERE Formel = 4003) 
		BEGIN
			INSERT INTO Zeitkonten (Formel, Bez, Module, YearCloseTypeId) VALUES (4003, 'Reisekosten', 307, (SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))
		END

		UPDATE ContractDateMaturities
		SET AccountId = (SELECT MIN(ZeitKtoNr) FROM Zeitkonten WHERE Formel = 4003 AND Module <> 0 AND Zeitkonten.Module&Gruppe.Modul = Gruppe.Modul)
		FROM ContractDateMaturities
			INNER JOIN ContractDates AS CD ON ContractDateMaturities.ContractDateId = cd.ContractDateId 
			INNER JOIN VertragRolle AS vr ON cd.ContractRoleId = vr.Vrid
			INNER JOIN Vertrag AS v ON vr.VertragsNr = v.Vertragsnr 
			INNER JOIN Gruppe ON V.ModulGruppeID = Gruppe.GruppeId
		WHERE ContractDateMaturities.CostType = 3 AND ContractDateMaturities.AccountId IS NULL

		UPDATE ContractDateMaturities
		SET AccountId = (SELECT MIN(ZeitKtoNr) FROM Zeitkonten WHERE Formel = 4003)
		FROM ContractDateMaturities
			INNER JOIN ContractDates AS CD ON ContractDateMaturities.ContractDateId = cd.ContractDateId 
			INNER JOIN VertragRolle AS vr ON cd.ContractRoleId = vr.Vrid
			INNER JOIN Vertrag AS v ON vr.VertragsNr = v.Vertragsnr 
			INNER JOIN Gruppe ON V.ModulGruppeID = Gruppe.GruppeId
		WHERE ContractDateMaturities.CostType = 3 AND ContractDateMaturities.AccountId IS NULL
  END
	UPDATE Zeitkonten SET [Formel] = 4020 , Settings =   
			  '<?xml version="1.0" encoding="utf-8"?>
			<FeeAndSalarySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
			  <MaturityCostType>TravelCosts</MaturityCostType>
			</FeeAndSalarySettings>'
	WHERE Formel =4003

  IF EXISTS (SELECT * FROM ContractDateMaturities WHERE CostType = 1) 
  BEGIN
	  IF NOT EXISTS (SELECT * FROM Zeitkonten WHERE Formel = 4002) 
		BEGIN
			INSERT INTO Zeitkonten (Formel, Bez, Module, YearCloseTypeId) VALUES (4002, 'Probenhonorar', 307, (SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))
		END

		UPDATE ContractDateMaturities
		SET AccountId = (SELECT MIN(ZeitKtoNr) FROM Zeitkonten WHERE Formel = 4002 AND Module <> 0 AND Zeitkonten.Module&Gruppe.Modul = Gruppe.Modul)
		FROM ContractDateMaturities
			INNER JOIN ContractDates AS CD ON ContractDateMaturities.ContractDateId = cd.ContractDateId 
			INNER JOIN VertragRolle AS vr ON cd.ContractRoleId = vr.Vrid
			INNER JOIN Vertrag AS v ON vr.VertragsNr = v.Vertragsnr 
			INNER JOIN Gruppe ON V.ModulGruppeID = Gruppe.GruppeId
		WHERE ContractDateMaturities.CostType = 1 AND ContractDateMaturities.AccountId IS NULL

		UPDATE ContractDateMaturities
		SET AccountId = (SELECT MIN(ZeitKtoNr) FROM Zeitkonten WHERE Formel = 4002)
		FROM ContractDateMaturities
			INNER JOIN ContractDates AS CD ON ContractDateMaturities.ContractDateId = cd.ContractDateId 
			INNER JOIN VertragRolle AS vr ON cd.ContractRoleId = vr.Vrid
			INNER JOIN Vertrag AS v ON vr.VertragsNr = v.Vertragsnr 
			INNER JOIN Gruppe ON V.ModulGruppeID = Gruppe.GruppeId
		WHERE ContractDateMaturities.CostType = 1 AND ContractDateMaturities.AccountId IS NULL
  END
  
	UPDATE Zeitkonten SET [Formel] = 4020 , Settings =   
		'<?xml version="1.0" encoding="utf-8"?>
	<FeeAndSalarySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
		<MaturityCostType>RehearsalFee</MaturityCostType>
	</FeeAndSalarySettings>'
		WHERE Formel = 4002

  IF EXISTS (SELECT * FROM ContractDateMaturities WHERE CostType = 2) 
  BEGIN
	  IF NOT EXISTS (SELECT * FROM Zeitkonten WHERE Formel = 4001) 
		BEGIN
			INSERT INTO Zeitkonten (Formel, Bez, Module, YearCloseTypeId) VALUES (4001, 'Vst. Honorar', 307, (SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))
		END

		UPDATE ContractDateMaturities
		SET AccountId = (SELECT MIN(ZeitKtoNr) FROM Zeitkonten WHERE Formel = 4001 AND Module <> 0 AND Zeitkonten.Module&Gruppe.Modul = Gruppe.Modul)
		FROM ContractDateMaturities
			INNER JOIN ContractDates AS CD ON ContractDateMaturities.ContractDateId = cd.ContractDateId 
			INNER JOIN VertragRolle AS vr ON cd.ContractRoleId = vr.Vrid
			INNER JOIN Vertrag AS v ON vr.VertragsNr = v.Vertragsnr 
			INNER JOIN Gruppe ON V.ModulGruppeID = Gruppe.GruppeId
		WHERE ContractDateMaturities.CostType = 2 AND ContractDateMaturities.AccountId IS NULL

		UPDATE ContractDateMaturities
		SET AccountId = (SELECT MIN(ZeitKtoNr) FROM Zeitkonten WHERE Formel = 4001)
		FROM ContractDateMaturities
			INNER JOIN ContractDates AS CD ON ContractDateMaturities.ContractDateId = cd.ContractDateId 
			INNER JOIN VertragRolle AS vr ON cd.ContractRoleId = vr.Vrid
			INNER JOIN Vertrag AS v ON vr.VertragsNr = v.Vertragsnr 
			INNER JOIN Gruppe ON V.ModulGruppeID = Gruppe.GruppeId
		WHERE ContractDateMaturities.CostType = 2 AND ContractDateMaturities.AccountId IS NULL
  END
  
	  UPDATE Zeitkonten SET [Formel] = 4020 , Settings =   
	  '<?xml version="1.0" encoding="utf-8"?>
	<FeeAndSalarySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
	  <MaturityCostType>PerformanceFee</MaturityCostType>
	</FeeAndSalarySettings>'
	  WHERE Formel =4001

END

ALTER TABLE ContractDateMaturities ALTER COLUMN  AccountId INT NOT NULL
GO

ALTER VIEW [dbo].[AbContractDateMaturities]
AS 
SELECT
	cdm.ContractDateId,
	CASE WHEN UG.HasFeesPermission = 1 THEN cdm.[Description] ELSE '********' END AS [Description],
	CASE WHEN UG.HasFeesPermission = 1 THEN cdm.Amount ELSE -1 END AS Amount,
	cdm.LC,
	cdm.UC,
	cdm.LM,
	cdm.UM,
	AccountId
FROM
	ContractDateMaturities cdm
	INNER JOIN ContractDates cd ON cdm.ContractDateId = cd.ContractDateId
	INNER JOIN VertragRolle vr ON cd.ContractRoleId = vr.VRID
	INNER JOIN Vertrag AS v ON VR.VertragsNr = v.VertragsNr  
	INNER JOIN	(SELECT GruppeID, Schreiben, (CASE WHEN OptionsFlag & 1 <> 1 THEN 0 ELSE 1 END) AS HasFeesPermission
						FROM			UserGruppe 
						INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
						WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 1) AS UG
				ON v.ModulGruppeID = UG.GruppeID
go
--#endregion

--#region 20171010 TK FK User mit primärer Gruppe
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_User_Groups') AND type = 'F')
BEGIN
	UPDATE Userpw SET PriGruppeID = NULL  WHERE NOT PriGruppeID IS NULL AND  NOT EXISTS(SELECT * FROM Gruppe WHERE Gruppeid = PriGruppeID)
	ALTER TABLE dbo.Userpw ADD CONSTRAINT	FK_User_Groups FOREIGN KEY	(PriGruppeID) REFERENCES dbo.Gruppe	(Gruppeid) ON UPDATE  NO ACTION 	 ON DELETE SET NULL
END
--#endregion

--#region 20171010 TK Adress Sort index entfernt
GO
IF  EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.[PersAdresse]') AND o.Name = 'IX_PersNr_Sort') DROP INDEX PersAdresse.IX_PersNr_Sort
GO
--#endregion

--#endregion (4.174)

--#region ----------- 4.174.x Release Übertrag ----------------

--#region bm 20170922 Bugfix in View
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].PersonModulGroupPermission_Update'))
BEGIN
	DROP VIEW [dbo].[PersonModulGroupPermission_Update]
END
GO

CREATE VIEW [dbo].[PersonModulGroupPermission_Update]
AS
	SELECT * FROM PersonModulGroupPermission 
	WHERE PersonId IN 
		(SELECT p.PersNr 
			FROM PersH AS P 
				INNER JOIN UserGruppe AS UG ON p.Besitzer = UG.GruppeID 
				INNER JOIN UserPw as PW ON UG.UserID = PW.UserID 
			WHERE ug.BerechtigungsbereichID = 0 AND PW.UserName = CURRENT_USER AND ug.Schreiben = 1)
WITH CHECK OPTION
GO

GRANT SELECT, DELETE, UPDATE, INSERT ON PersonModulGroupPermission_Update TO Public
GO

--#endregion

--#region 20171010 Exporte ausblenden
UPDATE [Plan] SET planArt = 5 WHERE NOT PlanExportId IS NULL AND PlanExportId > 0 AND planArt <> 5
GO
--#endregion

--#region bm 20170928 Berechtigungen Zusatzdatentypen überarbeitet
REVOKE SELECT, DELETE, UPDATE, INSERT ON [AbPersZusatzDatenTyp_Update] TO Public
REVOKE SELECT, DELETE, UPDATE, INSERT ON [AbPersZusatzDatenTyp_Update] TO [dispoadmin]
REVOKE SELECT, DELETE, UPDATE, INSERT ON [AbPersZusatzDatenTyp_Update] TO [soli-daten ändern]
GRANT SELECT, DELETE, UPDATE, INSERT ON [AbPersZusatzDatenTyp_Update] TO [MasterAdmin]
GO
--#endregion

--#region 20171012 
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbBasicCast')) DROP VIEW dbo.AbBasicCast
GO
CREATE VIEW [dbo].AbBasicCast
	AS
	SELECT s.BesetzungStdSoliID AS BasicCastId, s.RolleId AS RoleId, s.SpzNr AS SeasonId, s.BesSort AS OrderIndex, s.UnderstudyPosition,
		PersNr1 AS PersonId,
		 s.Gesperrt | IsPerson1Locked AS IsLocked,
		 s.Note, s.LM, s.UM, s.LC, s.UC
	FROM  BesetzungStdSoliTabelle AS S 
		INNER JOIN BesetzungStd AS R ON S.RolleID = R.Id
		INNER JOIN Gruppe AS G ON R.Besitzer = G.GruppeID
		INNER JOIN UserGruppe AS Ug ON G.GruppeID = Ug.GruppeID  
		INNER JOIN UserPW ON Ug.Userid = UserPW.Userid 
	WHERE   BerechtigungsbereichID = 4 AND UserPW.Username = CURRENT_USER AND (s.Gesperrt | IsPerson1Locked = 0 OR Ug.OptionsFlag&1 = 1) 
GO

GRANT SELECT ON AbBasicCast TO PUBLIC
GO
--#endregion

--#region dh 20171010 Fehler bei Aufgabenbereiche anlegen, Not null spalte wird nicht mehr gefüllt.
DropColumn  'RollenLtg','StdPro'
GO
--#endregion

--#region dh 20171020 Trigger für Order und Orderpos Tabelle, kein Löschen von Bestellungen mit Bestellnummer.
IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'TR' AND name = 'delete_Orders')
BEGIN
EXEC ('
CREATE TRIGGER delete_Orders ON dbo.orders AFTER DELETE 
AS 
BEGIN
IF EXISTS(SELECT Ordernumber FROM deleted WHERE Ordernumber IS NOT NULL) 
ROLLBACK TRANSACTION
END');
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'TR' AND name = 'delete_Orderspos')
BEGIN
EXEC ('
CREATE TRIGGER delete_Orderspos ON dbo.orderPos AFTER DELETE 
AS 
BEGIN
IF EXISTS(SELECT o.Ordernumber FROM deleted INNER JOIN orders o ON deleted.OrderId=o.OrderId WHERE Ordernumber IS NOT NULL) 
ROLLBACK TRANSACTION
END');
END
GO
--#endregion

--#region tk 20171025 Teile einses Scriptes aus 2015
DropColumn 'BesetzungTabelle', 'BesetzungTS'
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[BesetzungTabelle]') AND o.Name = 'IX_Cast_RoleId')
BEGIN
	IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[BesetzungTabelle]') AND o.Name = 'IX_RolleId') DROP INDEX BesetzungTabelle.IX_RolleId
	ALTER TABLE BesetzungTabelle ALTER COLUMN RolleId INT NOT NULL
	CREATE INDEX IX_Cast_RoleId ON dbo.BesetzungTabelle (RolleId) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[BesetzungTabelle]') AND o.Name = 'IX_Cast_PersonId')
BEGIN
	IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[BesetzungTabelle]') AND o.Name = 'IX_PersNr')  DROP INDEX BesetzungTabelle.IX_PersNr
	ALTER TABLE BesetzungTabelle ALTER COLUMN PersNr INT NOT NULL
	CREATE INDEX IX_Cast_PersonId ON dbo.BesetzungTabelle (PersNr) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[BesetzungTabelle]') AND o.Name = 'IX_Cast_ActivityId')
BEGIN
	IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[BesetzungTabelle]') AND o.Name = 'IX_AuffNr')  DROP INDEX BesetzungTabelle.IX_AuffNr
	DELETE FROM BesetzungTabelle WHERE Auffnr IS NULL
	ALTER TABLE BesetzungTabelle ALTER COLUMN AuffNr INT NOT NULL
	CREATE INDEX IX_Cast_ActivityId ON dbo.BesetzungTabelle (AuffNr) ON [PRIMARY]
END 
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[BesetzungTabelle]') AND o.Name = 'IX_Cast_ActivityId_RoleId')
	CREATE INDEX IX_Cast_ActivityId_RoleId ON dbo.BesetzungTabelle (AuffNr, RolleId) ON [PRIMARY]
GO 
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[BesetzungStd]') AND o.Name = 'IX_Roles_RoleId_OwnerId') 
	CREATE INDEX IX_Roles_RoleId_OwnerId ON dbo.BesetzungStd (Id, Besitzer) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[BesetzungStd]') AND o.Name = 'IX_Roles_ProductionId')
BEGIN
	IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[BesetzungStd]') AND o.Name = 'IX_Snr')  DROP INDEX BesetzungStd.IX_Snr
	ALTER TABLE BesetzungStd ALTER COLUMN SNR INT NOT NULL
	CREATE INDEX IX_Roles_ProductionId ON dbo.BesetzungStd (Snr) ON [PRIMARY]
END 	
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[XHDelAufführg]') AND o.Name = 'IX_ActivityHistory_Date') --!!!!
BEGIN
	ALTER TABLE [dbo].[XHDelAufführg] DROP CONSTRAINT [PRIMARYKEY_XHDelAufführg]
	DROP INDEX [IX_Date] ON [dbo].[XHDelAufführg]
	CREATE CLUSTERED INDEX [IX_ActivityHistory_Date] ON [dbo].[XHDelAufführg] ([Datum] ASC)	 
	ALTER TABLE dbo.XHDelAufführg ADD CONSTRAINT PK_ActivityHistory_XHId PRIMARY KEY (XHID) ON [PRIMARY]
	UPDATE XHDelAufführg SET Gesperrt = AufführgTabelle.Gesperrt  FROM XHDelAufführg INNER JOIN AufführgTabelle ON XHDelAufführg.AuffNr = AufführgTabelle.AuffNr
	UPDATE XHDelAufführg SET Gesperrt = 0 WHERE Gesperrt IS NULL

	ALTER TABLE XHDelAufführg ALTER COLUMN Gesperrt BIT NOT NULL 
	ALTER TABLE XHDelAufführg ADD CONSTRAINT DF_XHDelAufführg_gesperrt DEFAULT 0 FOR Gesperrt
	
	DROP INDEX [IX_UC_Tabl] ON [dbo].[KenntnisDel]
	CREATE NONCLUSTERED INDEX [IX_UC_Tabl] ON [dbo].[KenntnisDel] (	[UC] ASC,	[Tabl] ASC) INCLUDE ( [XHID])  ON [PRIMARY]
	
	CREATE NONCLUSTERED INDEX IX_Production_OwnerId_WithProductionId ON [dbo].[Stücke] ([ModuleGroupId] ASC)INCLUDE ( [SNr])

	EXEC('sp_refreshview besetzung')
END 
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.oAufführg'))	DROP VIEW [dbo].oAufführg
GO
--#endregion

--#endregion (4.174.x Release)

--#region ----------- 4.175.x ---------------------------------

--#region DH 201709
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[GroupSettings]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[GroupSettings](
	[GroupSettingId] [int] IDENTITY(1,1) NOT NULL,
	[GroupId] [int] NOT NULL,
	[SettingsKey] [varchar](30) NOT NULL,
	[SettingSection] [varchar](30) NOT NULL,
	[SettingsXML] [xml] NOT NULL,
	[PermissionAreaId] [int] NOT NULL,
	[LM] [datetime] NOT NULL,
	[UM] [int] NOT NULL,
	[LC] [datetime] NOT NULL,
	[UC] [int] NOT NULL,
 CONSTRAINT [PK_GroupSettings] PRIMARY KEY NONCLUSTERED 
(
	[GroupSettingId] ASC
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

ALTER TABLE [dbo].[GroupSettings]  WITH CHECK ADD  CONSTRAINT [FK_GroupSettings_Group_Group] FOREIGN KEY([GroupId])
REFERENCES [dbo].[Gruppe] ([GruppeID])

ALTER TABLE [dbo].[GroupSettings] CHECK CONSTRAINT [FK_GroupSettings_Group_Group]
END
GO
IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME='IX_GroupSetting_PermissionAreaID_GroupID_SettingSection_Settingskey') 
BEGIN
CREATE UNIQUE CLUSTERED INDEX [IX_GroupSetting_PermissionAreaID_GroupID_SettingSection_Settingskey] ON [dbo].[GroupSettings]
(
	[PermissionAreaID] ASC,
	[GroupId] ASC,
	[SettingSection] ASC,
	[SettingsKey] ASC
)
END
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.[ABGroupSettings]'))	DROP VIEW [dbo].[ABGroupSettings]
GO
CREATE VIEW [dbo].[ABGroupSettings]
		AS
	SELECT	GroupSettings.*
	FROM	GroupSettings
	WHERE EXISTS (
			SELECT * FROM GroupSettings AS R
					INNER JOIN Gruppe AS G ON R.GroupId  = G.GruppeID
					INNER JOIN UserGruppe AS Ug ON G.GruppeID = Ug.GruppeID   
					INNER JOIN UserPW ON Ug.Userid  = UserPW.Userid 
					WHERE ug.BerechtigungsbereichID = 11 AND UserPW.Username = CURRENT_USER  AND R.GroupSettingId = GroupSettings.GroupSettingId)
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.[ABGroupSettings_Update]'))	DROP VIEW [dbo].[ABGroupSettings_Update]
GO
CREATE VIEW [dbo].[ABGroupSettings_Update]
		AS
	SELECT	GroupSettings.*
	FROM	GroupSettings
	WHERE EXISTS (
			SELECT * FROM GroupSettings AS R
					INNER JOIN Gruppe AS G ON R.GroupId  = G.GruppeID
					INNER JOIN UserGruppe AS Ug ON G.GruppeID = Ug.GruppeID   
					INNER JOIN UserPW ON Ug.Userid  = UserPW.Userid 
					WHERE ug.BerechtigungsbereichID = 11 AND ug.Schreiben = 1  AND UserPW.Username = CURRENT_USER  AND R.GroupSettingId = GroupSettings.GroupSettingId ) 
WITH CHECK OPTION
GO
GRANT SELECT ON ABGROUpSettings to [public]
GO
GRANT SELECT,DELETE,UPDATE,INSERT ON [ABGroupSettings_Update] To public
--#endregion

--#region bm 20171009 Überstunden und -Zuschläge eines Tarifs als XML-Setting
IF NOT EXISTS (SELECT * FROM TimeAccountsTarifsSettings as t inner join Zeitkonten as a on t.TimeAccountId = a.ZeitKtoNr WHERE Formel IN (1252,1253,1210)) AND EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 175 OR (Minor = 175 AND Build < 2)))))
BEGIN
--delete from TimeAccountsTarifsSettings
	IF EXISTS (SELECT * FROM Zeitkonten where Formel = 1252)
	BEGIN
		--Überstunden übernehmen

		insert into TimeAccountsTarifsSettings (timeaccountid, TarifId, LC, UC, LM, UM, XMLSettings)
		select a.ZeitKtoNr, PersoParameterID, GETDATE(), -1, GETDATE(), -1, '<?xml version="1.0" encoding="utf-8"?>
		<OvertimeTimeAccountSettings> 
		<OvertimeType>' + CONVERT(VARCHAR(MAX), CASE WHEN p.Ueberstd = 10 THEN 10  WHEN a.WoAbrechnung = 1 OR p.Ueberstd NOT IN (3) THEN 0 ELSE p.Ueberstd END ) +'</OvertimeType>
		<PrintDailyValues>' + CASE WHEN a.WoAbrechnung = 0 AND p.Ueberstd <> 2 THEN 'true' ELSE 'false' END +'</PrintDailyValues>
		<OnlyDaysWithWorkingTime>' + CASE WHEN p.Ueberstd = 8 THEN 'true' ELSE 'false' END  +'</OnlyDaysWithWorkingTime>
		</OvertimeTimeAccountSettings>'
		from PersoParameter as p cross join Zeitkonten as a 
		where a.Formel = 1252 AND p.Module = 4
	END
	
	IF EXISTS (SELECT * FROM Zeitkonten where Formel = 1253)
	BEGIN
		--Überstundenzuschläge übernehmen

		insert into TimeAccountsTarifsSettings (timeaccountid, TarifId, LC, UC, LM, UM, XMLSettings)
		select a.ZeitKtoNr, PersoParameterID, GETDATE(), -1, GETDATE(), -1, 
		 '<?xml version="1.0" encoding="utf-8"?>
		<OvertimeBonusTimeAccountSettings>' + 
		'<OvertimeBonus>' + CONVERT(VARCHAR(MAX), p.Garantiestunden) + '</OvertimeBonus>' +
		'<DailyOvertimeBonusFromMinutes>' + CONVERT(VARCHAR(MAX), ROUND(p.UeberStdAb * 60, 0)) + '</DailyOvertimeBonusFromMinutes>' +
		'<WeeklyOrMonthlyOvertimeBonusFromMinutes>' + CONVERT(VARCHAR(MAX), ROUND(p.MehrAzBis * 60, 0)) + '</WeeklyOrMonthlyOvertimeBonusFromMinutes>' +
		case p.OvertimePremiumIsFixValue when 0 then '<IsWeeklyOvertimeBonusFixValue>false</IsWeeklyOvertimeBonusFixValue>' else '<IsWeeklyOvertimeBonusFixValue>true</IsWeeklyOvertimeBonusFixValue>' end +
		'</OvertimeBonusTimeAccountSettings>'
		from PersoParameter as p cross join Zeitkonten as a 
		where a.Formel = 1253 AND p.Module = 4
	END

	IF EXISTS (SELECT * FROM Zeitkonten where Formel = 1210)
	BEGIN
		--TäglicheStunden übernehmen
		
		insert into TimeAccountsTarifsSettings (timeaccountid, TarifId, LC, UC, LM, UM, XMLSettings)
		select a.ZeitKtoNr, PersoParameterID, GETDATE(), -1, GETDATE(), -1,
			REPLACE(CONVERT(VARCHAR(MAX),a.settings),'</DailyOvertimeSettings>', 
			'<WeeklyOvertimeBonusFromMinutes >' + CONVERT(VARCHAR(MAX), ROUND(p.MehrAzBis * 60, 0)) + '</WeeklyOvertimeBonusFromMinutes >' +
			case p.OvertimePremiumIsFixValue when 0 then '<IsWeeklyOvertimeBonusFixValue>false</IsWeeklyOvertimeBonusFixValue>' else '<IsWeeklyOvertimeBonusFixValue>true</IsWeeklyOvertimeBonusFixValue>' end +
			 '</DailyOvertimeSettings>') 
			from PersoParameter as p cross join Zeitkonten as a 
		where a.Formel = 1210  AND NOT a.Settings IS NULL AND MehrAzBis > 0 AND p.Module = 4 AND  CONVERT(VARCHAR(MAX),a.settings) Like '%<OnlyIfNoWeeklyOvertime>true</OnlyIfNoWeeklyOvertime>%'
	
	END
	IF EXISTS (SELECT * FROM Zeitkonten where Formel = 1251)
	BEGIN
		--Mehr Az -> 1251
		insert into TimeAccountsTarifsSettings (timeaccountid, TarifId, LC, UC, LM, UM, XMLSettings)
		select  a.ZeitKtoNr, PersoParameterID, GETDATE(), -1, GETDATE(), -1,
			'<?xml version="1.0" encoding="utf-8"?>  <WeeklyOvertimeSettings>  <FromMinutes>' + CONVERT(VARCHAR(MAX), ROUND(p.MehrAzBis * 60, 0)) + '</FromMinutes>'   
		+ case p.OvertimePremiumIsFixValue when 0 then '<IsWeeklyOvertimeBonusFixValue>false</IsWeeklyOvertimeBonusFixValue>' else '<IsWeeklyOvertimeBonusFixValue>true</IsWeeklyOvertimeBonusFixValue>' end + ' </WeeklyOvertimeSettings>'
		from PersoParameter as p cross join Zeitkonten as a 
		where a.Formel = 1251 AND MehrAzBis > 0 AND p.Module = 4
		
	END
	UPDATE Zeitkonten SET Formel = 1215 WHERE Formel = 1251 
		--Alte Spalten entfernen
	--exec dropcolumn 'PersoParameter', 'Ueberstd'
	--exec dropcolumn 'PersoParameter', 'UeberStdAb'
	--exec dropcolumn 'PersoParameter', 'MehrAzBis'
	--exec dropcolumn 'PersoParameter', 'OvertimePremiumIsFixValue'
	--exec dropcolumn 'PersoParameter', 'Garantiestunden'
END


exec dropcolumn 'RapportSpalte', 'x'
exec dropcolumn 'RapportSpalte', 'inMinuten'
GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.Auftritte20032004'))	DROP VIEW dbo.Auftritte20032004
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.Auftritte20032004'))	DROP VIEW dbo.Vorstellungen20032004
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.ZulagenDispo'))	DROP TABLE dbo.ZulagenDispo
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.OrchDienste'))	DROP TABLE dbo.OrchDienste
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.SpzBeTagesplan'))	DROP TABLE dbo.SpzBeTagesplan
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.VertragsBesetzungsHonorar'))	DROP TABLE dbo.VertragsBesetzungsHonorar
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.VertragsStammdaten'))	DROP TABLE dbo.VertragsStammdaten
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AllocateExtraFee')) 	DROP PROCEDURE dbo.AllocateExtraFee 
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AllocateFee')) 	DROP PROCEDURE dbo.AllocateFee
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.sp_Besetzung_Del')) 	DROP PROCEDURE dbo.sp_Besetzung_New
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.sp_Besetzung_del')) 	DROP PROCEDURE dbo.sp_Besetzung_del
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.sp_Besetzung_edit')) 	DROP PROCEDURE dbo.sp_Besetzung_edit
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.InherhitPermissions')) 	DROP PROCEDURE dbo.InherhitPermissions

GO
EXEC sp_refreshview 'ActivitiesUpdate'
GO

ALTER PROCEDURE [dbo].[DeleteProduction]
	@ProductionId INT
AS
BEGIN
SET NOCOUNT ON

DECLARE @UserGroup int
SELECT @UserGroup = ModuleGroupId FROM Stücke WHERE Snr = @ProductionId

--Berechtigungsprüfung
IF (dbo.GetCurrentPermission(@UserGroup, 3) < 2 ) 
	BEGIN
		SELECT 1 AS Attribut, 'No Permission' AS MSG
	END
ELSE
	BEGIN 
		IF (@ProductionId = 0)	
			BEGIN
				SELECT 0 AS Attribut,'Keine gültige Produktion übergeben (Id 0)' AS MSG
			END
		ELSE
			BEGIN
				DELETE FROM BesetzungStdSoliTabelle WHERE RolleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId)
				DELETE FROM VertragRolle WHERE RolleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId)
				DELETE FROM BesRepertoire WHERE RolleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId)
				DELETE FROM ContractDateConfirmations WHERE ContractDateId IN (SELECT ContractDateId FROM ContractDates WHERE CastId IN (SELECT ID FROM BesetzungTabelle WHERE RolleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId)))
				DELETE FROM ContractDates WHERE CastId IN (SELECT ID FROM BesetzungTabelle WHERE RolleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId))
				DELETE FROM CastBonus WHERE CastId IN (SELECT ID FROM BesetzungTabelle WHERE RolleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId))
				DELETE FROM CashCommandPos_Cast WHERE CastId IN (SELECT ID FROM BesetzungTabelle WHERE RolleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId))
				DELETE FROM CastCredits WHERE ServiceCastId IN (SELECT ID FROM BesetzungTabelle WHERE RolleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId))
				DELETE FROM CastCredits WHERE ReplacementCastId IN (SELECT ID FROM BesetzungTabelle WHERE RolleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId))
				UPDATE ContractDates SET  CastId = NULL WHERE CastId IN (SELECT ID FROM BesetzungTabelle WHERE RolleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId))
				DELETE FROM BesetzungTabelle WHERE RolleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId)
				DELETE FROM AuffTechAufgabe WHERE RolleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId)
				DELETE FROM RoleBonus WHERE RoleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId)
				DELETE FROM Role_Season WHERE RoleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId)
				DELETE FROM Roles_Scenes WHERE RoleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId)
				DELETE FROM Qualification_Role WHERE RoleId IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId)
				DELETE FROM BesetzungStd WHERE ID IN (SELECT ID FROM BesetzungStd WHERE Snr = @ProductionId)	
				DELETE FROM StückeTeil WHERE Snr = @ProductionId
				DELETE FROM StückeTeil WHERE SnrTeil = @ProductionId
				DELETE FROM ActivityScenes WHERE ActivityId IN (SELECT AuffNr FROM AufführgTabelle WHERE Snr = @ProductionId)
				DELETE FROM AuffDienstplanArten WHERE Auffnr IN (SELECT AuffNr FROM AufführgTabelle WHERE Snr = @ProductionId)
				DELETE FROM AuffTechAufgabe WHERE Auffnr IN (SELECT AuffNr FROM AufführgTabelle WHERE Snr = @ProductionId)
				DELETE FROM Kosten_Aufführg WHERE Auffnr IN (SELECT AuffNr FROM AufführgTabelle WHERE Snr = @ProductionId)
				DELETE FROM PresseText WHERE Auffnr IN (SELECT AuffNr FROM AufführgTabelle WHERE Snr = @ProductionId)
				DELETE FROM AufführgDetails WHERE Auffnr IN (SELECT AuffNr FROM AufführgTabelle WHERE Snr = @ProductionId)
				DELETE FROM Fahrplan WHERE AuffNr IN (SELECT AuffNr FROM AufführgTabelle WHERE Snr = @ProductionId)
				DELETE FROM CostUnitWorkingTime WHERE ActivityId IN (SELECT AuffNr FROM AufführgTabelle WHERE Snr = @ProductionId)
				DELETE FROM AufführgDetails WHERE AuffNr IN (SELECT AuffNr FROM AufführgTabelle WHERE Snr = @ProductionId)
				DELETE FROM AufR WHERE AuffNr IN (SELECT AuffNr FROM AufführgTabelle WHERE Snr = @ProductionId)
				DELETE FROM AufführgTabelle WHERE AuffNr IN (SELECT AuffNr FROM AufführgTabelle WHERE Snr = @ProductionId)
				UPDATE AufführgTabelle SET ZuAuffNr = NULL WHERE ZuAuffNr IN (SELECT AuffNr FROM AufführgTabelle WHERE Snr = @ProductionId)
			END
		END
END
GO

ALTER PROCEDURE [dbo].[DeleteRole]
	@RoleId INT
AS
BEGIN
SET NOCOUNT ON

DECLARE @UserGroup int
SELECT @UserGroup = Besitzer FROM BesetzungStd WHERE ID=@RoleId

--Berechtigungsprüfung
IF (dbo.GetCurrentPermission(@UserGroup, 4) < 2 ) 
	BEGIN
		SELECT 1 AS Attribut, 'No Permission' AS MSG
	END
ELSE
	BEGIN 
		IF (@RoleId = 0)	
			BEGIN
				SELECT 0 AS Attribut,'Keine gültige Rolle übergeben (Id 0)' AS MSG
			END
		ELSE
			BEGIN
				DELETE FROM BesetzungStdSoliTabelle WHERE RolleID=@RoleId
				DELETE FROM VertragRolle WHERE RolleID=@RoleId
				DELETE FROM BesRepertoire WHERE RolleID=@RoleId
				DELETE FROM RoleBonus WHERE RoleId=@RoleId
				DELETE FROM Role_Season WHERE RoleId=@RoleId
				DELETE FROM Roles_Scenes WHERE RoleId=@RoleId
				DELETE FROM Qualification_Role WHERE RoleId=@RoleId
				DELETE FROM ContractDateConfirmations WHERE ContractDateId IN (SELECT ContractDateId FROM ContractDates WHERE CastId IN (SELECT ID FROM BesetzungTabelle WHERE RolleID=@RoleId))
				DELETE FROM ContractDates WHERE CastId IN (SELECT ID FROM BesetzungTabelle WHERE RolleID=@RoleId)
				DELETE FROM CastBonus WHERE CastId IN (SELECT ID FROM BesetzungTabelle WHERE RolleID=@RoleId)
				DELETE FROM BesetzungTabelle WHERE RolleId=@RoleId
				DELETE FROM AuffTechAufgabe WHERE RolleId=@RoleId
				DELETE FROM BesetzungStd WHERE ID=@RoleId	
			END
		END
END
GO

ALTER PROCEDURE [dbo].[GetRelatedDataOfRole] 
	@RoleId INT
AS
BEGIN
SET NOCOUNT ON

CREATE TABLE #Msg(cnt int, tbl varchar(200))

INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*),'BesetzungStdSoliTabelle' FROM BesetzungStdSoliTabelle WHERE RolleID=@RoleId

	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'VertragRolle' FROM VertragRolle WHERE RolleID=@RoleId	
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'BesRepertoire' FROM BesRepertoire WHERE RolleID=@RoleId
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'ContractDateConfirmations' FROM ContractDateConfirmations WHERE ContractDateId IN (SELECT ContractDateId FROM ContractDates WHERE CastId IN (SELECT ID FROM BesetzungTabelle WHERE RolleID=@RoleId))
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'ContractDates' FROM ContractDates WHERE CastId IN (SELECT ID FROM BesetzungTabelle WHERE RolleID=@RoleId)
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'BesetzungTabelle' FROM BesetzungTabelle WHERE RolleId=@RoleId
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'AuffTechAufgabe' FROM AuffTechAufgabe WHERE RolleId=@RoleId
	
SELECT * FROM #Msg
END
GO

--#endregion

--#region IsInactive in Vertragsarten
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsInactive' and o.id = OBJECT_ID(N'[dbo].[VertragsVorlagen]'))
BEGIN
	ALTER TABLE [dbo].[VertragsVorlagen] ADD  IsInactive BIT NOT NULL CONSTRAINT DF_ContractType_IsInactive DEFAULT 0
END
GO
--#endregion

--#region 20171010 TK FK StückeSpz / Preise
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ProductionSeasons_Prices') AND type = 'F')
BEGIN
	UPDATE StückeSPZ SET PreisNr = NULL  WHERE NOT PreisNr IS NULL AND  NOT EXISTS(SELECT * FROM Preise WHERE StückeSPZ.PreisNr = Preise.PreisNr)
	ALTER TABLE dbo.StückeSPZ ADD CONSTRAINT FK_ProductionSeasons_Prices FOREIGN KEY (PreisNr) REFERENCES dbo.Preise (PreisNr) ON UPDATE  NO ACTION ON DELETE SET NULL
END
GO
--#endregion

--#region 20171010 TK Travels / Person - UserForAccess, Preise
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Travels_Person') AND type = 'F')
BEGIN
	PRINT 'Create...FK_Travels_Person'
	ALTER TABLE Travels ADD CONSTRAINT FK_Travels_Person FOREIGN KEY (PersonId) REFERENCES dbo.Persh (PersNr) 
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Travels_Contracts') AND type = 'F')
BEGIN
	PRINT 'Create...FK_Travels_Contracts'
	ALTER TABLE Travels ADD CONSTRAINT FK_Travels_Contracts FOREIGN KEY (ContractId) REFERENCES dbo.Vertrag (VertragsNr) 
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Travels_Groups') AND type = 'F')
BEGIN
	PRINT 'Create...FK_Travels_Groups'
	ALTER TABLE Travels ADD CONSTRAINT FK_Travels_Groups FOREIGN KEY (OwnerGroupId) REFERENCES dbo.Gruppe (GruppeId) 
	ALTER TABLE TravelSteps ALTER COLUMN [Start] DATE NOT NULL
	ALTER TABLE TravelSteps ALTER COLUMN [End] DATE NULL
	ALTER TABLE TravelSteps ALTER COLUMN [StartTime] SMALLDATETIME NULL
	ALTER TABLE TravelSteps ALTER COLUMN [EndTime] SMALLDATETIME NULL
END
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.UserForAccess') AND o.Name = 'IX_UserForAccess_SeasonId_UserId')
BEGIN
	PRINT 'Create...IX_UserForAccess_SeasonId_UserId'
	DELETE FROM UserForAccess  WHERE  UserID IS NULL OR NOT EXISTS (SELECT * FROM UserPW WHERE UserForAccess.UserID = UserPW.UserID)
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.UserForAccess') AND o.Name = 'SpzNrUserID') DROP INDEX SpzNrUserID ON dbo.UserForAccess
	ALTER TABLE UserForAccess ALTER COLUMN UserID INT NOT NULL
	CREATE UNIQUE INDEX IX_UserForAccess_SeasonId_UserId ON UserForAccess (SpzNr, UserID) ON [PRIMARY]
	ALTER TABLE dbo.UserForAccess ADD CONSTRAINT FK_UserForAccess_Users FOREIGN KEY (UserID) REFERENCES dbo.UserPW	(UserID) ON UPDATE  NO ACTION 	ON DELETE CASCADE	
END
GO

IF EXISTS(SELECT * FROM Preise WHERE PreisNr = 0) 
BEGIN
	UPDATE AufführgTabelle SET PreisNr = NULL WHERE PreisNr = 0
	UPDATE StückeSPZ SET PreisNr = NULL WHERE PreisNr = 0
	DELETE FROM SeatingPlan_PriceCategorys WHERE PriceCategoryId = 0
	DELETE FROM Preise WHERE PreisNr = 0
END
GO

IF EXISTS (SELECT * FROM syscolumns c WHERE c.cdefault > 0 AND c.id = OBJECT_ID('StückeSPZ') AND c.name = 'PreisNr') 
				EXECUTE sp_unbindefault N'dbo.StückeSPZ.PreisNr'

IF EXISTS (SELECT * FROM syscolumns c WHERE c.cdefault > 0 AND c.id = OBJECT_ID('AufführgTabelle') AND c.name = 'PreisNr') 
				EXECUTE sp_unbindefault N'dbo.AufführgTabelle.PreisNr'
GO

exec dropcolumn 'StückeSPZ', 'StückeSPZTS'
GO

exec dropcolumn 'UserForAccess', 'UserForAccessTS'
GO

exec dropcolumn 'UserForAccess', 'User'
GO
--#endregion
--#region 2017-10-19 sh Neue Berechtigung im Bereich Kontakte für Anzeige von verknüpften Kontakten

--#region View [AbPersonalChield_Update] aktualisieren (und auch mit korrigierten Namen)
PRINT 'Creating View AbPersonalChild_Update'
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPersonalChield_Update]'))
BEGIN
	DROP VIEW [dbo].[AbPersonalChield_Update]
END
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPersonalChild_Update]'))
BEGIN
	DROP VIEW [dbo].[AbPersonalChild_Update]
END
GO

CREATE VIEW [dbo].[AbPersonalChild_Update]
AS
	WITH WriteableLinkablePersonIds AS (
		SELECT pp.PersonId 
		FROM PersonModulGroupPermission AS PP
			INNER JOIN UserGruppe AS UG ON pp.ModulGroupId =  UG.GruppeID 
			INNER JOIN UserPW ON Ug.Userid = UserPW.Userid 
		WHERE pp.HasWritePermission=1
		      AND UG.Schreiben=1
		      AND ug.BerechtigungsbereichID = 0
		      AND pp.PermissionType=0
		      AND ug.OptionsFlag&512 = 512 
		      AND Username = CURRENT_USER
		GROUP BY pp.PersonId
	)
	SELECT PersAgentur.* FROM PersAgentur
	WHERE (PersNr IN (SELECT * FROM WriteableLinkablePersonIds) OR ChildPersNr IN (SELECT * FROM WriteableLinkablePersonIds))

	WITH CHECK OPTION
GO

GRANT SELECT, INSERT, UPDATE, DELETE ON [dbo].[AbPersonalChild_Update] TO [public]
GO

--#endregion

--#region neuer View zum Abfragen der Kontaktverknüpfungen (AbPersonalChild)
PRINT 'Creating View AbPersonalChild'
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPersonalChild]'))
BEGIN
	DROP VIEW [dbo].[AbPersonalChild]
END
GO

CREATE VIEW [dbo].[AbPersonalChild]
AS
	WITH LinkablePersonIds AS (
		SELECT pp.PersonId 
		FROM PersonModulGroupPermission AS PP
			INNER JOIN UserGruppe AS UG ON pp.ModulGroupId =  UG.GruppeID 
			INNER JOIN UserPW ON Ug.Userid = UserPW.Userid 
		WHERE ug.BerechtigungsbereichID = 0 AND pp.PermissionType=0 AND ug.OptionsFlag&512 = 512 AND Username = CURRENT_USER GROUP BY pp.PersonId
	)
	SELECT PersAgentur.* FROM PersAgentur
	WHERE PersNr IN (SELECT * FROM LinkablePersonIds) OR ChildPersNr IN (SELECT * FROM LinkablePersonIds)
GO

GRANT SELECT ON [dbo].[AbPersonalChild] TO [public]
GO

--berechtigungen auf tabelle entfernen
REVOKE SELECT, UPDATE, INSERT, DELETE ON [dbo].[PersAgentur] TO [public], [Kontaktdaten ändern], [OrchesterAdmin], [Soli-Daten ändern]
GO

--#endregion

--#region einmaliges setzen der berechtigung zum anzeigen von verknüpften kontakten wegen backwardcompatibility
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 175 OR (Minor=175 AND Build < 3)))))
BEGIN
	PRINT 'Updating permissions setting flag 512 (access contact links) for permission area 0 (contacts)...'
	UPDATE UserGruppe SET OptionsFlag = (OptionsFlag | 512) WHERE BerechtigungsbereichID = 0
END
GO
--#endregion

--#region anpassung an inheritpermission (inhaltlich und namentlich) damit bei kontak jeder auch berechtigung auf links
PRINT 'Updating InheritPermissions'
-- richtige prozedur mit falschen namen entfernen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[InherhitPermissions]'))
BEGIN
	DROP PROCEDURE dbo.[InherhitPermissions] 
END
GO

--veraltete prozedur mit richtigen namen entfernen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[InheritPermissions]'))
BEGIN
	DROP PROCEDURE dbo.[InheritPermissions] 
END
GO

-- =============================================
-- Author:			Torsten Klier
-- Create date:		2010 11 01
-- Modified date:	2011 01 24
--                  2015-03-26 sh temp table beim löschen entfernt, stattdessen usersingroups über temptabelle um alle abfragen zu beschleunigen
--                  2015-07-16 sh temp tabellen durch variablen ersetzt, ist für kleine daten besser
--                                neu anlegen von userpw eintrag hinzugefügt und auswertung bzgl windows gruppen
--                  2017-08-14 sh aufnahme von userfeatures und userfeaturesdefault in das skript, für die featureverwaltung
--                  2017-10-20 sh wenn berechtigung für jeder im bereich kontaktdaten erstellt wird, OptionsFlag auf 512 (links sehen) setzen
-- (Abteilungs-)Gruppenberechtigungen aus Datenbankrollen übernehmen
-- Wenn ein Recht aus mehreren Datenbankrollen geerbt wird, wird das "größte" übernommen 
-- =============================================
CREATE PROCEDURE [dbo].InheritPermissions
AS
BEGIN   
	DECLARE @dbo BIT
	DECLARE @currentUserId INT
	DECLARE @authorizedByGroup BIT
	DECLARE @forAllUsers BIT
	
	SET @currentUserId = 0
	SET @authorizedByGroup = 0
	SET @forAllUsers = 0

	--daten für aktuellen benutzer abfragen, notfalls neu anlegen
	SELECT @currentUserId = UserId, @authorizedByGroup = IsAuthorizedByWindowsGroup FROM UserPw WHERE UserName = CURRENT_USER
	IF @currentUserId = 0 
	BEGIN
		EXEC AddCurrentUser
		SELECT @currentUserId = UserId, @authorizedByGroup = IsAuthorizedByWindowsGroup FROM UserPw WHERE UserName = CURRENT_USER
	END

	SELECT @dbo = IS_MEMBER('db_owner')
	IF @dbo = 0
		BEGIN
			Print 'User' +  cast(@currentUserId as Varchar(10))
		END  
	ELSE
		BEGIN
			SET @forAllUsers = 1
			Print 'All User'
		END

	--2015-03-26 sh
	--UsersInGroups in variable speichern, da im weiteren Verlauf viel damit gearbeitet wird und die abfragen ansonsten sehr langsam sind
	DECLARE @usersInGroups TABLE (GroupId INT, UserId INT)
	INSERT INTO @usersInGroups (GroupId, UserId)
	SELECT ugs.GroupId, ugs.UserId
	FROM UsersInGroups AS ugs

	--2015-07-16 sh
	--wenn über gruppe authorisiert, manuell benutzergruppenzugehörigkeit einfügen
	IF @authorizedByGroup = 1 
	BEGIN
		INSERT INTO @usersInGroups (GroupId, UserId)
		SELECT grp.UserID, @currentUserId
		FROM [sys].[database_principals] dp 
		INNER JOIN UserPw grp ON dp.name = grp.UserName
		WHERE dp.[type] = 'R' AND IS_MEMBER(dp.name) = 1 AND dp.name like '[_]%' 
		AND NOT EXISTS(SELECT * FROM @usersInGroups WHERE GroupId = grp.UserID AND UserId = @currentUserId)
	END

	--abfragedaten für alle benutzer die über windowsgruppen authorisiert wurden und ignoriert werden (aktueller benutzer ausgenommen)
	DECLARE @usersAuthorizedByGroup TABLE (userId INT)
	--füllen nur, wenn für alle benutzer berechtigungen erstellt werden
	IF @forAllUsers = 1
	BEGIN 
	   	INSERT INTO @usersAuthorizedByGroup
		SELECT up.UserID FROM UserPw up WHERE up.IsAuthorizedByWindowsGroup = 1 AND up.UserID <> @currentUserId
    END
	
	--neue Berechtigungen einfügen
	INSERT INTO UserGruppe (GruppeID, UserID, BerechtigungsbereichID, Schreiben, OptionsFlag, IsInherited, LM, UM, LC, UC)
	SELECT  soll.GruppeID, ugs.UserID, soll.BerechtigungsbereichID, CAST(COUNT(soll.Schreiben) AS BIT),
			 MAX(soll.OptionsFlag&1)+MAX(soll.OptionsFlag&2)+MAX(soll.OptionsFlag&4)+MAX(soll.OptionsFlag&8)+MAX(soll.OptionsFlag&16)
			 +MAX(soll.OptionsFlag&32)+MAX(soll.OptionsFlag&64)+MAX(soll.OptionsFlag&128)+MAX(soll.OptionsFlag&256)
			 +MAX(soll.OptionsFlag&512)+MAX(soll.OptionsFlag&1024), 1, MAX(soll.LM), MAX(soll.UM), MAX(soll.LC), MAX(soll.UC)
	FROM	@usersInGroups AS ugs 
		INNER JOIN	UserGruppe AS soll	ON ugs.GroupID = soll.UserID
		LEFT JOIN	UserGruppe AS ist	ON ugs.UserID = ist.UserID AND soll.GruppeID  = ist.GruppeID AND soll.BerechtigungsbereichID = ist.BerechtigungsbereichID
	WHERE  ist.UserGruppeID IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)
	GROUP BY soll.GruppeID, ugs.UserID, soll.BerechtigungsbereichID

	--Berechtigungen entfernen
	DELETE FROM UserGruppe 
	WHERE IsInherited = 1 
		AND (UserGruppe.UserId = @currentUserId OR @forAllUsers = 1)
		AND  UserGruppeID NOT IN 
				(
					SELECT  ist.UserGruppeID
					FROM			@usersInGroups AS ugs 
						INNER JOIN	UserGruppe AS soll		ON ugs.GroupId = soll.UserID
						INNER JOIN	UserGruppe as ist	ON ugs.UserID = ist.UserID AND soll.GruppeID  = ist.GruppeID AND soll.BerechtigungsbereichID = ist.BerechtigungsbereichID
				)
		AND (UserGruppe.UserID NOT IN (SELECT * FROM @usersAuthorizedByGroup))
	
	UPDATE UserGruppe SET UserGruppe.Schreiben = SollSchreiben, UserGruppe.OptionsFlag=SollOp
	FROM 
	(SELECT ugs.UserId, g.GruppeID, BerechtigungsbereichID, MAX(CAST(g.Schreiben AS INT)) AS SollSchreiben,
			 MAX(g.OptionsFlag&1)+MAX(g.OptionsFlag&2)+MAX(g.OptionsFlag&4)+MAX(g.OptionsFlag&8)+MAX(g.OptionsFlag&16)
			 +MAX(g.OptionsFlag&32)+MAX(g.OptionsFlag&64)+MAX(g.OptionsFlag&128)+MAX(g.OptionsFlag&256)
			 +MAX(g.OptionsFlag&512)+MAX(g.OptionsFlag&1024) AS SollOp 
		FROM @usersInGroups AS ugs 
			INNER JOIN UserGruppe AS G ON ugs.GroupId = G.UserID
		GROUP BY ugs.UserId , g.GruppeID, BerechtigungsbereichID) AS soll 
	INNER JOIN UserGruppe  ON 
			soll.UserId = UserGruppe.UserID AND 
			soll.GruppeID = UserGruppe.GruppeID AND 
			soll.BerechtigungsbereichID = UserGruppe.BerechtigungsbereichID
	WHERE
		(SollSchreiben <> UserGruppe.Schreiben OR SollOp <> UserGruppe.OptionsFlag)
		AND UserGruppe.IsInherited = 1
		AND (UserGruppe.UserId = @currentUserId OR @forAllUsers = 1)
		AND (UserGruppe.UserID NOT IN (SELECT * FROM @usersAuthorizedByGroup))	
	
	--Jeden User in Gruppe Kontaktdaten Jeder
	INSERT INTO UserGruppe(GruppeID ,UserID ,Schreiben, LM, UM, LC, UC, BerechtigungsbereichID, OptionsFlag)
	SELECT -1, UserPw.UserID, 0, GETDATE(), 0 ,GETDATE(), 0, 0, 512
	FROM UserPw LEFT JOIN (SELECT * FROM UserGruppe WHERE BerechtigungsbereichID = 0 AND GruppeID = -1) AS UG on UserPW.UserID=UG.UserID WHERE UG.UserGruppeID IS NULL

	DELETE FROM UserGruppe WHERE BerechtigungsbereichID <> 0 AND GruppeID = -1
	
	INSERT INTO UserForAccess (SpzNr,UserID,IsInherited,LM,UM,LC,UC)
	SELECT DISTINCT soll.SpzNr, ugs.UserID, 1, GETDATE(), -1, GETDATE(), -1
	FROM	@usersInGroups AS ugs 
		INNER JOIN	UserForAccess AS soll	ON ugs.Groupid = soll.UserID
		LEFT JOIN	UserForAccess AS ist	ON ugs.UserID = ist.UserID AND soll.SpzNr=ist.SpzNr
	WHERE  ist.UserForAccessID IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)

	DELETE FROM UserForAccess 
	WHERE IsInherited = 1 AND  UserForAccessID NOT IN (
		SELECT      ist.UserForAccessID
		FROM        @usersInGroups          AS ugs
		INNER JOIN	UserForAccess soll      ON ugs.GroupId = soll.UserID
		INNER JOIN	UserForAccess ist       ON ugs.UserId = ist.UserID  AND soll.SpzNr=ist.SpzNr
	) AND (UserId = @currentUserId OR @forAllUsers = 1)
	AND (UserID NOT IN (SELECT * FROM @usersAuthorizedByGroup))

	--UserFeatures
	--Neue UserFeatures einfügen
	INSERT INTO UserFeatures (UserId, FeatureId, IsAvailable, IsInherited, LM, UM, LC, UC)
	SELECT ugs.UserId, soll.FeatureId, MAX(CAST(soll.IsAvailable AS INT)), 1, MAX(soll.LM), MAX(soll.UM), MAX(soll.LC), MAX(soll.UC)
	FROM @usersInGroups AS ugs 
		INNER JOIN UserFeatures AS soll ON ugs.GroupID = soll.UserID
		LEFT JOIN UserFeatures AS ist ON ugs.UserID = ist.UserID AND soll.FeatureId  = ist.FeatureId
	WHERE  ist.UserId IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)
	GROUP BY ugs.UserID, soll.FeatureId

	--Überflüssige UserFeatures entfernen
	DELETE FROM UserFeatures 
	WHERE IsInherited = 1 
		AND (UserFeatures.UserId = @currentUserId OR @forAllUsers = 1)
		AND UserFeatureId NOT IN 
				(
					SELECT  ist.UserFeatureId
					FROM			@usersInGroups AS ugs 
						INNER JOIN	UserFeatures AS soll ON ugs.GroupId = soll.UserID
						INNER JOIN	UserFeatures as ist ON ugs.UserID = ist.UserID AND soll.FeatureId  = ist.FeatureId
				)
		AND (UserFeatures.UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))
	
	--UserFeatures aktualisieren
	UPDATE UserFeatures SET UserFeatures.IsAvailable = SollIsAvailable
	FROM 
	(
		SELECT ugs.UserId, FeatureId, MAX(CAST(uf.IsAvailable AS INT)) AS SollIsAvailable
		FROM @usersInGroups AS ugs 
			INNER JOIN UserFeatures AS uf ON ugs.GroupId = uf.UserId
		GROUP BY ugs.UserId, uf.FeatureId
	) AS soll 
	INNER JOIN UserFeatures  ON 
			soll.UserId = UserFeatures.UserId AND 
			soll.FeatureId = UserFeatures.FeatureId
	WHERE
		SollIsAvailable <> UserFeatures.IsAvailable
		AND UserFeatures.IsInherited = 1
		AND (UserFeatures.UserId = @currentUserId OR @forAllUsers = 1)
		AND (UserFeatures.UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))

	--UserFeatureDefaults
	--Neue UserFeatureDefaults einfügen
	INSERT INTO UserFeatureDefaults (UserId, IsAvailable, IsInherited, LM, UM, LC, UC)
	SELECT ugs.UserId, MAX(CAST(soll.IsAvailable AS INT)), 1, MAX(soll.LM), MAX(soll.UM), MAX(soll.LC), MAX(soll.UC)
	FROM @usersInGroups AS ugs 
		INNER JOIN UserFeatureDefaults AS soll ON ugs.GroupID = soll.UserID
		LEFT JOIN UserFeatureDefaults AS ist ON ugs.UserID = ist.UserID
	WHERE  ist.UserId IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)
	GROUP BY ugs.UserID

	--Überflüssige UserFeatureDefaults entfernen
	DELETE FROM UserFeatureDefaults 
	WHERE IsInherited = 1 
		AND (UserFeatureDefaults.UserId = @currentUserId OR @forAllUsers = 1)
		AND UserFeatureDefaultId NOT IN 
				(
					SELECT  ist.UserFeatureDefaultId
					FROM			@usersInGroups AS ugs 
						INNER JOIN	UserFeatureDefaults AS soll ON ugs.GroupId = soll.UserID
						INNER JOIN	UserFeatureDefaults as ist ON ugs.UserID = ist.UserID
				)
		AND (UserFeatureDefaults.UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))
	
	--UserFeatureDefaults aktualisieren
	UPDATE UserFeatureDefaults SET UserFeatureDefaults.IsAvailable = SollIsAvailable
	FROM 
	(
		SELECT ugs.UserId, MAX(CAST(uf.IsAvailable AS INT)) AS SollIsAvailable
		FROM @usersInGroups AS ugs 
			INNER JOIN UserFeatureDefaults AS uf ON ugs.GroupId = uf.UserId
		GROUP BY ugs.UserId
	) AS soll 
	INNER JOIN UserFeatureDefaults  ON 
			soll.UserId = UserFeatureDefaults.UserId
	WHERE
		SollIsAvailable <> UserFeatureDefaults.IsAvailable
		AND UserFeatureDefaults.IsInherited = 1
		AND (UserFeatureDefaults.UserId = @currentUserId OR @forAllUsers = 1)
		AND (UserFeatureDefaults.UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))
END	
GO
GRANT EXECUTE ON InheritPermissions TO Public
GO
--#endregion

--#endregion 2017-10-19 sh

--#region DH20171024 FK für Drucklayouts
IF EXISTS (SELECT  d.VorlageDpId, v.ID  FROM DienstplanArtenTabelle d LEFT JOIN VorlageDP v ON d.VorlageDpId=v.ID WHERE v.ID IS NULL AND d.VorlageDpId IS NOT NULL)
BEGIN
UPDATE DienstplanArtenTabelle
SET VorlageDpId = NULL
WHERE VorlageDpId NOT IN (SELECT id FROM VorlageDP)
END
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_DienstplanartenTabelle_VorlageDP') AND type = 'F') ALTER TABLE dbo.DienstplanartenTabelle	DROP CONSTRAINT FK_DienstplanartenTabelle_VorlageDP 

GO
ALTER TABLE DienstplanartenTabelle
	ADD CONSTRAINT FK_DienstplanartenTabelle_VorlageDP 
	FOREIGN KEY (VorlageDPID)
	REFERENCES VorlageDP (ID);
GO
--#endregion DH20171024

--#region dh 2017-10-30 Bugfix  WI#12107 gelöschte Tabelle aus Prozedur entfernt
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[DeleteActivityRelations]')) DROP PROCEDURE [dbo].[DeleteActivityRelations] ;
GO
--Löscht keine Abos u. Auff.-Details
--Fehlende Tabelle entfernt.
CREATE PROCEDURE [dbo].[DeleteActivityRelations]
	@ActivityId INT
AS
BEGIN
SET NOCOUNT ON
	IF NOT EXISTS (SELECT * FROM ActivitiesUpdate WHERE AuffNr= @ActivityId)
		BEGIN
				SELECT 1 AS Attribut, 'No Permission' AS MSG
			END
		ELSE
	BEGIN
			
		DELETE FROM CastCredits WHERE ServiceCastId IN (SELECT Id FROM BesetzungTabelle WHERE Auffnr = @activityId)
		DELETE FROM CastCredits WHERE ReplacementCastId IN (SELECT Id FROM BesetzungTabelle WHERE Auffnr = @activityId)
		DELETE FROM CastBonus WHERE CastBonus.CastId IN (SELECT Id FROM BesetzungTabelle WHERE Auffnr = @activityId)
		DELETE FROM CashCommandPos_Cast WHERE CastId IN (SELECT Id FROM BesetzungTabelle WHERE Auffnr = @activityId)
		UPDATE ContractDates SET  CastId = NULL WHERE CastId IN (SELECT Id FROM BesetzungTabelle WHERE Auffnr = @activityId)
		DELETE FROM BesetzungTabelle WHERE Auffnr = @activityId
		DELETE FROM ActivityScenes WHERE ActivityId = @activityId
		DELETE FROM AuffDienstplanArten WHERE Auffnr = @activityId
		DELETE FROM AuffTechAufgabe WHERE Auffnr = @activityId
		DELETE FROM Kosten_Aufführg WHERE Auffnr = @activityId
		DELETE FROM PresseText WHERE Auffnr = @activityId
		DELETE FROM AufführgDetails WHERE Auffnr = @activityId
		DELETE FROM Fahrplan WHERE AuffNr = @ActivityId
		DELETE FROM CostUnitWorkingTime WHERE ActivityId = @activityId
		DELETE FROM ActivityScenes WHERE ActivityId = @activityId
		UPDATE AufführgTabelle SET ZuAuffNr = NULL WHERE ZuAuffNr = @ActivityId
	END	
END	
GO
GRANT EXECUTE ON [dbo].[DeleteActivityRelations] TO PUBLIC
GO
--#endregion dh 2017-10-30 Bugfix

--#region 2017-11-01 sh farben bei produktionen umschreiben aus details in die xml settings
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 175 OR (Minor=175 AND Build < 5)))))
BEGIN
	PRINT 'Moving and converting colors from production details to production...'
	;WITH colors AS (
		SELECT
			s.SNr,

			CASE WHEN s.FormatSettings IS NULL THEN 0 ELSE 1 END AS HasXML,
	
			CASE WHEN sd.DispoColorVst<=0 OR sd.DispoColorVst IS NULL THEN 0 ELSE 1 END AS HasPerformanceBackColor,
			CASE WHEN sd.DispoColorVst<=0 OR sd.DispoColorVst IS NULL THEN NULL ELSE CAST((isnull(sd.DispoColorVst,0) & 0xff)AS VARCHAR(3)) END as PerformanceBackColorR,
			CASE WHEN sd.DispoColorVst<=0 OR sd.DispoColorVst IS NULL THEN NULL ELSE CAST(((isnull(sd.DispoColorVst,0) & 0xff00) / 0x100)AS VARCHAR(3)) END as PerformanceBackColorG,
			CASE WHEN sd.DispoColorVst<=0 OR sd.DispoColorVst IS NULL THEN NULL ELSE CAST(((isnull(sd.DispoColorVst,0) & 0xff0000) / 0x10000)AS VARCHAR(3)) END as PerformanceBackColorB,

			CASE WHEN sd.DispoColorVst>=0 OR sd.DispoColorVst IS NULL THEN 0 ELSE 1 END AS HasPerformanceForeColor,
			CASE WHEN sd.DispoColorVst>=0 OR sd.DispoColorVst IS NULL THEN NULL ELSE CAST(((isnull(sd.DispoColorVst,0) * -1) & 0xff)AS VARCHAR(3)) END as PerformanceForeColorR,
			CASE WHEN sd.DispoColorVst>=0 OR sd.DispoColorVst IS NULL THEN NULL ELSE CAST((((isnull(sd.DispoColorVst,0) * -1) & 0xff00) / 0x100)AS VARCHAR(3)) END as PerformanceForeColorG,
			CASE WHEN sd.DispoColorVst>=0 OR sd.DispoColorVst IS NULL THEN NULL ELSE CAST((((isnull(sd.DispoColorVst,0) * -1) & 0xff0000) / 0x10000)AS VARCHAR(3)) END as PerformanceForeColorB,
	
	
			CASE WHEN sd.DispoColorPro<=0 OR sd.DispoColorPro IS NULL THEN 0 ELSE 1 END AS HasRehearsalBackColor,
			CASE WHEN sd.DispoColorPro<=0 OR sd.DispoColorPro IS NULL THEN NULL ELSE CAST((isnull(sd.DispoColorPro,0) & 0xff)AS VARCHAR(3)) END as RehearsalBackColorR,
			CASE WHEN sd.DispoColorPro<=0 OR sd.DispoColorPro IS NULL THEN NULL ELSE CAST(((isnull(sd.DispoColorPro,0) & 0xff00) / 0x100)AS VARCHAR(3)) END as RehearsalBackColorG,
			CASE WHEN sd.DispoColorPro<=0 OR sd.DispoColorPro IS NULL THEN NULL ELSE CAST(((isnull(sd.DispoColorPro,0) & 0xff0000) / 0x10000)AS VARCHAR(3)) END as RehearsalBackColorB,

			CASE WHEN sd.DispoColorPro>=0 OR sd.DispoColorPro IS NULL THEN 0 ELSE 1 END AS HasRehearsalForeColor,
			CASE WHEN sd.DispoColorPro>=0 OR sd.DispoColorPro IS NULL THEN NULL ELSE CAST(((isnull(sd.DispoColorPro,0) * -1) & 0xff)AS VARCHAR(3)) END as RehearsalForeColorR,
			CASE WHEN sd.DispoColorPro>=0 OR sd.DispoColorPro IS NULL THEN NULL ELSE CAST((((isnull(sd.DispoColorPro,0) * -1) & 0xff00) / 0x100)AS VARCHAR(3)) END as RehearsalForeColorG,
			CASE WHEN sd.DispoColorPro>=0 OR sd.DispoColorPro IS NULL THEN NULL ELSE CAST((((isnull(sd.DispoColorPro,0) * -1) & 0xff0000) / 0x10000)AS VARCHAR(3)) END as RehearsalForeColorB
		FROM Stücke s
		LEFT JOIN StückeDetails sd ON s.SNr = sd.Snr
	)

	UPDATE Stücke SET FormatSettings = updateData.FormatSettings
	FROM (
		SELECT
			colors.SNr,

			'<?xml version="1.0" encoding="utf-16"?><ProductionFormatSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'
			+ CASE WHEN colors.HasPerformanceForeColor = 0
				THEN '<SerializablePerformanceForeColor><A>0</A><R>0</R><G>0</G><B>0</B></SerializablePerformanceForeColor>'
				ELSE '<SerializablePerformanceForeColor><A>255</A><R>'+colors.PerformanceForeColorR+'</R><G>'+colors.PerformanceForeColorG+'</G><B>'+colors.PerformanceForeColorB+'</B></SerializablePerformanceForeColor>'
			 END
			+ CASE WHEN colors.HasPerformanceBackColor = 0
				THEN '<SerializablePerformanceBackColor><A>0</A><R>0</R><G>0</G><B>0</B></SerializablePerformanceBackColor>'
				ELSE '<SerializablePerformanceBackColor><A>255</A><R>'+colors.PerformanceBackColorR+'</R><G>'+colors.PerformanceBackColorG+'</G><B>'+colors.PerformanceBackColorB+'</B></SerializablePerformanceBackColor>'
			 END
			+ CASE WHEN colors.HasRehearsalForeColor = 0
				THEN '<SerializableRehearsalForeColor><A>0</A><R>0</R><G>0</G><B>0</B></SerializableRehearsalForeColor>'
				ELSE '<SerializableRehearsalForeColor><A>255</A><R>'+colors.RehearsalForeColorR+'</R><G>'+colors.RehearsalForeColorG+'</G><B>'+colors.RehearsalForeColorB+'</B></SerializableRehearsalForeColor>'
			 END
			+ CASE WHEN colors.HasRehearsalBackColor = 0
				THEN '<SerializableRehearsalBackColor><A>0</A><R>0</R><G>0</G><B>0</B></SerializableRehearsalBackColor>'
				ELSE '<SerializableRehearsalBackColor><A>255</A><R>'+colors.RehearsalBackColorR+'</R><G>'+colors.RehearsalBackColorG+'</G><B>'+colors.RehearsalBackColorB+'</B></SerializableRehearsalBackColor>'
			 END
			+'</ProductionFormatSettings>' AS FormatSettings

		FROM colors

		WHERE
			colors.HasXML = 0
			AND NOT (
				colors.HasPerformanceBackColor = 0
				AND colors.HasPerformanceForeColor = 0
				AND colors.HasRehearsalBackColor = 0
				AND colors.HasRehearsalForeColor = 0
			)
		) AS updateData
	WHERE Stücke.SNr = updateData.SNr
END
GO
--#endregion Bugfix

--#region dh 2017-11-02 Lange Bemerkung für Countdowns
IF NOT Exists (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'NoteLong' and o.id = OBJECT_ID(N'[dbo].[Countdown]'))
BEGIN
	ALTER TABLE Countdown ADD NoteLong VARCHAR(MAX) SPARSE NULL ;
	print('Column NoteLong for Countdown added!'); 
	ALTER TABLE Countdown ALTER COLUMN Bemerkung Varchar(256) Sparse NULL;
	ALTER TABLE Countdown ALTER COLUMN BemerkungTechnik Varchar(256) Sparse NULL;
END
--#endregion

--#region dh 2017-11-02 Von und Biszeit drucken für Countdowns
IF NOT Exists (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PrintStartTime' and o.id = OBJECT_ID(N'[dbo].[Countdown]'))
BEGIN
	ALTER TABLE Countdown ADD PrintStartTime BIT SPARSE NULL ;
	ALTER TABLE Countdown ADD PrintEndTime BIT SPARSE NULL ;
	print('Columns PrintStartTime,PrintEndTime for Countdown added!'); 
END
GO
--#endregion

--#endregion (4.175.x)

--#region ----------- 4.175.x Release Übertrag ----------------

--#region Doppelte Jahresabschlüße entfernen


DELETE FROM Jahresabschluss WHERE ID IN (
	SELECT ID FROM (
		SELECT
		ROW_NUMBER() OVER(PARTITION BY DienstplanArtenID, YearCloseTypeId, VonJahrMonat ORDER BY abgeschlossen DESC) as r,
		Jahresabschluss.ID
		FROM Jahresabschluss) AS sub WHERE r>1)

DELETE FROM Jahresabschluss WHERE ID IN (
	SELECT ID FROM (
		SELECT
		ROW_NUMBER() OVER(PARTITION BY DienstplanArtenID, YearCloseTypeId, BisJahrMonat ORDER BY abgeschlossen DESC) as r,
		Jahresabschluss.ID
		FROM Jahresabschluss) AS sub WHERE r>1)

IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME='IX_YearPeriods_Department_CloseType_Start') 
	CREATE UNIQUE INDEX IX_YearPeriods_Department_CloseType_Start ON dbo.Jahresabschluss (DienstplanArtenID, YearCloseTypeId, VonJahrMonat)
IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME='IX_YearPeriods_Department_CloseType_End') 
	CREATE UNIQUE INDEX IX_YearPeriods_Department_CloseType_End ON dbo.Jahresabschluss (DienstplanArtenID, YearCloseTypeId, BisJahrMonat)
GO
--20180117 falsch bennant-> löschen
IF EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME='IX_YearPeriods_DepartmentCloseTypeStart') 
	DROP INDEX dbo.Jahresabschluss.IX_YearPeriods_DepartmentCloseTypeStart 
IF EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME='IX_YearPeriods_DepartmentCloseTypeEnd') 
	DROP INDEX dbo.Jahresabschluss.IX_YearPeriods_DepartmentCloseTypeEnd 
GO


--#endregion

--#region Berechtigungen setzen für TimeAccountsTarifsSettings
	GRANT DELETE, INSERT, UPDATE ON TimeAccountsTarifsSettings TO PersoAdmin

--#endregion

--#region sh 2018-01-10 GetCastAsDbo korrigieren
PRINT('Updating GetCastAsDbo...')
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetCastAsDbo'))
	DROP PROCEDURE dbo.GetCastAsDbo
GO
CREATE PROCEDURE GetCastAsDbo 
	@include INT = NULL
AS
BEGIN
	SELECT * FROM BesetzungTabelle

	IF (@include IS NULL OR @include = 0)
		RETURN

	IF (@include&1 = 1) -- Zulagen der Besetzungen
		SELECT NULL AS [#1], cb.* 
		FROM CastBonus AS cb
		INNER JOIN BesetzungTabelle ON cb.CastId = BesetzungTabelle.ID
	IF (@include&2 = 2) -- Vertragstermine der Besetzungen
		SELECT NULL AS [#2], cd.*, rdc.ContractDateId AS ReplacedContractDateId 
		FROM ContractDates AS cd 
		LEFT JOIN ContractDates AS rdc ON cd.ContractDateId = rdc.ReplacementContractDateId
		INNER JOIN BesetzungTabelle ON cd.CastId = BesetzungTabelle.ID
	IF (@include&4 = 4) -- Aktivitäten der Besetzungen
		SELECT NULL AS [#4], a.*
		FROM AufführgTabelle AS a 
		WHERE EXISTS (SELECT * FROM BesetzungTabelle AS c WHERE c.AuffNr = a.AuffNr)
	IF (@include&8 = 8) -- Verträge der Besetzungen
		SELECT NULL AS [#8], v.*
		FROM Vertrag AS v
		WHERE EXISTS (SELECT * FROM BesetzungTabelle AS c WHERE c.ContractId = v.VertragsNr)
	IF (@include&16 = 16) -- Rollen der Besetzungen
		SELECT NULL AS [#16], r.*
		FROM BesetzungStd AS r 
		WHERE EXISTS (SELECT * FROM BesetzungTabelle AS c WHERE c.RolleID = r.ID)
	IF (@include&32 = 32) -- Personen der Besetzungen
		SELECT NULL AS [#32], p.*
		FROM PersH AS p 
		WHERE EXISTS (SELECT * FROM BesetzungTabelle AS c WHERE c.PersNr = p.PersNr)
	IF (@include&96 = 96) -- Alle Verträge der besetzen Personen (PreLoading von Person.Contracts)
		SELECT NULL AS [#96], v.*
		FROM Vertrag AS v
		WHERE EXISTS (SELECT * FROM BesetzungTabelle AS c WHERE c.PersNr = v.PersNr)
	IF (@include&224 = 224) -- Alle Rollenverträge (auch Spielzeithonorare etc.) der besetzten Personen (PreLoading von Contract.ContractRolle)
		SELECT NULL AS [#224], vr.*
		FROM VertragRolle AS vr
		INNER JOIN Vertrag AS v ON vr.VertragsNr = v.VertragsNr
		WHERE EXISTS (SELECT * FROM BesetzungTabelle AS c WHERE c.PersNr = v.PersNr)
END
GO
--#endregion

--#region sh 2018-01-10 GetCastWithContractPermission korrigieren
PRINT('Updating GetCastWithContractPermission...')
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetCastWithContractPermission'))
	DROP PROCEDURE dbo.GetCastWithContractPermission
GO
CREATE PROCEDURE GetCastWithContractPermission 
	@startDate DATE = NULL, 
	@endDate DATE = NULL,
	@persNrList VARCHAR(MAX) = NULL,
	@groupIdList VARCHAR(50) = NULL,
	@include INT = NULL
AS
BEGIN
	SELECT c.* INTO #cast FROM BesetzungTabelle AS c
	INNER JOIN BesetzungStd	AS r ON c.RolleId = r.ID
	INNER JOIN AufführgTabelle AS a ON c.AuffNr = a.AuffNr
	INNER JOIN UserGruppe AS Ug ON r.Besitzer IN (ISNULL(@groupIdList, r.Besitzer))   
	INNER JOIN UserPW ON Ug.Userid  = UserPW.Userid 
	WHERE ug.BerechtigungsbereichID = 1 /*Es soll der Berechtigungsbereich 1 (Vertragsdaten) verwendet werden*/
	AND ug.Schreiben = 1
	AND UserPW.Username = CURRENT_USER
	AND c.PersNr IN (ISNULL(@persNrList, c.PersNr))
	AND a.Datum >= ISNULL(@startDate, a.Datum)
	AND a.Datum <= ISNULL(@endDate, a.Datum)

	SELECT * FROM #Cast

	IF (@include IS NULL OR @include = 0)
		RETURN

	IF (@include&1 = 1) -- Zulagen der Besetzungen
		SELECT NULL AS [#1], cb.* 
		FROM CastBonus AS cb
		INNER JOIN #Cast ON cb.CastId = #Cast.ID
	IF (@include&2 = 2) -- Vertragstermine der Besetzungen
		SELECT NULL AS [#2], cd.*, rdc.ContractDateId AS ReplacedContractDateId 
		FROM ContractDates AS cd 
		LEFT JOIN ContractDates AS rdc ON cd.ContractDateId = rdc.ReplacementContractDateId
		INNER JOIN #Cast ON cd.CastId = #Cast.ID
	IF (@include&4 = 4) -- Aktivitäten der Besetzungen
		SELECT NULL AS [#4], a.*
		FROM AufführgTabelle AS a 
		WHERE EXISTS (SELECT * FROM #Cast AS c WHERE c.AuffNr = a.AuffNr)
	IF (@include&8 = 8) -- Verträge der Besetzungen
		SELECT NULL AS [#8], v.*
		FROM Vertrag AS v
		WHERE EXISTS (SELECT * FROM #Cast AS c WHERE c.ContractId = v.VertragsNr)
	IF (@include&16 = 16) -- Rollen der Besetzungen
		SELECT NULL AS [#16], r.*
		FROM BesetzungStd AS r 
		WHERE EXISTS (SELECT * FROM #Cast AS c WHERE c.RolleID = r.ID)
	IF (@include&32 = 32)  -- Personen der Besetzungen
		SELECT NULL AS [#32], p.*
		FROM PersH AS p 
		WHERE EXISTS (SELECT * FROM #Cast AS c WHERE c.PersNr = p.PersNr)
	IF (@include&96 = 96) -- Alle Verträge der besetzen Personen (PreLoading von Person.Contracts)
		SELECT NULL AS [#96], v.*
		FROM Vertrag AS v
		WHERE EXISTS (SELECT * FROM #Cast AS c WHERE c.PersNr = v.PersNr)
	IF (@include&224 = 224)  -- Alle Rollenverträge (auch Spielzeithonorare etc.) der besetzten Personen (PreLoading von Contract.ContractRolle)
		SELECT NULL AS [#224], vr.*
		FROM VertragRolle AS vr
		INNER JOIN Vertrag AS v ON vr.VertragsNr = v.VertragsNr
		WHERE EXISTS (SELECT * FROM #Cast AS c WHERE c.PersNr = v.PersNr)
END
GO

GRANT EXECUTE ON dbo.GetCastWithContractPermission TO PUBLIC
GO
--#endregion

--#region tk 20180123 Besetzungen

IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetCastByActivityIdInternal')) DROP PROCEDURE dbo.GetCastByActivityIdInternal
GO
CREATE PROCEDURE dbo.GetCastByActivityIdInternal
	@ActivityId VARCHAR(MAX),
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@userId INT,
	@ShowCastWithoutRights BIT 
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SQLQuery AS NVARCHAR(MAX)

	if (@include <> 0)  CREATE TABLE #Cast (CastId INT NOT NULL, NoPermission BIT NOT NULL)

	CREATE TABLE #Permissions (UserGruppeId INT NOT NULL, BerechtigungsbereichId INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #Permissions SELECT UserGruppe.GruppeId, UserGruppe.BerechtigungsbereichID, OptionsFlag  FROM UserGruppe WHERE UserId = @userId AND BerechtigungsbereichId IN (1,4)


	DECLARE @fields VARCHAR(MAX) --<
	DECLARE @secretfields VARCHAR(MAX)
	SET @fields = ', B.Id, B.RolleId, B.AuffNr, B.DiffVon, B.DiffBis, B.BesBem, B.Druck, B.LM, B.UM, B.LC, B.UC, B.Gesperrt, B.BesSort, 
					B.AgencyId, B.IsCover, B.IsCanceled, B.Creditable, B.BackColorArgb, B.IsReplacement'

	--Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben
	if (@include <> 0) 
		BEGIN
			SET @secretfields =		'CASE WHEN NoPermission = 1 THEN -1 ELSE B.PersNr END AS PersNr,
									 CASE WHEN NoPermission = 1 THEN -1 ELSE B.ContractId END AS ContractId,
									 CASE WHEN NoPermission = 1 THEN  0 ELSE B.CastStatusId END AS CastStatusId '

			SET @SQLQuery = 'INSERT INTO #Cast SELECT b.Id, CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN 1 ELSE 0 END '
		END	
	ELSE
		BEGIN
			SET @secretfields  =	'CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN -1 ELSE B.PersNr END AS PersNr,
									 CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN -1 ELSE B.ContractId END AS ContractId,
									 CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN  0 ELSE B.CastStatusId END AS CastStatusId '
			
			SET @SQLQuery = 'SELECT ' + @secretfields + @fields
		END

		SET @SQLQuery =  @SQLQuery + '	FROM BesetzungTabelle AS B
										INNER JOIN BesetzungStd	AS ro ON b.RolleID = ro.ID
										INNER JOIN #Permissions AS ugC ON ugC.UserGruppeId = ro.Besitzer AND ugC.BerechtigungsbereichId = 4'

		IF (@joins&1 = 1) 
			SET @SQLQuery = @SQLQuery + 'INNER JOIN (SELECT * FROM ContractDates WHERE IsCanceled = 0) AS cd ON b.ID = cd.CastID '

		SET @SQLQuery = @SQLQuery + ' WHERE b.Auffnr IN (' + @ActivityId + ')'

		IF (@ShowCastWithoutRights = 0) 
		BEGIN
			SET @SQLQuery = @SQLQuery  + ' AND (b.Gesperrt = 0 OR ugc.OptionsFlag&1 = 1)'
		END

		 IF (@condition IS NOT NULL  AND @condition <> '')
			 SET @SQLQuery = @SQLQuery + ' AND ' + @condition 

		EXECUTE sp_Executesql @SQLQuery 

	IF (@include <> 0) --Wenn keine weiteren Daten mitgeladen werden wurde das Ergebnis bereits zurückgeben
		BEGIN
			SET @SQLQuery = 'SELECT ' + @secretfields + @fields +' FROM BesetzungTabelle AS b 
														INNER JOIN  #Cast ON b.id = #cast.CastId'

			EXECUTE sp_Executesql  @SQLQuery
		END

	IF (@include&1 = 1) 
		SELECT NULL AS [#1], CastBonus.* 
		FROM CastBonus 
			INNER JOIN #Cast ON CastBonus.CastId = #Cast.CastId
	
	IF (@include&2 = 2) 
	BEGIN
			-- contractdates mit berechtigung laden
		CREATE TABLE #ContractDates (ContractDateId INT NOT NULL, ReplacementContractDateId INT NULL)

		INSERT INTO #ContractDates (ContractDateId, ReplacementContractDateId)
			SELECT cd.ContractDateId, cd.ReplacementContractDateId FROM ContractDates cd
				INNER JOIN VertragRolle vr ON cd.ContractRoleId = vr.VRID
				INNER JOIN Vertrag v ON vr.VertragsNr = v.VertragsNr
				INNER JOIN #Permissions p ON p.BerechtigungsbereichId = 1 AND p.UserGruppeId = v.ModulGruppeID

		--abfrage über tabelle mit join auf die ids mit berechtigungen
		SELECT NULL AS [#2], cd.*, rcd_temp.ContractDateId AS ReplacedContractDateId 
			FROM ContractDates AS cd
				INNER JOIN #ContractDates cd_temp ON cd.ContractDateId = cd_temp.ContractDateId
				LEFT JOIN  #ContractDates rcd_temp ON cd.ContractDateId = rcd_temp.ReplacementContractDateId
				INNER JOIN #Cast ON cd.CastId = #Cast.CastId
				WHERE #Cast.NoPermission = 0
	END
END
GO

IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetCastByActivityId')) DROP PROCEDURE dbo.GetCastByActivityId
GO
CREATE PROCEDURE dbo.GetCastByActivityId
	@ActivityId VARCHAR(MAX),
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowCastWithoutRights BIT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @userId INT
	SELECT @userId = UserId FROM UserPW WHERE UserName  = CURRENT_USER
	EXECUTE GetCastByActivityIdInternal @ActivityId, @condition, @joins, @include, @userId, @ShowCastWithoutRights
END
GO
GRANT EXECUTE ON dbo.GetCastByActivityId TO PUBLIC
GO

IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetCastByPeriodInternal')) DROP PROCEDURE dbo.GetCastByPeriodInternal
GO
CREATE PROCEDURE dbo.GetCastByPeriodInternal
	@start DATETIME,
	@end DATETIME,
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@userId INT,
	@ShowCastWithoutRights BIT 
	WITH EXECUTE AS 'dbo'
AS
BEGIN

	SET NOCOUNT ON;
	DECLARE @SQLQuery AS NVARCHAR(MAX)
	DECLARE @permissionPeriodStart DATETIME
	DECLARE @permissionPeriodEnd DATETIME

	SELECT @permissionPeriodStart = MIN(s.SpzStart), @permissionPeriodEnd = MAX(s.SpzEnde)
	FROM Spielzeittabelle AS s
		INNER JOIN UserForAccess AS us	ON s.spznr = us.spznr
	WHERE us.UserId = @userId AND s.SpzNr <> 0

	if (@permissionPeriodStart IS NULL)
		BEGIN 
			SELECT @start = '30000101'
			SELECT @end = '30000101'
		END
	ELSE
		BEGIN
			IF (@start < @permissionPeriodStart)	BEGIN SELECT @start = @permissionPeriodStart END
			IF (@end > @permissionPeriodEnd)		BEGIN SELECT @end = @permissionPeriodEnd END
		END

	if (@include <> 0)  CREATE TABLE #Cast (CastId INT NOT NULL, NoPermission BIT NOT NULL)

	CREATE TABLE #Permissions (UserGruppeId INT NOT NULL, BerechtigungsbereichId INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #Permissions	SELECT UserGruppe.GruppeId, UserGruppe.BerechtigungsbereichID, OptionsFlag
								FROM UserGruppe
								WHERE UserId = @userId AND BerechtigungsbereichId IN (1, 2, 4)

	DECLARE @fields VARCHAR(MAX)
	DECLARE @secretfields VARCHAR(MAX)
	SET @fields  = ', B.Id, B.RolleId, B.AuffNr, B.DiffVon, B.DiffBis, B.BesBem, B.Druck, B.LM, B.UM, B.LC, B.UC, B.Gesperrt, B.BesSort,
					B.AgencyId, B.IsCover, B.IsCanceled, B.Creditable, B.BackColorArgb, B.IsReplacement '

	--Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben
	if (@include <> 0) 
		BEGIN

			SET @secretfields =		'CASE WHEN NoPermission = 1 THEN -1 ELSE B.PersNr END AS PersNr,
									 CASE WHEN NoPermission = 1 THEN -1 ELSE B.ContractId END AS ContractId,
									 CASE WHEN NoPermission = 1 THEN  0 ELSE B.CastStatusId END AS CastStatusId '

			SET @SQLQuery = ' INSERT INTO #Cast SELECT b.Id, CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN 1 ELSE 0 END '
		END	
	ELSE
		BEGIN
			SET @secretfields =	'CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN -1 ELSE B.PersNr END AS PersNr,
								 CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN -1 ELSE B.ContractId END AS ContractId,
								 CASE WHEN B.Gesperrt = 1 AND ugC.OptionsFlag&1 <> 1 THEN  0 ELSE B.CastStatusId END AS CastStatusId '
			SET @SQLQuery = 'SELECT ' + @secretfields + @fields
		END	

	SET @SQLQuery = @SQLQuery + 
	'FROM  BesetzungTabelle			AS B
		INNER JOIN BesetzungStd		AS ro	ON b.RolleID = ro.ID
		INNER JOIN AufführgTabelle	AS A	ON B.AuffNr = A.Auffnr
		INNER JOIN Stücke			AS p	ON A.snr = p.snr
		INNER JOIN #Permissions		AS ugA	ON ugA.UserGruppeId = P.ModuleGroupId AND ugA.BerechtigungsbereichID = 2
		INNER JOIN #Permissions		AS ugC	ON ugC.UserGruppeId = ro.Besitzer AND ugC.BerechtigungsbereichID = 4'

		IF (@joins&1 = 1) 
			SET @SQLQuery = @SQLQuery + 'INNER JOIN (SELECT * FROM ContractDates WHERE IsCanceled = 0) AS cd ON b.ID = cd.CastID '	

		IF (@joins&4 = 4) 
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN StückeDetails ON A.Snr = StückeDetails.Snr '

		IF (@joins&8 = 8) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN AuffTypen AS AT ON A.art = AT.AufftNr '
			
		SET @SQLQuery = @SQLQuery + ' WHERE A.Datum BETWEEN ''' + CAST(@start AS VARCHAR(MAX)) + '''  AND ''' + CAST(@end AS VARCHAR(MAX)) + ''''
		 
		--Wenn in allen Besitzergruppe gesperrte Aktivitäten gelesen werden können ist keine Prüfung auf gesperrt erforderlich
		IF (EXISTS(SELECT * FROM #Permissions WHERE BerechtigungsbereichId = 2 AND OptionsFlag&1 <> 1)) 
		BEGIN
			SET @SQLQuery = @SQLQuery  + ' AND (a.Gesperrt = 0 OR uga.OptionsFlag&1 = 1)'
		END

		IF (@ShowCastWithoutRights = 0) 
		BEGIN
			SET @SQLQuery = @SQLQuery  + ' AND (b.Gesperrt = 0 OR ugc.OptionsFlag&1 = 1)'
		END

		IF (@condition IS NOT NULL)
			 SET @SQLQuery = @SQLQuery + ' AND ' + @condition 

		EXECUTE sp_Executesql @SQLQuery 

	IF (@include <> 0) --Wenn keine weiteren Daten mitgeladen werden wurde das Ergebnis bereits zurückgeben
		BEGIN
			SET @SQLQuery = 'SELECT ' + @secretfields + @fields +' FROM BesetzungTabelle AS b 
														INNER JOIN  #Cast ON b.id = #cast.CastId'
			print @SQLQuery
			EXECUTE sp_Executesql  @SQLQuery
		END
		
	IF (@include&1 = 1) 
		SELECT NULL AS [#1], CastBonus.* 
		FROM CastBonus 
			INNER JOIN #Cast ON CastBonus.CastId = #Cast.CastId

	IF (@include&2 = 2)
	BEGIN
			-- contractdates mit berechtigung laden
		CREATE TABLE #ContractDates (ContractDateId INT NOT NULL, ReplacementContractDateId INT NULL)

		INSERT INTO #ContractDates (ContractDateId, ReplacementContractDateId)
		SELECT cd.ContractDateId, cd.ReplacementContractDateId FROM ContractDates cd
		INNER JOIN VertragRolle vr ON cd.ContractRoleId = vr.VRID
		INNER JOIN Vertrag v ON vr.VertragsNr = v.VertragsNr
		INNER JOIN #Permissions p ON p.BerechtigungsbereichId = 1 AND p.UserGruppeId = v.ModulGruppeID

		--abfrage über tabelle mit join auf die ids mit berechtigungen
		SELECT NULL AS [#2], cd.*, rcd_temp.ContractDateId AS ReplacedContractDateId 
		FROM ContractDates AS cd
		INNER JOIN #ContractDates cd_temp ON cd.ContractDateId = cd_temp.ContractDateId
		LEFT JOIN #ContractDates rcd_temp ON cd.ContractDateId = rcd_temp.ReplacementContractDateId
		INNER JOIN #Cast ON cd.CastId = #Cast.CastId
		WHERE #Cast.NoPermission = 0
	END
END
GO

IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetCastByPeriod')) DROP PROCEDURE dbo.GetCastByPeriod
GO
CREATE PROCEDURE dbo.GetCastByPeriod
	@start DATETIME,
	@end DATETIME,
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowCastWithoutRights BIT 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @userId INT
	SELECT @userId = UserId FROM UserPW WHERE UserName  = CURRENT_USER
	EXECUTE GetCastByPeriodInternal @start, @end, @condition, @joins, @include, @userId, @ShowCastWithoutRights

END
GO
GRANT EXECUTE ON dbo.GetCastByPeriod TO PUBLIC

GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetCastByPeriod2')) DROP PROCEDURE dbo.GetCastByPeriod2
GO
CREATE PROCEDURE dbo.GetCastByPeriod2
	@start DATETIME,
	@end DATETIME,
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowCastWithoutRights BIT 
AS
BEGIN
	SET NOCOUNT ON;
	EXECUTE GetCastByPeriod @start, @end, @condition, @joins, @include, @ShowCastWithoutRights

END
GO
GRANT EXECUTE ON dbo.GetCastByPeriod2 TO PUBLIC
GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetCastByActivityId2')) DROP PROCEDURE dbo.GetCastByActivityId2
GO
CREATE PROCEDURE dbo.GetCastByActivityId2
	@ActivityId VARCHAR(MAX),
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowCastWithoutRights BIT
AS
BEGIN
	SET NOCOUNT ON;
	EXECUTE GetCastByActivityId @ActivityId, @condition, @joins, @include,  @ShowCastWithoutRights
END
GO
GRANT EXECUTE ON dbo.GetCastByActivityId2 TO PUBLIC
GO


--#endregion

--#endregion

--#region ----------- 4.176.x ---------------------------------

--#region DH 20171113 WI#12152 Ausgaberegel für Rapportspalten
IF NOT EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ColumnSettings' and o.id = OBJECT_ID(N'[dbo].[RapportSpalte]'))
BEGIN
	ALTER TABLE RapportSpalte ADD ColumnSettings XML SPARSE NULL 
END
GO
--#endregion

--#region DH 20171114 Countdownstartzeitpunkte
IF NOT EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'StartPoint' and o.id = OBJECT_ID(N'[dbo].[Countdown]'))
BEGIN
	ALTER TABLE Countdown ADD StartPoint TINYINT NOT NULL CONSTRAINT df_countdown_StartPoint DEFAULT 0 ;
EXEC	('UPDATE Countdown
		SET 
		StartPoint=3
		WHERE OffsetMinutes>0;')
EXEC    ('UPDATE CountDown
		SET OffsetMinutes=-OffsetMinutes
		WHERE StartPoint=0;')
END
GO
--#endregion

--#region DH 20171117 Flag Werke Zuweisen

-- ProductionsWorkVersions_Update
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbProductionsWorkVersions_Update'))
	DROP VIEW dbo.AbProductionsWorkVersions_Update

go
CREATE VIEW dbo.AbProductionsWorkVersions_Update
AS 
	SELECT
		pwv.*
	FROM  
		ProductionsWorkVersions pwv
	WHERE 
		pwv.ProductionId IN (
		SELECT P.SNr FROM dbo.Stücke AS P			
			INNER JOIN	(SELECT DISTINCT GruppeID, Schreiben,OptionsFlag&2 Write
							FROM			UserGruppe 
								INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
							WHERE	Username = CURRENT_USER AND 
									BerechtigungsbereichID = 3 AND 
									(Schreiben = 1 OR (OptionsFlag&2) = 2) ) AS UG
					ON P.ModuleGroupId = UG.GruppeID) 
	WITH CHECK OPTION
					--Schreibrecht oder Werke Zuweisen
GO
GRANT SELECT, DELETE, INSERT, UPDATE ON AbProductionsWorkVersions_Update TO public
GO
--#endregion

--#region DH 2017-11-20 Spalte OwnerGroupId in Tabelle ChecklistItem 
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'OwnerGroupId' and o.id = OBJECT_ID(N'[dbo].[CheckListItem]'))
BEGIN
	ALTER TABLE dbo.CheckListItem ADD OwnerGroupId INT NOT NULL CONSTRAINT DF_CheckListItem_OwnerGroupId DEFAULT 0;
	EXEC	('UPDATE C	SET c.OwnerGroupId = s.ModuleGroupId FROM dbo.CheckListItem C	INNER JOIN dbo.Stücke S ON C.ProductionId = S.SNr WHERE C.OwnerGroupId = 0')
END
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_CheckListItem_OwnerGroupId') AND type = 'F') ALTER TABLE dbo.CheckListItem	DROP CONSTRAINT FK_CheckListItem_OwnerGroupId
BEGIN 
	ALTER TABLE dbo.CheckListItem  WITH CHECK ADD  CONSTRAINT FK_CheckListItem_OwnerGroupId FOREIGN KEY(OwnerGroupId)
	REFERENCES dbo.Gruppe (GruppeID) ON DELETE CASCADE
	ALTER TABLE dbo.CheckListItem CHECK CONSTRAINT FK_CheckListItem_OwnerGroupId
END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCheckListItem]'))	DROP VIEW [dbo].[AbCheckListItem]
Print ('Creating View AbCheckListItem');
GO
CREATE VIEW [dbo].[AbCheckListItem]
AS 
SELECT  cli.*  FROM  CheckListItem  AS cli WHERE cli.CheckListItemId IN
	   (SELECT S.CheckListItemId
		FROM CheckListItem AS S 
			INNER JOIN UserGruppe ON S.OwnerGroupId = UserGruppe.GruppeID 
			INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 17)
WITH CHECK OPTION
GO
GRANT SELECT, DELETE, INSERT, UPDATE ON [AbCheckListItem] TO public
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCheckListItem_Update]'))	DROP VIEW [dbo].[AbCheckListItem_Update]
Print ('Creating View AbCheckListItem_Update');
GO
CREATE VIEW [dbo].[AbCheckListItem_Update]
AS 
SELECT  cli.*  FROM  CheckListItem  AS cli WHERE cli.CheckListItemId IN
	   (SELECT S.CheckListItemId
		FROM CheckListItem AS S 
			INNER JOIN UserGruppe ON S.OwnerGroupId = UserGruppe.GruppeID 
			INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 17 AND UserGruppe.Schreiben = 1)
WITH CHECK OPTION
GO
GRANT SELECT, DELETE, INSERT, UPDATE ON [AbCheckListItem_Update] TO public
GO
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 176 OR (Minor=176 AND Build <= 3)))))
BEGIN
	PRINT ('Setting Permissions on Checklists')
	--Schreibberechtigung
	INSERT INTO UserGruppe (
		GruppeID, USERID, Schreiben, LM,		UM,	LC,			UC, BerechtigungsbereichID, OptionsFlag,IsInherited, Options)
	SELECT 
		GruppeID, USERID, Schreiben, GETDATE(),	-1,	GETDATE(),	-1,	17,						0,			IsInherited, null 
	FROM UserGruppe	U		
		WHERE U.Schreiben = 1 AND U.BerechtigungsbereichID=3 
		AND NOT EXISTS ( SELECT UserGruppeID FROM UserGruppe U2 WHERE u2.BerechtigungsbereichID=17 AND u.GruppeID=u2.GruppeID AND u.UserID=u2.UserID and U2.Schreiben =1);
	INSERT INTO UserGruppe (
		GruppeID, USERID, Schreiben, LM,		UM,	LC,			UC, BerechtigungsbereichID, OptionsFlag,IsInherited, Options)
	SELECT 
		GruppeID, USERID, Schreiben, GETDATE(),	-1,	GETDATE(),	-1,	17,						0,			IsInherited, null 
	FROM UserGruppe	U		
		WHERE U.Schreiben = 0 AND U.BerechtigungsbereichID=3 
		AND NOT EXISTS ( SELECT UserGruppeID FROM UserGruppe U2 WHERE u2.BerechtigungsbereichID=17 AND u.GruppeID=u2.GruppeID AND u.UserID=u2.UserID and U2.Schreiben = 0);
END
--#endregion 2017-11-20 DH

--#region SH 20171124 Spalte Code für Kostenart
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'ExportCode' and o.id = OBJECT_ID(N'dbo.CostTypes'))
	ALTER TABLE dbo.CostTypes ADD ExportCode VARCHAR(10) NULL
GO
--#endregion

--#region SH 20171128 Spalten BudgetReference und Prevision für Budgets
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'BudgetReference' and o.id = OBJECT_ID(N'dbo.Budgets'))
	ALTER TABLE dbo.Budgets ADD BudgetReference VARCHAR(200) SPARSE NULL
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'Prevision' and o.id = OBJECT_ID(N'dbo.Budgets'))
	ALTER TABLE dbo.Budgets ADD Prevision VARCHAR(200) SPARSE NULL
GO
--#endregion

--#region SH 20171128 Spalten BookableFrom und BookableTo für CostCenter, CostTypes, BudgetItem
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'BookableFrom' and o.id = OBJECT_ID(N'dbo.CostCenter'))
	ALTER TABLE dbo.CostCenter ADD BookableFrom DATE SPARSE NULL
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'BookableTo' and o.id = OBJECT_ID(N'dbo.CostCenter'))
	ALTER TABLE dbo.CostCenter ADD BookableTo DATE SPARSE NULL
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'BookableFrom' and o.id = OBJECT_ID(N'dbo.CostTypes'))
	ALTER TABLE dbo.CostTypes ADD BookableFrom DATE SPARSE NULL
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'BookableTo' and o.id = OBJECT_ID(N'dbo.CostTypes'))
	ALTER TABLE dbo.CostTypes ADD BookableTo DATE SPARSE NULL
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'BookableFrom' and o.id = OBJECT_ID(N'dbo.BudgetItem'))
	ALTER TABLE dbo.BudgetItem ADD BookableFrom DATE SPARSE NULL
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'BookableTo' and o.id = OBJECT_ID(N'dbo.BudgetItem'))
	ALTER TABLE dbo.BudgetItem ADD BookableTo DATE SPARSE NULL
GO
--#endregion

--#region tk 2017-11-06
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.PersKom') AND o.Name = 'IX_PersId_Sort_PersKTypID')
BEGIN
	DROP INDEX PersKom.IX_PersId_Sort_PersKTypID
	Update Perskom SET PersKTypId = 0  WHERE PersKTypId is null
	ALTER TABLE PersKom ALTER COLUMN PersKTypId INT NOT NULL
END
GO
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.PersKom') AND o.Name = 'PK_PersNr')
BEGIN
	DROP INDEX PersKom.PK_PersNr
	DELETE FROM PersKom WHERE PersNr IS NULL
	ALTER TABLE PersKom ALTER COLUMN PersNr INT NOT NULL
	CREATE INDEX IX_PersCom_PersonId ON dbo.PersKom (PersNr) ON [PRIMARY]
	ALTER TABLE PersKom ALTER COLUMN Bemerkung VARCHAR(150) SPARSE NULL
	ALTER TABLE PersKom DROP COLUMN PersKomTS
	UPDATE PersKom Set Sort = 0 WHERE Sort IS NULL
	ALTER TABLE PersKom ALTER COLUMN Sort INT NOT NULL 
	ALTER TABLE PersKom ADD CONSTRAINT DF_PersCom_Sort DEFAULT 0 FOR Sort
--
	UPDATE PersKomTyp Set Sort = 0 WHERE Sort IS NULL
	ALTER TABLE PersKomTyp ALTER COLUMN Sort INT NOT NULL 
	ALTER TABLE PersKomTyp ADD CONSTRAINT DF_PersComTyp_Sort DEFAULT 0 FOR Sort

	UPDATE PersKomTyp Set KDefault = 0 WHERE KDefault IS NULL
	ALTER TABLE PersKomTyp ALTER COLUMN KDefault BIT NOT NULL 
	ALTER TABLE PersKomTyp ADD CONSTRAINT DF_PersComTyp_KDefault DEFAULT 0 FOR KDefault

	UPDATE PersKomTyp Set KTyp = 0 WHERE KTyp IS NULL
	ALTER TABLE PersKomTyp ALTER COLUMN KTyp TINYINT NOT NULL 
	ALTER TABLE PersKomTyp ADD CONSTRAINT DF_PersComTyp_KTyp DEFAULT 0 FOR KTyp

	UPDATE PersKomTyp Set KTyp = 0 WHERE KTyp IS NULL
	ALTER TABLE PersKomTyp ALTER COLUMN KTyp TINYINT NOT NULL 
	--ALTER TABLE PersKomTyp ADD CONSTRAINT DF_PersComTyp_KTyp DEFAULT 0 FOR KTyp

	ALTER TABLE PersKomTyp DROP COLUMN PersKomTypTS
	ALTER TABLE PersKomTyp DROP COLUMN Gesperrt
	IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.PersKomTyp') AND o.Name = 'UQ_PersKomTyp_Bezeichnung')
	BEGIN
		DROP INDEX PersKomTyp.UQ_PersKomTyp_Bezeichnung
	END

	UPDATE PersKomTyp SET Bezeichnung = '-' WHERE Bezeichnung IS NULL
	ALTER TABLE PersKomTyp ALTER COLUMN Bezeichnung VARCHAR(50) NOT NULL

	CREATE UNIQUE INDEX IX_PersComTyp_Name ON dbo.PersKomTyp (Bezeichnung) ON [PRIMARY]

END
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.Personal_Instrumente') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE Personal_Instrumente
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.Produktionsplan') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE Produktionsplan
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.Waehrung') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE Waehrung
GO
DropColumn 'PersonalHonorar', 'UserModified'
GO
DropColumn 'PersonalHonorar', 'LastModified'
GO
DropColumn 'PersonalHonorar', 'HonorarVs'
GO
DropColumn 'PersonalHonorar', 'HonorarUeberspiel'
GO
DropColumn 'PersonalHonorar', 'HonorarPro'
GO
DropColumn 'PersonalHonorar', 'PersonalHonorarTS'
GO
DropColumn 'PersonalNotizen', 'PersonalNotizenTS'
GO
DropColumn 'PersonalNotizen', 'UserModified'
GO
DropColumn 'PersonalNotizen', 'Datum'
GO
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.PersonalNotizen') AND o.Name = 'IX_PersNr')
BEGIN
	DROP INDEX PersonalNotizen.IX_PersNr
	DELETE FROM PersonalNotizen  WHERE PersNr IS NULL
	ALTER TABLE PersonalNotizen ALTER COLUMN PersNr INT NOT NULL
	CREATE INDEX IX_PersonalNotes_PersonId ON dbo.PersonalNotizen (PersNr) ON [PRIMARY]

	DELETE FROM PersonalNotizen  WHERE Besitzer IS NULL
	ALTER TABLE PersonalNotizen ALTER COLUMN Besitzer INT NOT NULL
	DELETE FROM PersonalNotizen WHERE Besitzer NOT IN (SELECT GruppeId FROM Gruppe)
	ALTER TABLE dbo.PersonalNotizen  WITH CHECK ADD  CONSTRAINT FK_PersonalNotes_Groups FOREIGN KEY (Besitzer)
	REFERENCES dbo.Gruppe (GruppeId) ON DELETE CASCADE
	ALTER TABLE dbo.PersonalNotizen CHECK CONSTRAINT FK_PersonalNotes_Groups

	ALTER TABLE PersonalNotizen ALTER COLUMN Inhalt VARCHAR(512)
	ALTER TABLE PersonalNotizen ALTER COLUMN Notizen VARCHAR(MAX)

	UPDATE DienstplanArtenTabelle SET DPGruppenID = NULL WHERE NOT EXISTS (SELECT * FROM DienstplanGruppen WHERE DienstplanGruppen.DienstplanGruppenID = DienstplanArtenTabelle.DPGruppenID)
	ALTER TABLE dbo.DienstplanArtenTabelle  WITH CHECK ADD  CONSTRAINT FK_Departments_DepartmentGroups FOREIGN KEY(DPGruppenID)
	REFERENCES dbo.DienstplanGruppen (DienstplanGruppenID) ON DELETE SET NULL
	ALTER TABLE dbo.DienstplanArtenTabelle CHECK CONSTRAINT FK_Departments_DepartmentGroups

END
GO

IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Zeitkonten') AND [name] = 'Settings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'Zeitkonten' ,@columnname = 'Settings'
END
GO

--#endregion

--#region tk 2017-12-12 umstellung der formeln und summen
IF NOT EXISTS (SELECT * FROM sysColumns c 	WHERE c.name = 'InternalCode' AND id = OBJECT_ID(N'dbo.FormulaConfigurations'))
BEGIN
	ALTER TABLE FormulaConfigurations ADD InternalCode VARCHAR(5) NULL
	print('Columns InternalCode for FormulaConfigurations added!'); 
END
GO

IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('FormulaConfigurations') AND [name] = 'SerializedParameter' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'FormulaConfigurations' ,@columnname = 'SerializedParameter'
END
GO

IF NOT EXISTS (SELECT * FROM FormulaConfigurations WHERE NOT InternalCode IS NULL)
BEGIN

	--DELETE from FormulaConfigurations_Departments WHERE FormulaConfigurations_Departments.FormulaConfigurationId in (SELECT FormulaConfigurationId FROM FormulaConfigurations WHERE NOT InternalCode IS NULL)
	--DELETE FROM FormulaConfigurations WHERE NOT InternalCode IS NULL
		DECLARE @sickId VARCHAR(MAX)
		DECLARE @id VARCHAR(MAX)
		DECLARE @Name VARCHAR(MAX)
		DECLARE @yearCloseId INT
		SET @sickId = -1
		SELECT @sickId = CONVERT(VARCHAR(MAX), ZeitKtoNr) FROM Zeitkonten WHERE  Formel = 3011
		SELECT TOP 1 @yearCloseId = Zeitkonten.YearCloseTypeId FROM Zeitkonten
		SELECT TOP 1 @yearCloseId = Zeitkonten.YearCloseTypeId FROM Zeitkonten WHERE Formel = 1


	DECLARE @country VARCHAR(20)
	SELECT @country = WertText FROM Settings WHERE Form = 'Adresse' AND Control = 'Country'

	DECLARE @code as VARCHAR(5)
	DECLARE @long AS VARCHAR(50)



--Monatliche Arbeitszeit
	SELECT @code = 'MoAz', @long = 'Monatliche Arbeitszeit'
	IF @country = 'EN' SELECT @code = 'MoWt', @long = 'Monthly working time'
	IF @country = 'F' OR @country = 'BE'SELECT @code = 'TTm',  @long = 'Temps de travail mensuel'

	INSERT INTO FormulaConfigurations ([Name], Code,InternalCode, Modul, FormulaId, LC, UC, LM, UM, SerializedParameter)
	VALUES (@long,@code,'MoWt', 4, 'OvertimeInPeriodFormula',GetDate() ,-1, GetDate(), -1, '<PlusMinusHoursInPeriodFormulaParameter PeriodType="Months" PeriodCount="1" StartMonth="0" DebitHoursBy="Planned" InformationType="Actual" AbsoluteValues="false" EndIsCurrentWeek="false" TimeAccountId="0" />')
	SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
	INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC,UC,LM,UM)
	SELECT @id, DienstplanArtenID, GetDate(), -1,GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&1 = 1
--Wöchentliche Arbeitszeit
	SELECT @code = 'WoAz', @long = 'Wöchentliche Arbeitszeit'
	IF @country = 'EN' SELECT @code = 'WeWt', @long = 'Weekly working hours'
	IF @country = 'F' OR @country = 'BE'SELECT @code = 'TTh',  @long = 'Temps de travail hebdomadaire'
	IF NOT EXISTS (SELECT * FROM FormulaConfigurations WHERE FormulaId = 'WeeklySumFormula')
	BEGIN
		INSERT INTO FormulaConfigurations ([Name], Code,InternalCode, Modul, FormulaId, LC, UC, LM, UM, SerializedParameter)
		VALUES (@long,@code,'wAc', 4, 'WeeklySumFormula', GetDate(),-1 ,GetDate(),-1 , '<WeeklySumFormulaParameter InformationType="Actual" />')
		SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC, UC, LM, UM)
		SELECT @id, DienstplanArtenID, GetDate(), -1,GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&2 = 2
	END
	ELSE
	BEGIN
		UPDATE FormulaConfigurations SET InternalCode = 'wAc', SerializedParameter = '<WeeklySumFormulaParameter InformationType="Actual" />' WHERE FormulaId = 'WeeklySumFormula'
		SELECT @id = FormulaConfigurationId FROM FormulaConfigurations WHERE InternalCode = 'wAc'
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC, UC, LM, UM)
		SELECT @id, DienstplanArtenID, GetDate(), -1, GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&2 = 2 AND
			NOT EXISTS(SELECT * FROM FormulaConfigurations_Departments AS cd WHERE DienstplanArtenTabelle.DienstplanArtenID = cd.DepartmentId AND cd.FormulaConfigurationId = @id)
	END
--Wöchentliche Sollarbeitszeit
	SELECT @code = 'WoSoll', @long = 'Wöchentliche Sollarbeitszeit'
	IF @country = 'EN' SELECT @code = 'WeRe', @long = 'weekly regular working time hours'
	--IF @country = 'F' OR @country = 'BE'SELECT @code = '####',  @long = '###'

	IF NOT EXISTS (SELECT * FROM FormulaConfigurations WHERE FormulaId = 'WeeklyPLannedWorkingTimeFormula')
		INSERT INTO FormulaConfigurations ([Name], Code,InternalCode, Modul, FormulaId, LC, UC, LM, UM,SerializedParameter )
		VALUES ('Wöchentliche Sollarbeitszeit','WoSol','wRe', 4, 'WeeklySumFormula', GetDate(), -1, GetDate(), -1 , '<WeeklySumFormulaParameter InformationType="Debit" />')
	ELSE
		UPDATE FormulaConfigurations SET InternalCode = 'wRe', FormulaId = 'WeeklySumFormula', SerializedParameter = '<WeeklySumFormulaParameter InformationType="Debit" />' WHERE FormulaId = 'WeeklyPLannedWorkingTimeFormula'
--Wöchentliche +/-
	SELECT @code = 'Wo+/-', @long = 'Wöchentliche +/-'
	IF @country = 'EN' SELECT @code = 'We+/-', @long = 'weekly +/-'
	--IF @country = 'F' OR @country = 'BE'SELECT @code = '####',  @long = '###'

	INSERT INTO FormulaConfigurations ([Name], Code,InternalCode, Modul, FormulaId, LC, UC, LM, UM,SerializedParameter )
	VALUES (@long,@code,'w+/-', 4, 'WeeklySumFormula', GetDate(), -1, GetDate(), -1, '<WeeklySumFormulaParameter InformationType="PlusMinus" />')
--Arbeitszeit der Abrechnungsperiode
	SELECT @code = 'JAz', @long = 'Jährliche Arbeitszeit'
	IF @country = 'EN' SELECT @code = 'Y Wt', @long = 'Yearly working time'
	--IF @country = 'F' OR @country = 'BE'SELECT @code = '####',  @long = '###'

	INSERT INTO FormulaConfigurations ([Name], Code,InternalCode, Modul, FormulaId, LC,UC,LM,UM,SerializedParameter )
	VALUES (@long, @code,'pAt', 4, 'OvertimeInPeriodFormula', GetDate(), -1, GetDate(), -1, '<PlusMinusHoursInPeriodFormulaParameter  PeriodType="YearCloseType" PeriodCount="1" StartMonth="0" DebitHoursBy="Planned" InformationType="Actual" AbsoluteValues="false" EndIsCurrentWeek="true" TimeAccountId="0" />')
	SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
	INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC,UC,LM,UM)
	SELECT @id, DienstplanArtenID, GetDate(), -1 ,GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&4 = 4
--Jahresurlaub
	IF EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 3010) --Url
	BEGIN
		SELECT @id = CONVERT(VARCHAR(MAX), ZeitKtoNr) , @name = Bez FROM Zeitkonten WHERE  Formel = 3010
		SELECT @code = 'JUrl', @long = 'Jahresurlaub'
		IF @country = 'EN' SELECT @code = 'Y Vac', @long = 'Vacation year'
		IF @country = 'F' OR @country = 'BE'SELECT @code = 'Co J',  @long = 'Jours de congé'

		INSERT INTO FormulaConfigurations ([Name], Code,InternalCode, Modul, FormulaId, LC, UC, LM, UM, SerializedParameter)
		VALUES (@long, @code,'pVa', 4, 'TimeAccountFormula',GetDate(), -1, GetDate() ,-1, '<TimeAccountFormulaParameter TimeAccountId="10" MonthValuesFromDutyRoster="true">
																								  <PeriodParameter>
																									<PeriodElementsCount>1</PeriodElementsCount>
																									<PeriodElementType>YearCloseType</PeriodElementType>
																									<IsCurrentWeekPeriodEnd>false</IsCurrentWeekPeriodEnd>
																								  </PeriodParameter>
																								</TimeAccountFormulaParameter>')
		SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC, UC, LM, UM)
		SELECT @id, DienstplanArtenId, GetDate(), -1,GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&8 = 8
	--Aktueller Urlaub

		SELECT @id = CONVERT(VARCHAR(MAX), ZeitKtoNr) , @name = Bez FROM Zeitkonten WHERE  Formel = 3010
		SELECT @code = 'AUrl', @long = 'Aktueller Urlaub'
		IF @country = 'EN' SELECT @code = 'C Vac', @long = 'Current vacation'
		IF @country = 'F' OR @country = 'BE'SELECT @code = 'Co A', @long = 'Congé act.'

		INSERT INTO FormulaConfigurations (Name, Code,InternalCode, Modul, FormulaId, LC,UC,LM,UM,SerializedParameter )
		VALUES (@long, @code,'cVA', 4, 'TimeAccountFormula', GetDate(), -1, GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id + '" MonthValuesFromDutyRoster="true">
																								  <PeriodParameter>
																									<PeriodElementsCount>1</PeriodElementsCount>
																									<PeriodElementType>YearCloseType</PeriodElementType>
																									<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																								  </PeriodParameter>
																								</TimeAccountFormulaParameter>')
		SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC,UC,LM,UM)
		SELECT @id, DienstplanArtenID, GetDate(), -1, GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&524288 = 524288
	END
--Plus/Minus-Stunden
	SELECT @code = '+/-', @long = 'Plus/Minus-Stunden'
	IF @country = 'EN' SELECT  @long = 'Plus/Minus-Hours'
	IF @country = 'F' OR @country = 'BE'SELECT  @long = 'Heures +/-'

	IF EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 1252) --+--
	BEGIN	
		SELECT @id = CONVERT(VARCHAR(MAX), ZeitKtoNr) FROM Zeitkonten WHERE  Formel = 1252
		INSERT INTO FormulaConfigurations ([Name], Code,InternalCode, Modul, FormulaId, LC, UC, LM, UM, SerializedParameter )
		VALUES (@long, @code,'c+/-', 4, 'TimeAccountFormula', GetDate(), -1, GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id + '" SumCountingSource="TimeAccountUntilMonthClosure">
																								  <PeriodParameter>
																									<PeriodElementsCount>1</PeriodElementsCount>
																									<PeriodElementType>YearCloseType</PeriodElementType>
																									<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																								  </PeriodParameter>
																								  <ShowBudget>false</ShowBudget>
																								</TimeAccountFormulaParameter>')
		SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC, UC, LM, UM)
		SELECT @id, DienstplanArtenID, GetDate(), -1,GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&16 = 16
	END
--Feiertage
	SELECT @code = 'Ft', @long = 'Feiertage'
	IF @country = 'EN' SELECT @code = 'HoD', @long = 'Holidays'
	IF @country = 'F' OR @country = 'BE'SELECT @code = 'jo fé',  @long = 'Jours fériés'

	IF EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 1230) --Ft
	BEGIN	
		SELECT @id = CONVERT(VARCHAR(MAX), ZeitKtoNr) FROM Zeitkonten WHERE  Formel = 1230
		INSERT INTO FormulaConfigurations ([Name], Code,InternalCode, Modul, FormulaId, LC, UC, LM, UM, SerializedParameter )
		VALUES (@long,@code,'cBH', 4, 'TimeAccountFormula', GetDate(), -1, GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id + '" MonthValuesFromDutyRoster="true">
																								  <PeriodParameter>
																									<PeriodElementsCount>1</PeriodElementsCount>
																									<PeriodElementType>YearCloseType</PeriodElementType>
																									<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																								  </PeriodParameter>
																								</TimeAccountFormulaParameter>')
		SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC, UC, LM, UM)
		SELECT @id, DienstplanArtenID, GetDate(), -1,GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&262144 = 262144
	END
--Freie Tage +/-
	SELECT @code = 'Frei', @long = 'Freie Tage +/-'
	IF @country = 'EN' SELECT @code = 'Free', @long = 'Free days +/-'
	IF @country = 'F' OR @country = 'BE'SELECT @code = 'Libre',  @long = 'Libre +/-'
	
	IF EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 3050) --Frei
	BEGIN
		SELECT @id = CONVERT(VARCHAR(MAX), ZeitKtoNr) , @name = Bez FROM Zeitkonten WHERE  Formel = 3050
		INSERT INTO FormulaConfigurations ([Name], Code,InternalCode, Modul, FormulaId, LC, UC, LM, UM, SerializedParameter )
		VALUES (@long, @code, 'free', 4, 'TimeAccountFormula', GetDate(), -1, GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id + '" MonthValuesFromDutyRoster="true">
																								  <PeriodParameter>
																									<PeriodElementsCount>1</PeriodElementsCount>
																									<PeriodElementType>YearCloseType</PeriodElementType>
																									<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																								  </PeriodParameter>
																								</TimeAccountFormulaParameter>')
		SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC,UC,LM,UM)
		SELECT @id, DienstplanArtenID, GetDate(), -1, GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&2097152 = 2097152
	END
--FreiKurz
	IF EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 3051) --FreiKurz
	BEGIN
		SELECT @id = CONVERT(VARCHAR(MAX), ZeitKtoNr) , @name = Bez FROM Zeitkonten WHERE  Formel = 3051

		INSERT INTO FormulaConfigurations ([Name], Code, Modul, FormulaId, LC, UC, LM, UM, SerializedParameter)
		VALUES (@name, LEFT(@name,5), 4, 'TimeAccountFormula', GetDate(), -1, GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id + '" MonthValuesFromDutyRoster="true">
																								  <PeriodParameter>
																									<PeriodElementsCount>1</PeriodElementsCount>
																									<PeriodElementType>YearCloseType</PeriodElementType>
																									<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																								  </PeriodParameter>
																								</TimeAccountFormulaParameter>')
		SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC, UC, LM, UM)
		SELECT @id, DienstplanArtenID, GetDate(), -1, GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&1048576 = 1048576  
	END
--Jubiläumstage
	IF EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 3013) --Jub
	BEGIN
		SELECT @id = CONVERT(VARCHAR(MAX), ZeitKtoNr) , @name = Bez FROM Zeitkonten WHERE  Formel = 3013

		INSERT INTO FormulaConfigurations ([Name], Code, Modul, FormulaId, LC, UC, LM, UM, SerializedParameter )
		VALUES (@name, LEFT(@name,5), 4, 'TimeAccountFormula', GetDate(), -1, GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id + '" MonthValuesFromDutyRoster="true">
																								  <PeriodParameter>
																									<PeriodElementsCount>1</PeriodElementsCount>
																									<PeriodElementType>YearCloseType</PeriodElementType>
																									<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																								  </PeriodParameter>
																								</TimeAccountFormulaParameter>')
		SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC,UC,LM,UM)
		SELECT @id, DienstplanArtenID, GetDate(), -1, GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&0x8000000 = 0x8000000  
	END
--AK-Tage
	IF EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 3020) --Ak
	BEGIN
		SELECT @id = CONVERT(VARCHAR(MAX), ZeitKtoNr) , @name = Bez FROM Zeitkonten WHERE  Formel = 3020

		INSERT INTO FormulaConfigurations (Name, Code, Modul, FormulaId, LC,UC,LM,UM,SerializedParameter )
		VALUES (@name, LEFT(@name,5), 4, 'TimeAccountFormula', GetDate(), -1, GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id + '" MonthValuesFromDutyRoster="true">
																								  <PeriodParameter>
																									<PeriodElementsCount>1</PeriodElementsCount>
																									<PeriodElementType>YearCloseType</PeriodElementType>
																									<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																								  </PeriodParameter>
																								</TimeAccountFormulaParameter>')
		SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC,UC,LM,UM)
		SELECT @id, DienstplanArtenID, GetDate(), -1, GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&0x10000000 = 0x10000000  
	END
--Jahressoll (Stunden)
	IF EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 1281) --Debit Hours
	BEGIN
		SELECT @id = CONVERT(VARCHAR(MAX), ZeitKtoNr) , @name = Bez FROM Zeitkonten WHERE  Formel = 1281

		INSERT INTO FormulaConfigurations ([Name], Code, Modul, FormulaId, LC, UC, LM, UM, SerializedParameter)
		VALUES (@name, LEFT(@name,5), 4, 'TimeAccountFormula', GetDate(), -1, GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id + '" MonthValuesFromDutyRoster="true">
																								  <PeriodParameter>
																									<PeriodElementsCount>1</PeriodElementsCount>
																									<PeriodElementType>YearCloseType</PeriodElementType>
																									<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																								  </PeriodParameter>
																								</TimeAccountFormulaParameter>')
		SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC,UC,LM,UM)
		SELECT @id, DienstplanArtenID, GetDate(), -1, GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&0x40000000 = 0x40000000
	END
--Jahressoll (Tage)
	IF EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 1282) --Debit Days
	BEGIN
		SELECT @id = CONVERT(VARCHAR(MAX), ZeitKtoNr) , @name = Bez FROM Zeitkonten WHERE  Formel = 1282

		INSERT INTO FormulaConfigurations ([Name], Code, Modul, FormulaId, LC, UC, LM, UM, SerializedParameter )
		VALUES (@name, LEFT(@name,5), 4, 'TimeAccountFormula', GetDate(), -1, GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id + '" MonthValuesFromDutyRoster="true">
																								  <PeriodParameter>
																									<PeriodElementsCount>1</PeriodElementsCount>
																									<PeriodElementType>YearCloseType</PeriodElementType>
																									<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																								  </PeriodParameter>
																								</TimeAccountFormulaParameter>')
		SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC,UC,LM,UM)
		SELECT @id, DienstplanArtenID, GetDate(), -1, GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&0x20000000 = 0x20000000  
	END
--Mehrteiler
	IF EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 1226) --mehrteiler
	BEGIN
		SELECT @id = CONVERT(VARCHAR(MAX), ZeitKtoNr) , @name = Bez FROM Zeitkonten WHERE  Formel = 1226

		INSERT INTO FormulaConfigurations ([Name], Code, Modul, FormulaId, LC,UC,LM,UM,SerializedParameter )
		VALUES (@name, LEFT(@name,5), 4, 'TimeAccountFormula', GetDate(), -1, GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id + '" MonthValuesFromDutyRoster="true">
																								  <PeriodParameter>
																									<PeriodElementsCount>1</PeriodElementsCount>
																									<PeriodElementType>YearCloseType</PeriodElementType>
																									<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																								  </PeriodParameter>
																								</TimeAccountFormulaParameter>')
		SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
		INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC,UC,LM,UM)
		SELECT @id, DienstplanArtenID, GetDate(), -1, GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&0x1000000 = 0x1000000  
	END
--Frei Sonntage
	SELECT @code = 'F.So', @long = 'Frei Sonntage'
	IF @country = 'EN' SELECT @code = 'F Su', @long = 'Free sundays'
	IF @country = 'F' OR @country = 'BE'SELECT @code = 'L Di',  @long = 'Dimanches libres'

	INSERT INTO Zeitkonten (Bez, Formel, YearCloseTypeId, IsCreditAccount, Module, LC, UC, LM, UM, Settings)
	VALUES (@long, 1203, @yearCloseId, 0, 4, GetDate(), -1, GetDate(), -1, '<CountingDaysAndHoursSettings>
																		  <WorkShifts>NoFilter</WorkShifts>
																		  <DaysOfWeek>Sunday</DaysOfWeek>
																		  <CountFreeDays>true</CountFreeDays>
																		</CountingDaysAndHoursSettings>')
	SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
	
	INSERT INTO FormulaConfigurations ([Name], Code,InternalCode, Modul, FormulaId, LC,UC,LM,UM,SerializedParameter )
	VALUES (@long, @code,'cFSu', 4, 'TimeAccountFormula', GetDate(), -1,GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id + '" MonthValuesFromDutyRoster="true">
																							  <PeriodParameter>
																								<PeriodElementsCount>1</PeriodElementsCount>
																								<PeriodElementType>YearCloseType</PeriodElementType>
																								<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																							  </PeriodParameter>
																							</TimeAccountFormulaParameter>')
	SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
	INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC, UC, LM, UM)
	SELECT @id, DienstplanArtenID, GetDate(), -1, GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&64 = 64
--Frei Sonnabend
	SELECT @code = 'F.Sa', @long = 'Frei Sonnabend'
	IF @country = 'EN' SELECT @code = 'F Sa', @long = 'Free saturdays'
	IF @country = 'F' OR @country = 'BE'SELECT @code = 'L Sa',  @long = 'Samedis libres'

	INSERT INTO Zeitkonten (Bez, Formel, YearCloseTypeId, IsCreditAccount, Module, LC, UC, LM, UM, Settings)
	VALUES (@long, 1203, @yearCloseId, 0, 4, GetDate(), -1, GetDate(), -1, '<CountingDaysAndHoursSettings>
																		  <WorkShifts>NoFilter</WorkShifts>
																		  <DaysOfWeek>Saturday</DaysOfWeek>
																		  <CountFreeDays>true</CountFreeDays>
																		</CountingDaysAndHoursSettings>')
	SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
	
	INSERT INTO FormulaConfigurations ([Name], Code,InternalCode, Modul, FormulaId, LC,UC,LM,UM,SerializedParameter )
	VALUES (@long, @code, 'cFSa', 4, 'TimeAccountFormula', GetDate(), -1,GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id+ '" MonthValuesFromDutyRoster="true">
																							  <PeriodParameter>
																								<PeriodElementsCount>1</PeriodElementsCount>
																								<PeriodElementType>YearCloseType</PeriodElementType>
																								<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																							  </PeriodParameter>
																							</TimeAccountFormulaParameter>')
	SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
	INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC, UC, LM, UM)
	SELECT @id, DienstplanArtenID, GetDate(), -1,GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&32 = 32
--Frei Wochenenden
	SELECT @code = 'F.We', @long = 'Frei Wochenenden'
	IF @country = 'EN' SELECT @code = 'F we', @long = 'Free weekends'
	IF @country = 'F' OR @country = 'BE'SELECT @code = 'L We',  @long = 'Week-ends libres'

	INSERT INTO Zeitkonten (Bez, Formel, YearCloseTypeId, IsCreditAccount, Module, LC, UC, LM, UM, Settings)
	VALUES (@long, 1203, @yearCloseId, 0, 4, GetDate(), -1, GetDate(), -1,'<CountingDaysAndHoursSettings>
																		  <WorkShifts>NoFilter</WorkShifts>
																		  <OnCompleteWeekend>true</OnCompleteWeekend>
																		  <CountFreeDays>true</CountFreeDays>
																		</CountingDaysAndHoursSettings>')
	SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
	
	INSERT INTO FormulaConfigurations ([Name], Code, InternalCode, Modul, FormulaId, LC, UC, LM, UM, SerializedParameter)
	VALUES (@long, @code,'cFWE', 4, 'TimeAccountFormula', GetDate(), -1,GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id+'" MonthValuesFromDutyRoster="true">
																							  <PeriodParameter>
																								<PeriodElementsCount>1</PeriodElementsCount>
																								<PeriodElementType>YearCloseType</PeriodElementType>
																								<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																							  </PeriodParameter>
																							</TimeAccountFormulaParameter>')
	SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
	INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC,UC,LM,UM)
	SELECT @id, DienstplanArtenID, GetDate(), -1,GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&128 = 128
--Gearbeitete Sonntage
	SELECT @code = 'G.So', @long = 'Gearbeitete Sonntage'
	IF @country = 'EN' SELECT @code = 'W Su', @long = 'Worked on Sundays'
	IF @country = 'F' OR @country = 'BE'SELECT @code = 'trv Di',  @long = 'Dimanches travaillés'

	INSERT INTO Zeitkonten (Bez, Formel, YearCloseTypeId, Module, LC, UC, LM, UM, Settings)
	VALUES (@long,1203, @yearCloseId, 4, GetDate(), -1, GetDate(), -1,'<CountingDaysAndHoursSettings>
																		  <Accounts>
																			<AccountId>' + @sickId+ '</AccountId>
																			<EveryDayCount>false</EveryDayCount>
																		  </Accounts>
																		  <Accounts>
																			<AccountId>1</AccountId>
																			<EveryDayCount>false</EveryDayCount>
																		</Accounts>
																		  <WorkShifts>MinOneWorkShift</WorkShifts>
																		  <DayOyWeek>Sunday</DayOyWeek>
																		</CountingDaysAndHoursSettings>')
	SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
	
	INSERT INTO FormulaConfigurations ([Name], Code,InternalCode, Modul, FormulaId, LC, UC, LM, UM, SerializedParameter)
	VALUES (@long, @code,'cWSu', 4, 'TimeAccountFormula', GetDate(), -1,GetDate(), -1, '<TimeAccountFormulaParameter TimeAccountId="' + @id+'" MonthValuesFromDutyRoster="true">
																							  <PeriodParameter>
																								<PeriodElementsCount>1</PeriodElementsCount>
																								<PeriodElementType>YearCloseType</PeriodElementType>
																								<IsCurrentWeekPeriodEnd>true</IsCurrentWeekPeriodEnd>
																							  </PeriodParameter>
																							</TimeAccountFormulaParameter>')
	SELECT @id = CONVERT(VARCHAR(MAX), SCOPE_IDENTITY())
	INSERT INTO FormulaConfigurations_Departments (FormulaConfigurationId, DepartmentId, LC, UC, LM, UM)
	SELECT @id, DienstplanArtenID, GetDate(), -1, GetDate(), -1 FROM DienstplanArtenTabelle WHERE DienstplanArtenTabelle.SumColVisible&0x4000000 = 0x4000000


	DECLARE @sick AS NVARCHAR(MAX) 
	DECLARE @leave AS NVARCHAR(MAX) 
	DECLARE @holiday AS NVARCHAR(MAX) 
	SET @sick = ''
	SET @leave = ''
	SET @holiday = ''

	SELECT @sick = '<Accounts><AccountId>' + CONVERT(VARCHAR(MAX), ZeitKtoNr)+ '</AccountId><EveryDayCount>false</EveryDayCount></Accounts>' FROM Zeitkonten WHERE  Formel = 3011
	SELECT @leave = '<Accounts><AccountId>' + CONVERT(VARCHAR(MAX), ZeitKtoNr)+ '</AccountId><EveryDayCount>false</EveryDayCount></Accounts>' FROM Zeitkonten WHERE  Formel = 3010
	SELECT @holiday = '<Accounts><AccountId>' + CONVERT(VARCHAR(MAX), ZeitKtoNr)+ '</AccountId><EveryDayCount>false</EveryDayCount></Accounts>' FROM Zeitkonten WHERE  Formel = 1230

	INSERT INTO TimeAccountsTarifsSettings (timeaccountid, TarifId, LC, UC, LM, UM, XMLSettings)
		SELECT a.ZeitKtoNr, PersoParameterID, GETDATE(), -1, GETDATE(), -1, '<?xml version="1.0" encoding="utf-8"?><CountingDaysAndHoursSettings>'
			+ (CASE WHEN p.TBZUrlKrk <> 0 THEN @sick + @leave ELSE '' END) 
			+ (CASE WHEN p.TBZFt <> 0 THEN @holiday ELSE '' END) +
		'<WorkShifts>MinOneWorkShift</WorkShifts></CountingDaysAndHoursSettings>'
		FROM PersoParameter as p cross join Zeitkonten as a 
		WHERE a.Formel = 1203 AND p.Module = 4  AND  (CAST(a.Settings AS VARCHAR(MAX)) = '<?xml version="1.0" encoding="utf-8"?>  <TBZSettings Version="2" />' OR a.Settings IS NULL ) AND (p.TBZFt <> 0  OR p.TBZUrlKrk <> 0)

END
GO
--#endregion

--#region 20171213 nicht verwendet Spalten löschen
DropColumn 'VorlageDP', 'SGName'
GO
DropColumn 'VorlageDP', 'SGZeiten'
GO
DropColumn 'VorlageDP', 'SGAZ'
GO
DropColumn 'VorlageDP', 'SGSumme'
GO
DropColumn 'VorlageDP', 'SGDatum'
GO
DropColumn 'VorlageDP', 'BrName'
GO
DropColumn 'VorlageDP', 'BrZeiten'
GO
DropColumn 'VorlageDP', 'BrAz'
GO
DropColumn 'VorlageDP', 'BrSumme'
GO
DropColumn 'VorlageDP', 'TextL'
GO
DropColumn 'VorlageDP', 'TextM'
GO
DropColumn 'VorlageDP', 'TextR'
GO
DropColumn 'VorlageDP', 'QFormat'
GO
DropColumn 'VorlageDP', 'Format'
GO
DropColumn 'VorlageDP', 'FtNachweis'
GO
DropColumn 'VorlageDP', 'ZyNachweis'
GO
DropColumn 'VorlageDP', 'Farben'
GO
DropColumn 'VorlageDP', 'GtCr'
GO
DropColumn 'VorlageDP', 'FettName'
GO
DropColumn 'VorlageDP', 'WoUB'
GO
DropColumn 'VorlageDP', 'Frei'
GO
DropColumn 'VorlageDP', 'Zeilen'
GO
DropColumn 'VorlageDP', 'Urlaub'
GO
DropColumn 'VorlageDP', 'FreiFt'
GO
DropColumn 'VorlageDP', 'farbenAZ'
GO
DropColumn 'VorlageDP', 'Morgens'
GO
DropColumn 'VorlageDP', 'Mittag'
GO
DropColumn 'VorlageDP', 'Abends'
GO
DropColumn 'VorlageDP', 'Spalten'
GO
DropColumn 'VorlageDP', 'ZeitLang'
GO
DropColumn 'VorlageDP', 'BrVortrag'
GO
DropColumn 'VorlageDP', 'BrSoll'
GO
DropColumn 'VorlageDP', 'BrSaldo'
GO
DropColumn 'VorlageDP', 'ExportNach'
GO
DropColumn 'VorlageDP', 'keineLeerZeilen'
GO
DropColumn 'VorlageDP', 'Zulagen'
GO
DropColumn 'VorlageDP', 'BrGes'
GO
DropColumn 'VorlageDP', 'SgBem'
GO
DropColumn 'VorlageDP', 'RandL'
GO
DropColumn 'VorlageDP', 'RandR'
GO
DropColumn 'VorlageDP', 'RandO'
GO
DropColumn 'VorlageDP', 'RandU'
GO
DropColumn 'VorlageDP', 'Schrift'
GO
DropColumn 'VorlageDP', 'Printer'
GO
DropColumn 'VorlageDP', 'SchichtProTag'
GO
DropColumn 'VorlageDP', 'Rowheight0'
GO
DropColumn 'VorlageDP', 'Rowheight1'
GO
DropColumn 'VorlageDP', 'AusrichtungNachSchicht'
GO
DropColumn 'VorlageDP', 'ZeitenNachAzAusrichten'
GO
DropColumn 'VorlageDP', 'AuffLayer'
GO
DropColumn 'VorlageDP', 'PrintWorkCellCaption'
GO
DropColumn 'Stücke', 'BallettID'
GO
--#endregion

--#region Spalte Standardtsortierung für Formeln
IF NOT EXISTS (SELECT * FROM sysColumns c 	WHERE c.name = 'SortDefault' AND id = OBJECT_ID(N'dbo.FormulaConfigurations'))
BEGIN
	ALTER TABLE FormulaConfigurations ADD SortDefault SMALLINT NULL
	EXEC ('UPDATE FormulaConfigurations SET SortDefault = FormulaConfigurations.FormulaConfigurationId')
	ALTER TABLE FormulaConfigurations ALTER COLUMN SortDefault SMALLINT NOT NULL 
	ALTER TABLE FormulaConfigurations ADD CONSTRAINT DF_FormulaConfigurations_SortDefault DEFAULT 0 FOR SortDefault
END
GO
--#endregion

--#region LayoutSettings von VorlageDP auf XML umstellen
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('VorlageDP') AND [name] = 'LayoutSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'VorlageDP' ,@columnname = 'LayoutSettings'
END
GO

--#endregion

--#region DH 20171207 Anmerkung für Dienstplaneinträge vergrößert.
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'Anmerkung' and o.id = OBJECT_ID(N'dbo.Dienstplan') and c.prec=250)
	ALTER TABLE dbo.Dienstplan ALTER COLUMN Anmerkung varchar(250) SPARSE NULL
GO
--#endregion

--#region SH 2017-12-20 Neue Anrede für Firmen/Kollektive und entsprechende umstellung von ID 2 auf neue Anrede
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 176 OR (Minor = 176 AND Build < 8)))))
BEGIN
	PRINT('Adding salutation for companies/collectives...')
	DECLARE @ID TABLE (ID INT)

	INSERT INTO Anrede (Anrede, BriefAnrede, AnschriftAnrede, suffix, LM, UM, LC, UC, IsMale)
	OUTPUT INSERTED.Geschlechtid INTO @ID
	VALUES ('Firma/Kollektiv', 'Sehr geehrte Damen und Herren,', '', '', GETDATE(), -1, GETDATE(), -1, NULL);

	DECLARE @companyId INT
	SELECT @companyId = ID FROM @ID
	PRINT('Added salutation has id ' + CAST(@companyId AS VARCHAR) + '...')

	PRINT('Updating companies/collectives to use new salution instead of empty salutation...')
	UPDATE PersH SET Geschlecht = @companyId WHERE Geschlecht = -2 AND PersKatNr IN(SELECT pk.PersKatNr FROM PersKat pk WHERE pk.AdressArt BETWEEN 10 AND 130)
END
GO
--#endregion

--#region SH 2017-12-20 Neue Tabelle für Bühnenattachments
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.StageAttachments') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.StageAttachments (
			StageAttachmentId INT IDENTITY(1,1) NOT NULL,--ID
			StageId INT NOT NULL, 
			AttachmentId INT NOT NULL, 
			Note VARCHAR (255) NULL,
			Sort INT NOT NULL CONSTRAINT DF_StageAttachments_Sort DEFAULT(0),
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_StageAttachments PRIMARY KEY CLUSTERED (StageAttachmentId ASC) ON [PRIMARY]
			CONSTRAINT FK_StageAttachments_Stages FOREIGN KEY (StageId) REFERENCES dbo.ZR (ZRNr),
			CONSTRAINT FK_StageAttachments_Attachments FOREIGN KEY (AttachmentId) REFERENCES dbo.[Attachments] (AttachmentId),
	) ON [PRIMARY]
	--berechtigungen wie bei bühnen
	GRANT SELECT ON dbo.StageAttachments TO [Public]
	GRANT DELETE, INSERT, UPDATE ON dbo.StageAttachments TO DispoAdmin, LibraryAdmin
END
GO
--#endregion

--#region
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'TemplateOwnerGroupId' and o.id = OBJECT_ID(N'dbo.RollenLtg'))
BEGIN
	Print ('Create FK_RoleGroup_Groups')
	ALTER TABLE dbo.RollenLtg ADD TemplateOwnerGroupId INT NULL
	ALTER TABLE dbo.RollenLtg WITH CHECK ADD CONSTRAINT FK_RoleGroup_OwnerGroup FOREIGN KEY(TemplateOwnerGroupId)
	REFERENCES dbo.Gruppe (Gruppeid)
	ALTER TABLE dbo.RollenLtg CHECK CONSTRAINT FK_RoleGroup_OwnerGroup
END
GO
--#endregion
--#region Karenzstunden 
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PayOutBeforeFactor' and o.id = OBJECT_ID(N'dbo.TimeAccountUsage') and c.length=1)
BEGIN
	print 'TimeAccountBehavior'
	IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.DF_TimeAccountUsage_PayOutBeforeFactor'))	ALTER TABLE TimeAccountUsage DROP CONSTRAINT DF_TimeAccountUsage_PayOutBeforeFactor;
	ALTER TABLE TimeAccountUsage ALTER COLUMN PayOutBeforeFactor SMALLINT NOT NULL
	ALTER TABLE TimeAccountUsage ADD CONSTRAINT DF_TimeAccountUsage_PayOutBeforeFactor DEFAULT 0 FOR PayOutBeforeFactor
END
GO
--#endregion Karenzstunden

--#endregion (4.176.x)

--------------------- Ende Änderungsblock --------------------- 
---------------------------------------------------------------
--------------------- RELEASE SECTION -------------------------

--#region ----------- 4.176.x Release Übertrag ----------------

--#region SH 2018-02-05 Nummer von Kostenträger, Kostenstelle, Haushaltstitel und Lohnart auf 15 Zeichen stellen
IF EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = object_id('CostUnit') and c.name = 'CostUnitNo' and c.max_length = 10)
BEGIN
	PRINT 'Settings size of CostUnit.CostUnitNo to 15...'
	ALTER TABLE CostUnit ALTER COLUMN CostUnitNo VARCHAR(15) NOT NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = object_id('CostCenter') and c.name = 'CostCenterNo' and c.max_length = 10)
BEGIN
	PRINT 'Settings size of CostCenter.CostCenterNo to 15...'
	ALTER TABLE CostCenter ALTER COLUMN CostCenterNo VARCHAR(15) NOT NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = object_id('BudgetItem') and c.name = 'BudgetItemNo' and c.max_length = 12)
BEGIN
	PRINT 'Settings size of BudgetItem.BudgetItemNo to 15...'
	ALTER TABLE BudgetItem ALTER COLUMN BudgetItemNo VARCHAR(15) NOT NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = object_id('BudgetItem') and c.name = 'ChapterNumber' and c.max_length = 12)
BEGIN
	PRINT 'Settings size of BudgetItem.ChapterNumber to 15...'
	ALTER TABLE BudgetItem ALTER COLUMN ChapterNumber VARCHAR(15) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = object_id('WageType') and c.name = 'WageTypeNo' and c.max_length = 10)
BEGIN
	PRINT 'Settings size of WageType.WageTypeNo to 15...'
	ALTER TABLE WageType ALTER COLUMN WageTypeNo VARCHAR(15) NULL
END
GO
--#endregion

--#region SH 2018-02-07 Bugfix MergeDoubletten (Tabellen Produktionsplan, Planstellen_Personal, Personal_Instrumente und OrchBesetzung existiert nicht mehr)
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].MergeDoubletten'))
BEGIN
	DROP PROCEDURE dbo.MergeDoubletten 
END
go

CREATE PROCEDURE dbo.MergeDoubletten
	@PersId int, 
	@DoubletteId int
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	UPDATE Besetzungtabelle SET PersNr = @PersId WHERE PersNr = @DoubletteId
	UPDATE BesetzungstdSoli  SET PersNr1 = @PersId WHERE PersNr1=@DoubletteId 
	UPDATE BesetzungstdSoli  SET PersNr2 = @PersId WHERE PersNr2=@DoubletteId
	UPDATE BesetzungstdSoli  SET PersNr3 = @PersId WHERE PersNr3=@DoubletteId 
	UPDATE BesetzungstdSoli  SET PersNr4 = @PersId WHERE PersNr4=@DoubletteId 

	UPDATE StatusZeitR   SET PersNr=@PersId WHERE PersNr=@DoubletteId
	UPDATE Vertrag  SET PersNr=@PersId WHERE PersNr=@DoubletteId
	UPDATE CashCommand  SET PersonId=@PersId WHERE PersonId=@DoubletteId
	UPDATE PersAgentur  SET PersNr=@PersId WHERE PersNr=@DoubletteId
	UPDATE PersAgentur  SET childPersNr=@PersId WHERE childPersNr=@DoubletteId
	DELETE FROM BesRepertoire WHERE PersNr = @DoubletteId AND RolleID IN (SELECT RolleID FROM BesRepertoire WHERE PersNr = @PersId)
	UPDATE BesRepertoire  SET PersNr=@PersId WHERE PersNr=@DoubletteId
	UPDATE PersonalNotizen  SET PersNr=@PersId WHERE PersNr=@DoubletteId
	UPDATE PersZusatzDaten  SET PersNr=@PersId  WHERE PersNr=@DoubletteId
	UPDATE BodyMeasurements  SET PersonId=@PersId  WHERE PersonId=@DoubletteId
	UPDATE PersZusatzDaten  SET PersNr=@PersId  WHERE PersNr=@DoubletteId
	UPDATE Qualification_Person  SET PersonId=@PersId  WHERE PersonId=@DoubletteId
	UPDATE XHDelBasicCast SET PersonNewId=@PersId WHERE PersonNewId=@DoubletteId

	DELETE FROM BankAccount WHERE PersID = @DoubletteId
	DELETE FROM PersonModulGroupPermission WHERE PersonId = @DoubletteId
	DELETE FROM PersKom WHERE PersNr = @DoubletteId
	DELETE FROM PersAdresse WHERE PersNr = @DoubletteId
	--DELETE FROM PersMasse WHERE PersNr = @DoubletteId
	DELETE FROM PersonalDetails WHERE Pnr = @DoubletteId
	DELETE FROM PersonalHonorar WHERE PersNr = @DoubletteId
	DELETE FROM PersEmployee WHERE PersonId = @DoubletteId
	DELETE FROM PersH WHERE PersNr = @DoubletteId
END
GO

GRANT EXECUTE ON MergeDoubletten TO PUBLIC
GO
--#endregion

--#region SH 2018-02-07 Bugfix DeletePersonReference (Tabelle Produktionsplan existiert nicht mehr)

--es gab fehler beim prozedurändern das der view nicht aktuell ist, daher nochmal explizit aktualisieren
EXEC sp_refreshview AbPersonalNotizen_Update
GO

ALTER PROCEDURE [dbo].[DeletePersonReference] (@personId INT, @del INT) AS 
	DECLARE @conflictCounter INT
	SELECT @conflictCounter = 0
	DECLARE @conflictDescription VARCHAR(MAX)
	SELECT @conflictDescription = ''

	DECLARE @Temp INT
	SELECT  @Temp = 0
	DECLARE @CRLF char(2)
	SET @CRLF =  '|'
	SET NOCOUNT On
	/*
	Eingabeparameter: 
	@personId			=> Zu bearbeitendes PersId
	@del			= 0 Nur überprüfen, ob das Löschen der Detaildaten möglich ist / 1 löschen

	Rückgabewerte:

	1. @conflictCounter			=> Anzahl der Tabellen in denen eine Löschung nicht möglich wäre.
	2. @ConflictDescription		=>	Ausgabe der Löschkonflikte
	*/

	if (@del > 0)
	--Rekusiveraufruf beim "echtem löschen mit Check (0)"
	BEGIN
		DECLARE @return_value int
		EXEC @return_value = dbo.DeletePersonReference @personId, 0

		IF (@return_value > 0) 
		BEGIN
			RETURN @return_value
		END
	END

	SELECT @Temp = Besitzer FROM PersH WHERE PersNr = @personId

	IF (dbo.GetCurrentPermission(@Temp,0) <> 2) 
	BEGIN
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'No Owner Permission' + @CRLF
		SELECT @conflictCounter AS ConflictCount,  @conflictDescription AS ConflictDescription
		RETURN @conflictCounter
	END

	/*  Tabelle BesetzungstdSoli */
	IF (SELECT COUNT(*) FROM BesetzungstdSoli WHERE PersNr1 = @personId OR PersNr2 = @personId OR PersNr3 = @personId OR PersNr4 = @personId) > 0
	BEGIN 
		SELECT @conflictCounter=@conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'BasicCast' + @CRLF
	END

	/*  Tabelle Besetzung */
	IF (SELECT COUNT(*) FROM BesetzungTabelle WHERE PersNr = @personId) > 0
	BEGIN 
		SELECT @conflictCounter=@conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Cast' + @CRLF
	END

	/*  Bereich der Tabellen StatusZeitR  */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM StatusZeitR WHERE PersNr = @personId
	IF (SELECT COUNT(*) FROM AbPersStatus_Update WHERE PersNr = @personId) < @Temp 
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Status' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp) > 0
			BEGIN 
				IF (@del > 0) DELETE FROM StatusZeitR WHERE PersNr = @personId
			END
		END

	/*  Tabelle Vertrag  */
	IF (SELECT COUNT(*) FROM Vertrag WHERE PersNr = @personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Contract' + @CRLF
	END
	/*  Tabelle Vertrag  */
	IF (SELECT COUNT(*) FROM VertragDetails WHERE VertragDetails.AgPersNr = @personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Contract (Agency)' + @CRLF
	END

	/* Cashcommand*/
	IF (SELECT COUNT(*) FROM CashCommand WHERE PersonId = @personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'CashCommand' + @CRLF
	END

	IF (SELECT COUNT(*) FROM CashCommand WHERE AgencyId=@personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'CashCommand (Agency)' + @CRLF
	END

	/* PersonalDetails*/
	IF (SELECT COUNT(*) FROM PersonalDetails WHERE HealthInsuranceId=@personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Personal( HealthInsurance)' + @CRLF
	END

	IF (SELECT COUNT(*) FROM PersonalDetails WHERE TaxOfficeId = @personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Personal (TaxOffice)' + @CRLF
	END
	
	/* ------------------------------------Dispositionsbereich ende -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

	IF (@del > 0) DELETE FROM PersonalDetails WHERE Pnr = @personId

	/*  Tabelle PersAgentur  */
	IF  (SELECT PERMISSIONS(OBJECT_ID('PersAgentur'))&2)<>2     /*  Keine Updateberechtingung    */
		BEGIN
			IF (SELECT COUNT(*) FROM PersAgentur WHERE PersNr = @personId) > 0  
			BEGIN 
				SELECT @conflictCounter=@conflictCounter+1
				SELECT @conflictDescription = @conflictDescription + 'Secondary Person' + @CRLF
			END
	
			IF (SELECT COUNT(*) FROM PersAgentur WHERE childPersNr=@personId) > 0  
			BEGIN 
				SELECT @conflictCounter = @conflictCounter + 1
				SELECT @conflictDescription = @conflictDescription + 'Secondary Person' + @CRLF
			END
		END
	ELSE
		BEGIN
			IF (@del > 0) 
			BEGIN
				DELETE FROM PersAgentur WHERE PersNr = @personId
				DELETE FROM PersAgentur WHERE childPersNr = @personId
			END
		END

	/*  Tabelle BesRepertoire  */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM BesRepertoire WHERE PersNr = @personId
	IF (SELECT COUNT(*) FROM RoleQualifications_Update WHERE PersNr = @personId) < @Temp 
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Repertoire' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp) > 0
			BEGIN 
				IF (@del > 0) DELETE FROM BesRepertoire WHERE PersNr = @personId
			END
		END

	/*  Tabelle XHDelBasicCast */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM XHDelBasicCast WHERE PersonOldId = @personId OR PersonNewId = @personId
	IF (SELECT COUNT(*) FROM AbXHDelBasicCast_Update WHERE PersonOldId = @personId OR PersonNewId = @personId) < @Temp
		BEGIN 
			SELECT @conflictCounter=@conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'BasicCastHistory' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp) > 0
			BEGIN 
				IF (@del > 0) DELETE FROM XHDelBasicCast WHERE PersonOldId = @personId OR PersonNewId = @personId
			END
		END

	/*  Tabelle PersonalHonorar  */
	IF  (SELECT PERMISSIONS(OBJECT_ID('PersonalHonorar'))&2)<>2     /*  Keine Updateberechtingung    */
		BEGIN
			IF (SELECT COUNT(*) FROM PersonalHonorar WHERE PersNr = @personId) > 0
			BEGIN 
				SELECT @conflictCounter = @conflictCounter + 1
				SELECT @conflictDescription = @conflictDescription + 'Fee Notes' + @CRLF
			END
		END
	ELSE
		BEGIN
			IF (@del > 0)DELETE FROM PersonalHonorar WHERE PersNr=@personId
		END

/*  Tabelle AbPersonalNotizen_Update  */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersonalNotizen WHERE PersNr = @personId
	IF (SELECT COUNT(*) FROM AbPersonalNotizen_Update WHERE PersNr=@personId) < @Temp 
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Notes' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp) > 0
			BEGIN 
				IF (@del > 0) DELETE FROM PersonalNotizen WHERE PersNr = @personId
			END
		END


	/*  Tabelle ABPersKom_Update  */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersKom WHERE PersNr = @personId
	IF (SELECT COUNT(*) FROM ABPersKom_Update WHERE PersNr = @personId) < @Temp
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Contactdata' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp)>0
			BEGIN 
				IF (@del > 0)DELETE FROM PersKom WHERE PersNr=@personId
			END
		END

	/*  Tabelle ABPersAdresse_Update  */
		SELECT  @Temp = 0
		SELECT @Temp = COUNT(*) FROM PersAdresse WHERE PersNr = @personId
		IF (SELECT COUNT(*) FROM ABPersAdresse_Update WHERE PersNr = @personId) < @Temp
			BEGIN
				SELECT @conflictCounter = @conflictCounter + 1
				SELECT @conflictDescription = @conflictDescription + 'Adressdata' + @CRLF
			END
		ELSE
			BEGIN
				IF(@Temp)>0
				BEGIN 
					IF (@del > 0)DELETE FROM PersAdresse WHERE PersNr=@personId
				END
			END

	/*  Tabelle AbPersZusatzDaten_Update  */
		SELECT  @Temp = 0
		SELECT @Temp = COUNT(*) FROM PersZusatzDaten WHERE PersNr = @personId
		IF (SELECT COUNT(*) FROM AbPersZusatzDaten_Update WHERE PersNr = @personId) < @Temp 
			BEGIN
				SELECT @conflictCounter = @conflictCounter + 1
				SELECT @conflictDescription = @conflictDescription + 'Personal attribute' + @CRLF
			END
		ELSE
			BEGIN
				IF(@Temp) > 0
				BEGIN 
					IF (@del > 0)DELETE FROM PersZusatzDaten WHERE PersNr = @personId
				END
			END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM ResourceObjectBorrows WHERE PersonId = @personId AND EndDate IS NULL
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Open Borrows' + @CRLF
		END

	IF (@del > 0) DELETE FROM ResourceObjectBorrows WHERE PersonId = @personId


	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM CashCommand WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'CashCommand' + @CRLF
		END


	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM CashCommand WHERE AgencyId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'CashCommand (Agency)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM DepartmentCollectives WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'DepartmentCollectives' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM Orders WHERE SupplierId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Orders' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM Orders WHERE SupplierId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Orders (Supplier)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM OrderTravelers WHERE TravelerId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'OrderTravelers' + @CRLF
		END


	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM DienstplanArtenTabelle WHERE HeadOfDepartmentId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Department (HeadOfDepartment)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersonAttachments WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'PersonAttachments' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM WorkCreators WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'WorkCreators' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM WorkVersionRoles_Repertoire WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'WorkVersionRoles_Repertoire (Person)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM WorkVersionRoles_Repertoire WHERE TheaterId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'WorkVersionRoles_Repertoire (TheaterId)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM WorkVersions WHERE PublisherId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'WorkVersions (Publisher)' + @CRLF
		END


	SELECT @conflictCounter AS ConflictCount,  @conflictDescription AS ConflictDescription
	RETURN @conflictCounter
GO
--#endregion

--#region Bugfix SecurityAdmin deletes User DH 20180213
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[FindUsagesOfUserModified]
 @Userid INT
 with EXECUTE AS Owner
  AS
BEGIN

	SET NOCOUNT ON
	DECLARE @table NVARCHAR(250), @field VARCHAR(2)
	CREATE TABLE #Msg(tableName VARCHAR(250),fieldName VARCHAR(2), countUsages int)

	DECLARE fields CURSOR FOR 
		SELECT o.name, c.name FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
		WHERE (c.name = 'UC' OR c.name = 'UM' ) AND o.xtype = 'U' AND  c.xtype = 56 AND o.name <> 'Settings' AND o.name <> 'UpdateLog' ORDER BY 1

	OPEN fields;

	FETCH NEXT FROM fields

	INTO  @table, @field
	WHILE @@FETCH_STATUS = 0
		BEGIN
	
			DECLARE @count INT
			DECLARE @sql NVARCHAR(max)
			SET @sql = N'SELECT @count = COUNT(*) FROM [' + @table  + '] WHERE [' + @field + ']=' +   CONVERT(VARCHAR(20), @Userid) 
	
			EXEC sp_executesql @sql,N'@count int out', @count out
			IF (@count>0) 
			BEGIN
				DECLARE @sql1 NVARCHAR(max)
				SET @sql1 = N'INSERT INTO #Msg (tableName, fieldName, countUsages) VALUES (''' +@table+ ''','''+ @field+''','+   CONVERT(VARCHAR(20), @count)  +')'
				EXEC (@sql1)
			END
			FETCH NEXT FROM fields INTO  @table, @field
		END
	CLOSE fields
	DEALLOCATE fields
	SELECT * FROM #Msg
END
GO

ALTER PROCEDURE [dbo].[DeleteUsagesOfUserModified]
 @Userid   INT
 WITH EXECUTE AS OWNER
  AS 
BEGIN
	SET NOCOUNT ON
	DECLARE @table VARCHAR(250), @field VARCHAR(2)
	DECLARE fields CURSOR FOR 
		SELECT o.name, c.name FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
		WHERE (c.name = 'UC' OR c.name = 'UM' ) AND o.xtype = 'U' AND  c.xtype = 56  

	OPEN fields

	FETCH NEXT FROM fields

	INTO  @table, @field
	WHILE @@FETCH_STATUS = 0
		BEGIN

			EXEC ('UPDATE [' + @table  + '] SET [' + @field + ']=-1 WHERE [' + @field + ']='+ @Userid ) 

			FETCH NEXT FROM fields INTO  @table, @field
	
		END
		
	CLOSE fields
	DEALLOCATE fields
END
GO
--#endregion

--#region TK 20180213/20180219 Bugfix und Varianten nur innerhalb der Variante
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActivityPerformanceNumber') AND xtype = 'IF') DROP Function dbo.GetActivityPerformanceNumber
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActivityPerformanceNumbers')) DROP Function dbo.GetActivityPerformanceNumbers
GO
CREATE FUNCTION dbo.GetActivityPerformanceNumbers(@start DATE, @end DATE)
		RETURNS TABLE
		AS
			RETURN (SELECT Row_Number() OVER (PARTITION BY a.Snr, CASE WHEN [Status] <= 99 THEN 0 ELSE [Status] END ORDER BY Datum, UhrBeg) AS RowNum, AuffNr, Datum
					FROM AufführgTabelle AS A
						INNER JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art
					WHERE KatNr = 0 AND Datum BETWEEN @start AND @end AND  [Status] > 0)
GO
GRANT SELECT ON dbo.GetActivityPerformanceNumbers TO PUBLIC
GO
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActivityPerformanceNumberAllSeason'))	DROP Function dbo.GetActivityPerformanceNumberAllSeason
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActivityPerformanceNumbersAllSeasons'))	DROP Function dbo.GetActivityPerformanceNumbersAllSeasons
GO
CREATE FUNCTION dbo.GetActivityPerformanceNumbersAllSeasons(@start DATE, @end DATE)
		RETURNS TABLE
		AS
			RETURN (SELECT * FROM (SELECT Row_Number() OVER (PARTITION BY a.Snr ORDER BY Datum, UhrBeg)  + ISNULL(pd.AnzahlAuff, 0)  AS RowNum, AuffNr, Datum
					FROM AufführgTabelle AS A
						INNER JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art
						LEFT JOIN StückeDetails AS PD ON Pd.Snr = A.Snr
					WHERE KatNr = 0 AND Datum <= @end AND  [Status] BETWEEN 0 AND 99 ) AS subA WHERE Datum BETWEEN @start AND @end)
GO
GRANT SELECT ON dbo.GetActivityPerformanceNumbersAllSeasons TO PUBLIC
GO
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActivityTypeNumbersRehearsal')) DROP Function dbo.GetActivityTypeNumbersRehearsal
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActivityTypeRehearsalNumbers')) DROP Function dbo.GetActivityTypeRehearsalNumbers
GO
CREATE FUNCTION dbo.GetActivityTypeRehearsalNumbers(@start DATE, @end DATE)
		RETURNS TABLE
		AS
			RETURN (SELECT Row_Number() OVER (PARTITION BY Art, Snr, CASE WHEN [Status] <= 99 THEN 0 ELSE [Status] END ORDER BY Datum, UhrBeg) AS RowNum, AuffNr, Datum
					FROM AufführgTabelle AS A
						INNER JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art 
				WHERE AT.LfdNr = 1 AND Datum BETWEEN @start AND @end AND [Status] > 0)
GO
GRANT SELECT ON dbo.GetActivityTypeRehearsalNumbers TO PUBLIC
GO
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActivityTypeNumbersPerformance'))	DROP Function dbo.GetActivityTypeNumbersPerformance
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActivityTypeNumbersPerformanceByStatus'))	DROP Function dbo.GetActivityTypeNumbersPerformanceByStatus
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActivityTypeNumbersRehearsalByStatus'))	DROP Function dbo.GetActivityTypeNumbersRehearsalByStatus
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActvityTypeNumbersPerformance'))	DROP Function dbo.GetActvityTypeNumbersPerformance
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActvityTypeNumbersRehearsal'))	DROP Function dbo.GetActvityTypeNumbersRehearsal

IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.sp_ProductionActivityCount')) DROP PROCEDURE dbo.sp_ProductionActivityCount
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActivityPerformanceNumber')) DROP PROCEDURE dbo.GetActivityPerformanceNumber
GO
CREATE PROCEDURE dbo.GetActivityPerformanceNumber
	@productionId INT,
	@seasonStart DATE,
	@date DATE,
	@startTime SMALLDATETIME,
	@varianteBaseIndex INT
AS
DECLARE @varianteEndIndex INT
IF (@varianteBaseIndex < 99) SET @varianteBaseIndex = 0
SET @varianteEndIndex = @varianteBaseIndex + 99

		SELECT COUNT(*) AS Anz
		FROM AufführgTabelle AS a
			INNER JOIN AuffTypen AS At ON a.Art = At.AuffTNr
		WHERE a.Snr = @productionId 
		AND At.KatNr = 0
		AND a.[status] BETWEEN @varianteBaseIndex AND @varianteEndIndex
		AND ((a.Datum < @date AND a.Datum >= @seasonStart) OR (a.Datum = @date AND UhrBeg <= @startTime))
	GO
GRANT EXECUTE ON dbo.GetActivityPerformanceNumber TO PUBLIC
GO
--#endregion

--#region Bugfix DeleteOrderpos DH 20180223
IF EXISTS (SELECT * FROM sys.objects s WHERE s.type='Tr' and s.[name]='delete_Orderspos')
BEGIN
	EXEC ('
		Alter Trigger delete_Orderspos ON dbo.orderPos AFTER DELETE 
		AS 
		BEGIN
		DECLARE @Cinfo VARBINARY(128) 
		SELECT @Cinfo = Context_Info() 
		IF @Cinfo = 0x666666 RETURN
		IF EXISTS(SELECT o.Ordernumber FROM deleted INNER JOIN orders o ON deleted.OrderId=o.OrderId WHERE Ordernumber IS NOT NULL) 
		ROLLBACK TRANSACTION
		END')
	Print 'Trigger deleteOrderspos Updated'
END
GO
--#endregion Bugfix DeleteOrderpos

--#region SH 2018-03-15 PersoAdmin Berechtigungen für RepArt geben

GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.RepArt TO PersoAdmin
GO

--#endregion

--#endregion Release Übertrag

---------------------------------------------------------------
--#region ----------- Views aktualisieren ---------------------
Print ('Updating Views...')
DECLARE @SchemaView VARCHAR(100)
DECLARE view_cursor CURSOR FOR
SELECT Name
	FROM 	sysobjects
	WHERE	xtype = 'V'
	ORDER BY Name

OPEN view_cursor
FETCH NEXT FROM view_cursor INTO @SchemaView
WHILE @@FETCH_STATUS = 0
	BEGIN
		PRINT '	' + @SchemaView
		BEGIN TRY
			EXEC sp_refreshview @SchemaView;
		END TRY
		BEGIN CATCH
			declare @error int, @line INT, @severity INT, @state INT, @procedure NVARCHAR(128), @message nvarchar(4000), @xstate int;
			select @error = ERROR_NUMBER(), @line = ERROR_LINE(), @severity = ERROR_SEVERITY(), @state = ERROR_STATE(),
			       @procedure = ERROR_PROCEDURE(), @message = ERROR_MESSAGE(),@xstate = XACT_STATE();
			PRINT('		Refreshing view failed...')
			PRINT('		ERROR #' + CONVERT(VARCHAR, @error) +' Severity '+ CONVERT(VARCHAR, @severity) + ' State ' + CONVERT(VARCHAR, @state))
			PRINT('		XACT_STATE ' + CONVERT(VARCHAR, @xstate))
			PRINT('		Procedure ' + @procedure + ' Line ' + CONVERT(VARCHAR, @line))
			PRINT('		Message ' + @message)

			-- wenn es noch offene transaktionen aus sp_refreshview gibt,
			-- diese rückgängig machen,
			-- da sonst folgefehler bei der nächsten view kommen
			-- tritt bei tests auf sql 2008 auf
			IF @xstate = -1 BEGIN
				PRINT('		Rolling back open transaction...')
				ROLLBACK;
			END

		END CATCH
		FETCH NEXT FROM view_cursor INTO @SchemaView
	END
CLOSE view_cursor
DEALLOCATE view_cursor
GO
--#endregion
---------------------------------------------------------------
--#region ----------- Wegräumen der Hilfsprozeduren -----------
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].DropIndexByTable'))				DROP PROCEDURE dbo.DropIndexByTable
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].DropColumn'))					DROP PROCEDURE dbo.DropColumn 
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].DeleteConstraint'))				DROP PROCEDURE dbo.DeleteConstraint 
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].DropDefault'))					DROP PROCEDURE dbo.DropDefault 
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].DropRoleWithDropRoleMember'))	DROP PROCEDURE dbo.DropRoleWithDropRoleMember 
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].SumToFormula'))					DROP PROCEDURE dbo.SumToFormula 
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].PrepareUniqueColumnIndex'))		DROP PROCEDURE dbo.PrepareUniqueColumnIndex
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].ConvertColumnToXml'))			DROP PROCEDURE dbo.ConvertColumnToXml 
GO
--#endregion
---------------------------------------------------------------
--#region ----------- VERSIONIERUNG ---------------------------

--#region ----------- Version aus ts_evt in TS_DataClass ------
DECLARE @major INT
DECLARE @minor INT
DECLARE @build INT
DECLARE @Datum INT
----------
SET @major = 4
SET @minor = 176
SET @build = 110
SET @Datum = 20180326
--#endregion

--#region ----------- Version setzen ---------------------------
IF NOT EXISTS (SELECT *
				FROM  NvData
				WHERE ByModulScript = 1)
BEGIN
	INSERT INTO NvData (lfdVerNr, ByModulScript)
	VALUES				(1, 1)
END

--Ausführungen des Datenbankskripts werden geloggt.
--Diese haben für ByModulScript den Wert 2
INSERT INTO 
	NVData(
	   [lfdVerNr]
      ,[ByModulScript]
      ,[Major]
      ,[Minor]
      ,[LastDatabaseUpdateDate]
      ,[Build]) 
	SELECT lfdVerNr,2,Major,Minor,LastDataBaseUpdateDate,Build 
	FROM NVData 
	WHERE [ByModulScript]=1;

--Version setzen.
--Diese hat für ByModulScript den Wert 1.
UPDATE NvData
SET
	Major = @major, Minor = @minor, Build = @build, lfdVerNr = @Datum, LastDatabaseUpdateDate = GetDate()
WHERE
	ByModulScript = 1
GO
--#endregion
--#endregion
--#region ----------- NOEXEC OFF ------------------------------
SET NOEXEC OFF
--#endregion