/*
	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 sys.objects 
	 WHERE object_id = OBJECT_ID('dbo.NVData') AND OBJECTPROPERTY(object_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 Berechtigungsprüfung
 if ((SELECT IS_SRVROLEMEMBER('sysadmin'))+(SELECT IS_ROLEMEMBER('db_Owner'))= 0)
 BEGIN
																																															Print ''
																																															Print ''
																																															Print '=================================================================='
		
																																															Print ''
																																															Print '		Keine ausreichenden Berechtigungen auf der Datenbank!!!'	
																																															Print '		Bitte führen Sie das Skript als SysAdmin oder db_owner aus'
																																															Print ''
																																															Print '=================================================================='
																																															Print ''
																																															Print ''	
																																															Print ''
																																															Print ''
																																															RAISERROR('Nicht genügend Berechtigungen!!!', 20, -1) WITH LOG
																																															SET NOEXEC ON
END
GO
--#endregion Berechtigungsprüfung


--#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 184 (letzte Version 2018)
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 184 OR (Minor=184 AND Build < 100)))))
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='		
																																															Print ''
																																															Print '		Der Versionsunterschied ist zu groß!!!'	
																																															Print '		Bitte führen Sie DbScript_2018.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 201
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major > 4 OR (Major = 4 AND (Minor >= 201))))
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='		
																																															Print ''
																																															Print '		Veraltete Skriptversion!!!'	
																																															Print '		Bitte führen Sie DbScript_2020.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 DropIndexByTable
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_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  sys.objects o WHERE o.object_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 DropDefaultConstraint
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'DropDefaultConstraint'))
	DROP PROCEDURE dbo.DropDefaultConstraint 
GO
CREATE PROCEDURE dbo.DropDefaultConstraint
	@tablename varchar(100),
	@columnname varchar(100)
AS
BEGIN
	DECLARE @defname VARCHAR(100)
	DECLARE @cmd VARCHAR(200)

	SELECT @defname = Name
	FROM sys.default_constraints dc
	WHERE	OBJECT_NAME(parent_object_id) = @tablename
	AND		COL_NAME(parent_object_id, parent_column_id) = @columnname
	
	IF (NOT @defname IS NULL)
	BEGIN
			SELECT @cmd='ALTER TABLE '+ @tablename + ' DROP CONSTRAINT ' + @defname
			EXEC (@cmd)
			PRINT @defname + ' dropped'
	END

	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)
		PRINT @columnname + ' unbound'
	END
END
GO
--#endregion

--#region DropColumn
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_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(N'[dbo].[' + @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(N'[dbo].[' + @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

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

IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_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 : 19.10.2018 ---------
--------------------- Datenbankänderungen ab hier -------------
--------------------- möglichst mit regions umschließen -------

--#region ========================================================= DB 2.0 =====================================================
--#region RenameColumn

IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'RenameColumn')) DROP PROCEDURE dbo.RenameColumn 
GO
CREATE PROCEDURE RenameColumn(
	@oldColumnName  VARCHAR(128),
	@newColumnName  VARCHAR(128))
AS
BEGIN
DECLARE @table VARCHAR(128) 
DECLARE cview_cursor CURSOR FOR 
	SELECT o.name AS tab FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = @oldColumnName AND  o.xtype = 'U' 
	
	OPEN cview_cursor 
	FETCH NEXT FROM cview_cursor 
	INTO @table
	WHILE @@FETCH_STATUS = 0
	BEGIN
		
		DECLARE @field VARCHAR(128)
		SET @field = '['+ @table + '].[' + @oldColumnName + ']'
		Print 'Rename ' + @field + ' -> ' + @newColumnName
		EXEC sp_rename  @field, @newColumnName, 'COLUMN'
		
		FETCH NEXT FROM cview_cursor 
		INTO  @table
	END 
CLOSE cview_cursor 
DEALLOCATE cview_cursor 
END
GO
--#endregion
--#region RenameColumnInTable
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'RenameColumnInTable')) DROP PROCEDURE dbo.RenameColumnInTable 
GO

CREATE PROCEDURE RenameColumnInTable(
	@table VARCHAR(128),
	@oldColumnName VARCHAR(128),
	@newColumnName VARCHAR(128))
AS
BEGIN
	DECLARE cview_cursor CURSOR FOR 
	SELECT o.name AS tab FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = @oldColumnName AND  o.xtype = 'U' AND  o.name =  @table 

	OPEN cview_cursor 
	FETCH NEXT FROM cview_cursor 
	INTO @table
	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE @field VARCHAR(128)
		SET @field = '['+ @table + '].[' + @oldColumnName + ']'
		Print 'Rename ' + @field + ' -> ' + @newColumnName
		EXEC sp_rename  @field, @newColumnName, 'COLUMN'
		
		FETCH NEXT FROM cview_cursor 
		INTO  @table
	END 
	CLOSE cview_cursor 
	DEALLOCATE cview_cursor 
END
GO 
--#endregion
--#region RenameTable
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'RenameTable')) DROP PROCEDURE dbo.RenameTable 
GO
CREATE PROCEDURE RenameTable(@oldTableName VARCHAR(128),@newTableName VARCHAR(128))
AS
BEGIN

IF EXISTS(SELECT * FROM sysobjects o WHERE  o.name = @oldTableName  ) 
	BEGIN 
	Print 'Rename ' + @oldTableName + ' -> ' +  @newTableName
		EXEC sp_rename  @oldTableName ,  @newTableName 
	END
END

GO
--#endregion
--#region Delete Table
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.Cast') AND type <> 'U')				DROP VIEW dbo.Cast
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.ABGruppe_Person') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)		DROP TABLE ABGruppe_Person
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.AblagePfade') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)		DROP TABLE AblagePfade
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.DienstplanArtenKopf') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)		DROP TABLE DienstplanArtenKopf
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.ExportFunktion') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)		DROP TABLE ExportFunktion
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.Fehler_Daten') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)		DROP TABLE Fehler_Daten
--IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.HDMZr') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)		DROP TABLE HDMZr
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.ReportTemplate') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)		DROP TABLE ReportTemplate
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.Reminder') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)		DROP TABLE Reminder

--Fehler_Daten,PlanZR,PresseTegfxt,VerteilerFeld
--AnredeInternational, PeriodNotes, Serienbrief
--TODO   Abteilung, Aufgabe PersoParameter,Unterabteilung,Vordruck
--#endregion
--#region Rename

Print '####################### Rename Tables / Columns 2.0 #######################'
GO
DropColumn 'PersAdresse','Gesperrt'
GO
DropColumn 'PersonAddress','Gesperrt'
GO
EXEC RenameColumn 'CollectivPersonId', 'CollectivePersonId'
EXEC RenameColumn 'Plan_Kalender', 'Plan_Calendar'
EXEC RenameTable 'TimeAccountsTarifsSettings', 'TimeAccountTarifSettings'
EXEC RenameColumnInTable 'TimeAccountTarifSettings', 'SettingsId', 'TimeAccountTarifSettingId'

EXEC RenameColumnInTable 'ContractSalaryRules', 'FromPerformanceNumber', 'NumberUnpaid'
EXEC RenameColumnInTable 'ContractDates', 'ContractRoleId', 'ContractEngagementId'
EXEC RenameColumnInTable 'ContractSalaryRules', 'ContractRoleId', 'ContractEngagementId'
EXEC RenameTable 'RoleGroups_ActivityTypes', 'CastRules'
EXEC RenameColumnInTable 'CastRules', 'RoleGroupId', 'RoleTypeId'
EXEC RenameColumnInTable 'RollenLtg', 'GruppeID', 'TemplateJourneyGroupId'
EXEC RenameColumnInTable 'RollenLtg', 'JourneyGroupId', 'TemplateJourneyGroupId'
EXEC RenameColumnInTable 'RoleTypes', 'JourneyGroupId', 'TemplateJourneyGroupId'
EXEC RenameColumn 'RoleGroups_ActivityTypeId', 'CastRuleId'
EXEC RenameColumn 'DokName', 'Filename'
EXEC RenameColumn 'IsNotPublished', 'IsSecret'
EXEC RenameColumn 'StageId', 'LocationId'
IF EXISTS (SELECT * FROM sys.sysobjects dc WHERE dc.name = 'CK_SecondaryPersons_SelfReferencingCheck') ALTER TABLE PersAgentur DROP CONSTRAINT CK_SecondaryPersons_SelfReferencingCheck
EXEC DropColumn 'Settings' ,'Wert'

EXEC RenameTable 'Vorlagen', 'Templates'
IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.Templates') AND o.Name = 'BerichtID') DROP INDEX Templates.BerichtID
EXEC DropColumn 'Templates' ,'BerichtID'
GO
EXEC RenameColumnInTable 'Templates', 'Beschreibung','Description'
EXEC DropColumn 'Plan' ,'Rolle'
EXEC RenameColumnInTable 'Templates', 'VorlagenID', 'TemplateId'
EXEC RenameColumn 'DokName', 'Filename'
EXEC RenameColumn 'OrgBereich', 'RelativePath'

EXEC RenameTable 'GroupSettings', 'OwnerGroupSettings'
EXEC RenameColumnInTable 'OwnerGroupSettings', 'GroupId','OwnerGroupId'
EXEC RenameTable 'Status', 'PersonStatusTypes'

EXEC RenameColumn 'StatusID','PersonStatusTypeId'
EXEC RenameColumnInTable 'PersonStatusTypes', 'Status','Name'
EXEC RenameColumnInTable 'PersonStatusTypes', 'Kurz','Code'
EXEC RenameColumn 'defUhrBeginn','TemplateStartTime'
EXEC RenameColumn 'defUhrEnde','TemplateEndTime'

EXEC RenameTable 'StatusZeitR', 'PersonStatus'
IF EXISTS (SELECT * FROM sys.sysobjects dc WHERE dc.name = 'CK_PersonStatus_PeriodCheck') ALTER TABLE PersonStatus DROP CONSTRAINT CK_PersonStatus_PeriodCheck
IF EXISTS (SELECT * FROM sys.sysobjects dc WHERE dc.name = 'CK_StatusZeitR_Period') ALTER TABLE PersonStatus DROP CONSTRAINT CK_StatusZeitR_Period
EXEC RenameColumn 'StatusZeitRNr','PersonStatusId'
EXEC RenameColumnInTable 'PersonStatus', 'Von','StartDate'
EXEC RenameColumnInTable 'PersonStatus', 'Bis','EndDate'
EXEC RenameColumnInTable 'PersonStatus', 'UhrBeginn','StartTime'
EXEC RenameColumnInTable 'PersonStatus', 'UhrEnde','EndTime'
EXEC RenameColumnInTable 'PersonStatus', 'StatusID','PersonStatusTypeId'
EXEC RenameColumnInTable 'PersonStatus', 'Status','ApprovalStatus'
EXEC RenameColumnInTable 'PersonStatus', 'Bem','Note'

ALTER TABLE PersonStatus WITH CHECK ADD CONSTRAINT CK_PersonStatus_PeriodCheck 
	CHECK ( CASE WHEN StartTime IS NULL THEN StartDate ELSE CAST(StartDate AS DATETIME)+  CAST(StartTime AS DATETIME) END
		<=  CASE WHEN EndTime   IS NULL THEN DATEADD (DAY,1, CAST(EndDate AS DATETIME)) ELSE CAST(EndDate AS DATETIME)+ CAST(EndTime AS DATETIME) END)
ALTER TABLE PersonStatus CHECK CONSTRAINT CK_PersonStatus_PeriodCheck

EXEC RenameColumnInTable 'StückeDetails', 'Bem', 'TextInsteadOfEndTime'
EXEC RenameColumnInTable 'Roles', 'GruppeID', 'JourneyGroupId'
EXEC RenameColumnInTable 'BesetzungStd', 'GruppeID', 'JourneyGroupId'

EXEC RenameColumn 'IsActivityPrivate', 'IsActivitySecret'
EXEC RenameTable 'Ab', 'WorkAreas'
EXEC RenameColumn 'ABId','WorkAreaId'
EXEC RenameColumn 'Bezeichnung','Name'
EXEC RenameColumn 'DienstplanArtenID','DepartmentId'

EXEC RenameTable 'ABGruppe', 'WorkAreaGroups'
EXEC RenameColumn 'ABGruppeId','WorkAreaGroupId'
EXEC RenameColumn 'ABGruppe_AB', 'WorkAreasInWorkAreaGroups'
EXEC RenameColumn 'ABGruppe_ABId','WorkAreasInWorkAreaGroupsId'

EXEC RenameTable 'ABGruppe_AB', 'WorkAreaGroupMembers'
EXEC RenameColumn 'WorkAreasInWorkAreaGroupsId','WorkAreaGroupMemberId'

EXEC RenameTable 'Anrede', 'Salutations'
EXEC RenameColumn 'Anrede', 'Name'
EXEC RenameColumn 'Geschlechtid', 'SalutationId'
EXEC RenameColumn 'BriefAnrede', 'SalutationInOpening'
EXEC RenameColumn 'AnschriftAnrede', 'SalutationInAddress'

EXEC RenameTable 'AuffDienstplanArten', 'ActivityDepartmentData'
EXEC RenameColumn 'AuffDienstplanArtenID','ActivityDepartmentDataId'
EXEC RenameColumn 'DienstplanArtenID','DepartmentId'
EXEC RenameColumn 'AuffNr','ActivityId'
EXEC RenameColumnInTable 'ActivityDepartmentData', 'Farbe', 'BackColor'
EXEC RenameColumnInTable 'ActivityDepartmentData', 'DPBem','Note'

EXEC RenameTable 'AuffTechAufgabe', 'TechnicalJobs'
EXEC RenameColumn 'AuffTechAufgabeID','TechnicalJobId'
EXEC RenameColumn 'ArbeiterAnzahl','PersonCount'
EXEC RenameColumn 'RolleID','RoleId'
EXEC RenameColumnInTable 'TechnicalJobs', 'Beschreibung','Name'
EXEC RenameColumnInTable 'TechnicalJobs', 'Description','Name'


EXEC RenameTable 'AuffTypen', 'ActivityTypes'
EXEC RenameColumn 'AuffTNr','ActivityTypeId'
EXEC RenameColumn 'AuffTKurz','ShortName'
EXEC RenameColumn 'AuffTBez','Name'
EXEC RenameColumn 'WoBez','ShortPrintName'
EXEC RenameColumn 'TagBez','PrintName'
EXEC RenameColumn 'VonzeitDrucken','DefaultPrintStartTime'
EXEC RenameColumn 'BiszeitDrucken','DefaultPrintEndTime'
EXEC RenameColumn 'ProbenZeitMo','DefaultRehearsalStartTimeMorning'
EXEC RenameColumn 'ProbenZeitAb','DefaultRehearsalStartTimeEvening'

EXEC RenameColumn 'ModulGruppeIDWrite','Module'
EXEC RenameColumn 'ModulGruppeIDWrite','NumberActivitiesByProduction'

EXEC RenameTable 'AufführgDetails', 'ActivityDetails'
EXEC RenameColumn 'BesucherSoll','ProjectedVisitors'
EXEC RenameColumn 'BesucherSoll','ActualVisitors'
EXEC RenameColumn 'EinahmenSoll','ProjectedIncome'
EXEC RenameColumn 'EinahmenIST','ActualIncome'
EXEC RenameColumn 'AuffNrExtern','ExternalAcitivityId'
EXEC RenameColumn 'VKStart','SaleStartDate'
EXEC RenameColumn 'VKStatus','SaleStateId'
EXEC RenameColumn 'PreisBem','PriceNote'
EXEC RenameColumn 'PreisBem_en','PriceNote_en'
EXEC RenameColumn 'WebStart','PublishInWebFrom'

EXEC RenameTable 'AufführgTabelle', 'Activities'
EXEC RenameColumn 'SNr','ProductionId'
EXEC RenameColumn 'Datum','Date'
EXEC RenameColumn 'UhrBeg','StartTime'
EXEC RenameColumn 'UhrEnde','EndTime'
EXEC RenameColumn 'ZRNr','LocationId'
EXEC RenameColumn 'Gesperrt','IsSecret'
EXEC RenameColumnInTable 'Settings','SID','SettingId'
EXEC RenameColumnInTable 'Settings','Form','Section'
EXEC RenameColumnInTable 'Settings','Control','KeyName'
EXEC RenameColumnInTable 'Settings','Pref','Context'
EXEC RenameColumnInTable 'Settings','Werttext','DataValue'

EXEC RenameColumnInTable 'Activities','Art','ActivityTypeId'
EXEC RenameColumnInTable 'Activities','Bem','LongNote'
EXEC RenameColumnInTable 'Activities','BemKurz','ArtisticNote'
EXEC RenameColumnInTable 'Activities','BemKurz2','TechnicalNote'
EXEC RenameColumnInTable 'Activities','DiplaDru', 'PrintEndTime'
EXEC RenameColumnInTable 'Activities','VonZeit', 'PrintStartTime'

IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.Activities') AND o.Name = 'IX_Activities_ParentActivityId') DROP INDEX Activities.IX_Activities_ParentActivityId
EXEC RenameColumn 'ZuAuffNr', 'LinkedActivityId'
CREATE NONCLUSTERED INDEX IX_Activities_ParentActivityId ON Activities(LinkedActivityId) WHERE (LinkedActivityId IS NOT NULL) ON [PRIMARY]

EXEC RenameTable 'AufR', 'ActivitySubscriptions'
EXEC RenameColumn 'AufRNr','ActivitySubscriptionId'
EXEC RenameColumn 'AboNr','SubscriptionId' -----------------------
EXEC DropColumn 'ActivitySubscriptions', 'PlAbend'

EXEC RenameTable 'AZTypen', 'ShiftTypes'
EXEC RenameColumn 'AZTNr','ShiftTypeId'
EXEC RenameColumn 'AZTBez','Name'
EXEC RenameColumn 'KurzBez','ShortName'
EXEC RenameColumn 'ZeitKtoNr','TimeAccountId'
EXEC RenameColumnInTable 'ShiftTypes','Farbe','BackColor'
EXEC RenameColumn 'FarbeDruck','PrintBackColor'
EXEC RenameColumn 'aV1','StartTimeDefault1'
EXEC RenameColumn 'aV2','StartTimeDefault2'
EXEC RenameColumn 'aV3','StartTimeDefault3'
EXEC RenameColumn 'aB1','EndTimeDefault1'
EXEC RenameColumn 'aB2','EndTimeDefault2'
EXEC RenameColumn 'aB3','EndTimeDefault3'
EXEC RenameColumn 'inDienstplan','DepartmentId'
EXEC RenameColumn 'DPGruppenID','DepartmentGroupId'
EXEC RenameColumn 'AztBemerkung','Note'
EXEC RenameColumn 'ExportBez','ExportName'
EXEC RenameColumn 'PersID','PersonId'

EXEC RenameTable 'BesetzungStd', 'Roles'
EXEC RenameColumnInTable 'Roles', 'Id', 'RoleId'
EXEC RenameColumnInTable 'Roles', 'Rolle', 'Name'

EXEC RenameColumn 'Besitzer', 'OwnerGroupId'
EXEC RenameColumn 'DruckSteuerung', 'FontFormat'
EXEC RenameColumn 'DruckStd', 'PrintMode'
EXEC RenameColumn 'RolleKurz', 'ShortName'
EXEC RenameColumnInTable 'Roles', 'Anzahl', 'PersonCount'
EXEC RenameColumn 'RollePresse', 'PublishedName'
EXEC RenameColumn 'StarRole', 'IsStarRole'

EXEC RenameTable 'BesetzungTabelle', 'Cast'
EXEC RenameColumnInTable 'Cast', 'Id', 'CastId'
EXEC RenameColumn 'Druck', 'PrintMode'
EXEC RenameColumn 'BesSort', 'GroupPosition'
EXEC RenameColumnInTable 'Cast','BesBem', 'Note'

EXEC RenameTable 'BesRepertoire', 'CastRepertoire'
EXEC RenameColumn 'BesRepertoireID', 'CastRepertoireId'
EXEC RenameColumnInTable 'CastRepertoireId', 'Ort', 'TheaterPersonId'
EXEC RenameColumn 'RepArt', 'RepertoireCategoryId'
EXEC RenameColumn 'LetzteVS', 'LastPerformanceDate'
EXEC RenameColumn 'Sprache', 'LanguageCode'

EXEC RenameTable 'DienstplanArtenTabelle', 'Departments'
EXEC RenameColumn 'DienstplanBez','Name'
EXEC RenameColumn 'DienstplanBezLang','DutyRosterHeaderName'
EXEC RenameColumn 'MAbschluss','LastClosedYearMonth'
EXEC RenameColumn 'Teilung','TimePartitionMinutes'
EXEC RenameColumn 'DPSpalten','VisibleDaysNumber'
EXEC RenameColumn 'DienstProTag','VisibleDaySums'
EXEC RenameColumn 'Zeilen','VisibleColumns'
EXEC RenameColumn 'ModulGruppeID','OwnerGroupId'
EXEC RenameColumn 'TimePartitions','ActivitiesTimePartitions'

EXEC DropColumn 'Departments', 'SumColVisible'
EXEC DropColumn 'Departments', 'Morgens'
EXEC DropColumn 'Departments', 'Mittag'
EXEC DropColumn 'Departments', 'SchriftMorgens'
EXEC DropColumn 'Departments', 'SchriftMittag'
EXEC DropColumn 'Departments', 'SchriftAbends'
EXEC DropColumn 'Departments', 'HintergrundMorgens'
EXEC DropColumn 'Departments', 'HintergrundMittag'
EXEC DropColumn 'Departments', 'HintergrundAbends'
EXEC DropColumn 'Departments', 'SchriftAbends'
EXEC DropColumn 'Departments', 'ZulageOhneAZ'
EXEC DropColumn 'Departments', 'ArchivDatum'
EXEC DropColumn 'Departments', 'EndOfEvening'
EXEC DropColumn 'Departments', 'EndOfNight'
EXEC DropColumn 'Departments', 'NightShiftBackgroundColor'
EXEC DropColumn 'Departments', 'NightShiftForegroundColor'
EXEC DropColumn 'Departments', 'EndOfNight'
EXEC DropColumn 'Departments', 'GroupGuestPerformingStages'

EXEC RenameTable 'DienstplanEintragArt', 'DutyRosterTypes'
EXEC RenameColumn 'DienstplanEintragArtId','DutyRosterTypeId'

EXEC RenameTable 'DienstplanGruppen', 'DepartmentGroups'
EXEC RenameColumn 'DienstplanGruppenID','DepartmentGroupId'
EXEC RenameColumn 'DienstplanGruppenBez','Name'

EXEC RenameTable 'Fahrplan', 'JourneyTimetables'
EXEC RenameColumn 'FahrplanID','JourneyTimetableId'
EXEC RenameColumn 'PersAnz','PersonCount'
EXEC RenameColumnInTable 'JourneyTimetables', 'Gruppe','JourneyGroupId'
EXEC RenameColumn 'RichtungHin','JourneyDirectionIsOutward'
EXEC DropColumn 'JourneyTimetables', 'Tmp'
EXEC RenameColumn 'Diff','OffsetHours'

EXEC RenameTable 'FahrplanGruppen', 'JourneyGroups'
EXEC RenameColumnInTable 'JourneyGroups','GruppeID','JourneyGroupId' 
EXEC RenameColumnInTable 'JourneyGroups','SparteID','JourneyGroupBranchId' 

EXEC RenameColumnInTable 'JourneyGroups', 'GruppeBezKurz','ShortName'
EXEC RenameColumnInTable 'JourneyGroups', 'GruppeBez','Name'

EXEC RenameTable 'FahrplanSparten', 'JourneyGroupBranches'
EXEC RenameColumnInTable 'JourneyGroupBranches','Sparte','Name'
EXEC RenameColumnInTable 'JourneyGroupBranches','SparteID','JourneyGroupBranchId'

EXEC RenameTable 'FahrplanStd', 'JourneyTimetableProductionDefaults'
EXEC RenameColumn 'FahrplanStdID','JourneyTimetableProductionDefaultId'
EXEC RenameColumn 'Snr','ProductionId'--Null
EXEC RenameColumnInTable 'JourneyTimetableProductionDefaults', 'Gruppe','JourneyGroupId'

EXEC RenameTable 'Feiertage', 'Holidays'
EXEC RenameColumn 'FeiertagID','HolidayId'
EXEC RenameColumn 'FDatum','Date'
EXEC RenameColumn 'FtBez','Name'
EXEC RenameColumn 'Ftart','HolidayCategory'
EXEC DropColumn 'BankHolidays', 'Hoch'

EXEC RenameTable 'FeiertageAusg', 'HolidayCompensationRules'
EXEC RenameColumn 'FeiertageAusgID','HolidayCompensationRuleId'
EXEC RenameColumnInTable 'HolidayCompensationRules', 'WT','DayOfWeekCategory' --TINYINT 
EXEC RenameColumnInTable 'HolidayCompensationRules', 'AZA','CompensationHours'
EXEC RenameColumnInTable 'HolidayCompensationRules', 'FF','CompensationDays'

EXEC RenameTable 'Gruppe', 'OwnerGroups'
EXEC RenameColumn 'GruppeID','OwnerGroupId'
EXEC RenameColumn 'GruppeBez','Name'--Null
EXEC RenameColumn 'vDatum','ActivityLockingDate'
EXEC RenameColumn 'WebLockDatum','WebPublishLockingDate'
EXEC RenameColumnInTable 'OwnerGroups', 'GruppeBez','Name'

EXEC RenameTable 'HDM', 'DispoLayoutColumns'
EXEC RenameColumn 'HDMID','DispoLayoutColumnId'
EXEC RenameColumn 'HDMVorlageID','DispoLayoutId'
EXEC RenameColumn 'SpaltenBez','Name'
EXEC RenameColumn 'visible','IsVisible'

EXEC RenameTable 'HDMVorlagen', 'DispoLayouts'
EXEC RenameColumn 'HDMVorlageID','DispoLayoutId'
EXEC RenameColumn 'HDMBez','Name' --Null
EXEC DropColumn 'HDMVorlagen', 'HDMStd'
DELETE FROM DispoLayoutColumns WHERE Name = '!!Werk'

EXEC RenameTable 'HolidayBalanceSet', 'HolidayCompensationRuleSets'
EXEC RenameColumn 'HolidayBalanceSetID','HolidayCompensationRuleSetId'

EXEC RenameTable 'Jahresabschluss', 'YearClosePeriods'
EXEC RenameColumnInTable 'YearClosePeriods', 'Id','YearClosePeriodId'
EXEC RenameColumn 'VonJahrMonat','StartYearMonth'
EXEC RenameColumn 'BisJahrMonat','EndYearMonth'
EXEC RenameColumn 'Abgeschlossen','IsClosed'

EXEC RenameTable 'Kalender', 'Calendar'
EXEC RenameColumnInTable 'Calendar', 'Plan_Kalender','Plan_Calendar'
EXEC RenameColumn 'Kennzeichen','Code'

EXEC RenameTable 'KenntnisDel', 'HistoryConfirmations'
EXEC RenameColumnInTable 'HistoryConfirmations', 'Id','HistoryConfirmationId'
EXEC RenameColumn 'Tabl','TableName'

EXEC RenameTable 'Kosten', 'ProductionCostTypes'
EXEC RenameColumn 'KostenID','ProductionCostTypeId'
EXEC RenameColumn 'KostenBez','Name' --Null
EXEC RenameColumn 'proVst','IsProPerformance' --BIT
EXEC RenameColumn 'KostenArt','IsIncome' --BIT

EXEC RenameTable'Kosten_Aufführg', 'ActivityCosts'
EXEC RenameColumn 'Kosten_AufführgID','ActivityCostId'
EXEC RenameColumnInTable 'ActivityCosts', 'BetragPlan','ProjectedCosts'
EXEC RenameColumnInTable 'ActivityCosts', 'BetragIst','ActualCosts'

EXEC RenameTable 'Kosten_Stück', 'ProductionCosts'
EXEC RenameColumn 'Kosten_AufführgID','ProductionCostsId'
EXEC RenameColumnInTable 'ProductionCosts', 'BetragPlan','ProjectedCosts'
EXEC RenameColumnInTable 'ProductionCosts', 'BetragIst','ActualCosts'
EXEC RenameColumn 'VrId','ContractEngagementId'
EXEC RenameColumn 'Kosten_StückID','ProductionCostId'
EXEC RenameTable 'Land', 'Countries'
EXEC RenameColumn 'LandID','CountryId'
EXEC RenameColumnInTable 'Countries', 'Land','Code'
EXEC RenameColumnInTable 'Countries', 'LandLang','Name'
EXEC DropColumn 'Countries', 'Postformat'

EXEC RenameTable 'PersAdresse', 'PersonAddress'
EXEC RenameColumn 'PersNr','PersonId'
EXEC RenameColumn 'Str','Street'
EXEC RenameColumn 'Plz','PostCode'
EXEC RenameColumn 'Ort','City'
EXEC RenameColumn 'Land','CountryCode'
EXEC RenameColumn 'AdrName','Name'

EXEC RenameTable 'PersDataCategories', 'PersonFields'
EXEC RenameColumn 'PersDataCategoryId','PersonFieldId'
EXEC RenameColumn 'CategoryName','Name'
EXEC RenameColumn 'CategoryCode','Code'

EXEC RenameTable 'PersDataCategoryData', 'PersonFieldData'
EXEC RenameColumn 'PersDataCategoryId','PersonFieldDataIs'

IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.Activities') AND o.Name = 'IX_Activities_ParentActivityId') DROP INDEX Activities.IX_Activities_ParentActivityId
EXEC RenameColumn 'ZuAuffNr', 'LinkedActivityId'
CREATE NONCLUSTERED INDEX IX_Activities_ParentActivityId ON Activities(LinkedActivityId) WHERE (LinkedActivityId IS NOT NULL) ON [PRIMARY]

EXEC RenameTable 'PersAgentur', 'PersonRelations'
EXEC RenameColumn 'PersAgNr','PersonRelationId'
EXEC RenameColumnInTable 'PersonRelations','Schreiben','WriteLetter'
EXEC RenameColumn 'Ansprechpartner','TypeOfRelation'
EXEC RenameColumn 'ChildPersNr','ChildPersonId'
EXEC RenameColumn 'PersNr','PersonId'

IF NOT EXISTS (SELECT * FROM sys.sysobjects dc WHERE dc.name = 'CK_PersonRelations_SelfReferencingCheck') ALTER TABLE PersonRelations  WITH CHECK ADD  CONSTRAINT CK_PersonRelations_SelfReferencingCheck CHECK (ChildPersonId<>PersonId)

EXEC RenameColumn 'Funktion','FunctionName'
EXEC RenameColumn 'AnschiftFunktion','FunctionInAddress'
EXEC RenameColumn 'BriefAnrede','SalutationInOpening'
EXEC RenameColumn 'AdressAnrede','SalutationInAddress'

EXEC RenameTable 'PersH', 'Persons'
EXEC RenameColumn'Suchname', 'KeyName'
EXEC RenameColumn'Vorname', 'FirstName'
EXEC RenameColumn'Nachname', 'LastName'
EXEC RenameColumn'PersKatNr', 'PersonCategoryId'
EXEC RenameColumn'Geschlecht', 'SalutationId'
EXEC RenameColumn'alt', 'IsInactive'
EXEC RenameColumn'VornKurz', 'FirstNameCode'
EXEC RenameColumn'Besitzer', 'OwnerGroupId'
EXEC RenameColumn'Ansprache', 'SalutationInOpening'
EXEC RenameColumn'PTitel', 'AcademicTitle'
EXEC RenameColumn'PrimFirma', 'PreferredAddress'
EXEC RenameColumn'PFunktion', 'FunctionName'

EXEC RenameTable 'PersEmployee', 'PersonEmployee'
EXEC RenameTable 'PersonModulGroupPermission', 'PersonPermissions'
EXEC RenameColumn'PersonModulGroupPermissionId', 'PersonPermissionId'
EXEC RenameColumn'ModulGroupId', 'OwnerGroupId'
EXEC RenameColumn'OwnerId', 'OwnerGroupId'
EXEC RenameTable 'PersKat', 'PersonCategories'
EXEC RenameColumn'PersKat', 'ShortName'
EXEC RenameColumn'PersKatLang', 'Name'
EXEC RenameColumn'AdressArt', 'PersonCategoryType'

EXEC RenameTable'PersKom', 'PersonContactData'
EXEC RenameColumn'PersKomID', 'PersonContactDataId'
EXEC RenameColumn'PersKTypID', 'CommunicationTypeId'

EXEC RenameColumn'Wert', 'DataValue'

EXEC RenameTable 'PersKomTyp', 'CommunicationTypes'

EXEC RenameColumn'KDefault', 'IsDefault'
EXEC RenameColumn'KTyp', 'ComumunicationMedium'

EXEC RenameTable 'PersonalDetails', 'PersonDetails'
EXEC RenameColumn'PNr', 'PersonId'
EXEC RenameColumn'GebDatum', 'DateOfBirth'
EXEC RenameColumn'National', 'Nationality'
EXEC RenameColumn'GebOrt', 'PlaceOfBirth'
EXEC RenameColumn'Finanzamt', 'TaxOfficeNote'
EXEC RenameColumn'SteuerNr', 'TaxNumber'
EXEC RenameColumn'VersicherungsNr', 'SocialSecurityNumber'

EXEC RenameColumn'PassAusAmt', 'PassAuthority'
EXEC RenameColumn'PassAusOrt', 'PassCity'
EXEC RenameColumn'PassNr', 'PassNumber'
EXEC RenameColumn'PassAusDatum', 'PassDateOfIssue'
EXEC RenameColumn'PassAblDatum', 'PassDateOfExpiry'

EXEC RenameColumn'IdentityCardIssuedIn', 'IdentityCardAuthority'
EXEC RenameColumn'IdentityCardNo', 'IdentityCardNumber'
EXEC RenameColumn'IdentityCardIssuedOn', 'IdentityCardDateOfIssue'
EXEC RenameColumn'IdentityCardValidTo', 'IdentityCardDateOfExpiry'

EXEC RenameTable 'PersonalHonorar', 'PersonFeeNotes'
EXEC RenameColumn'MemoVertraulich', 'InternalNote'

EXEC RenameTable 'PersonalNotizen', 'PersonMemo'
EXEC RenameColumn 'PersonalNotizenID', 'PersonMemoId'
EXEC RenameColumn 'NotizTypID', 'PersonMemoTypeId'
EXEC RenameColumn 'Notizen', 'Summary'
EXEC RenameColumn 'Inhalt', 'Body'
--SBid
EXEC RenameTable 'PersonalNotizenTyp', 'PersonMemoTypes'
EXEC RenameColumn 'NotizTypID', 'PersonMemoTypeId'
EXEC RenameColumn 'NotizenArt', 'ComumunicationMedium'

EXEC RenameTable 'PersZusatzDaten', 'PersonAdditionalData'
EXEC RenameColumn 'PersZusatzDatenID', 'PersonAdditionalDataId'
EXEC RenameColumn 'PersZDTypID', 'PersonAdditionalDataTypeId'

EXEC RenameTable 'PersZusatzDatenTyp', 'PersonAdditionalDataTypes'
EXEC RenameColumn 'PersZDTypID', 'PersonAdditionalDataId'


EXEC RenameTable 'Plan', 'PlanLayouts'
EXEC RenameColumn 'PlanID', 'PlanLayoutId'
EXEC RenameColumn 'PlanArt', 'PlanLayoutType'
EXEC RenameColumnInTable 'PlanLayouts', 'Bem','Note'
EXEC RenameTable 'PlanPermissionSettings', 'PlanLayoutPermissions'

EXEC RenameTable 'PlanSort', 'PlanColumnContent'
EXEC RenameColumn 'PlanSortID', 'PlanColumnContentId'
EXEC RenameColumnInTable 'PlanColumnContent', 'SpalteID','PlanColumnId'
EXEC DropColumn 'PlanColumnContent', 'TextID'
EXEC DropColumn 'PlanColumnContent', 'Body'

EXEC RenameTable 'PlanSpalte', 'PlanColumns'
EXEC RenameColumnInTable 'PlanColumns', 'SpalteID','PlanColumnId'
EXEC RenameColumn 'Ausri', 'Alignment'
EXEC RenameColumn 'Ueberschrift', 'ColumnHeader'
EXEC RenameColumn 'ColumHaeder', 'ColumnHeader'
EXEC RenameColumn 'Breite', 'ColumnWidth'
EXEC RenameColumn 'ColumWidth', 'ColumnWidth'
EXEC RenameColumn 'AlleZr', 'NegateLocationFilter'
EXEC DropColumn 'PlanColumns', 'Sparte'
EXEC DropColumn 'PlanColumns', 'UeberschriftArt'
EXEC DropColumn 'PlanColumns', 'SG'
EXEC DropColumn 'PlanColumns', 'Tabulator'
EXEC RenameColumnInTable 'PlanColumns', 'von','TimeOfDayStartFilter'
EXEC RenameColumnInTable 'PlanColumns', 'bis','TimeOfDayEndFilter'

EXEC RenameTable 'Preise', 'PriceCategories'
EXEC RenameColumn 'Kurz','ShortName'
EXEC RenameColumn 'Bez','Name'
EXEC RenameColumn 'PreisNr','PriceCategoryId'

EXEC DropColumn 'PriceCategories', 'Durchschnitt'

EXEC DropColumn 'PersoParameter', 'TBZFt'
EXEC DropColumn 'PersoParameter', 'TBZUrlKrk'
EXEC DropColumn 'PersoParameter', 'Beschaeftigung'

EXEC RenameColumn 'qFormat','IsLandscape'
EXEC RenameColumn 'Rid','RapportId'
EXEC RenameColumnInTable 'Rapport','FreieTage','ShowFreeDays'
EXEC DropColumn 'Rapport', 'Urlaub'

EXEC RenameTable'RapportSpalte', 'RapportColumns'
EXEC RenameColumnInTable 'RapportColumns', 'Ausgabe','TimeAccountId'
EXEC RenameColumnInTable 'RapportColumns', 'Lohnart','HeaderText1'
EXEC RenameColumnInTable 'RapportColumns', 'LohnBez','HeaderText2'
EXEC RenameColumnInTable 'RapportColumns', 'Faktor','Factor'
EXEC RenameColumn 'RSpalteID', 'RapportColumnId'
EXEC RenameColumnInTable 'RapportColumns', 'InAccountID','InOtherTimeAccountId'

EXEC RenameTable 'RepArt', 'RepertoireCategories'
EXEC RenameColumnInTable 'RepertoireCategories', 'Id','RepertoireCategoryId'
EXEC RenameColumn 'Kuerzel','Code'

EXEC RenameTable 'RingBez', 'SubscriptionTypes'
EXEC RenameColumn 'ZuAbo','SubscriptionTypeId'
EXEC RenameColumn 'AboBez','Name'
EXEC RenameColumn 'KurzBez','Code'
EXEC RenameColumn 'AboBezLang','LongName'
EXEC RenameColumnInTable 'SubscriptionTypes', 'Ft','NotOnBankHolidays'
EXEC RenameColumn 'Abend','TimeOfDayRule'
EXEC RenameColumn 'Prem','PremiereRule'
EXEC RenameColumn 'TageD','DaysBetweenRule'
EXEC RenameColumn 'HauptAbo','MainSubscriptionTypeId'

EXEC RenameTable 'Ring', 'Subscriptions'
EXEC RenameColumn 'AboNr','SubscriptionId'
EXEC RenameColumn 'SpZNr','SeasonId'
EXEC RenameColumn 'Pers','PersonCount'

EXEC RenameTable 'RollenLtg', 'RoleTypes'
EXEC RenameColumn 'RollenLtgID','RoleTypeId'
EXEC RenameColumn 'Rolle','Name'
EXEC RenameColumn 'Rolle_en','Name_en'
EXEC RenameColumn 'RolleKurz','ShortName'
EXEC RenameColumn 'TagesplanSpalte','RoleTypeCategory'
EXEC RenameColumnInTable 'RoleTypes', 'DruckStd','TemplatePrintMode'
EXEC RenameColumn 'FixAbId','WorkAreaId'

EXEC RenameTable 'Sparte', 'MainGenres'
EXEC RenameColumn 'SpartenBez','Name'
EXEC RenameColumnInTable 'MainGenres', 'SparteID','MainGenreId'

EXEC RenameTable 'SpielzeitTabelle', 'Seasons'
EXEC RenameColumn 'SpzBez','Name'
EXEC RenameColumn 'SpzStart','StartDate'
EXEC RenameColumn 'SpzEnde','EndDate'
EXEC RenameColumn 'SpzAnzNr','Sort'
EXEC RenameColumn 'SpzStartOrch','OrchestraStartDate'


EXEC DropColumn 'Bonus', 'Art'
EXEC DropColumn 'Bonus', 'StdWert'

EXEC RenameTable 'StückeDetails', 'ProductionDetails'
EXEC RenameColumn 'Komponist', 'Creator'
EXEC RenameColumn 'Sprache', 'LanguageCode'
EXEC RenameColumn 'AnzahlAuff', 'NumberOfPerformancesBefore'
EXEC RenameColumn 'VonDru', 'PublicStartTime'
EXEC RenameColumn 'BisZeit', 'PublicEndTime'
EXEC RenameColumn 'wwwBes', 'PublicCast'
EXEC RenameColumn 'PureTitel', 'PureTitle'


EXEC RenameColumnInTable 'ActivityTypeGroups', 'GroupId', 'OwnerGroupId'
EXEC RenameTable 'Stücke', 'Productions'
EXEC RenameColumn 'Titel', 'Title'
EXEC RenameColumn 'OriginalTitel', 'OriginalTitle'
EXEC RenameColumnInTable 'Productions', 'Dauer', 'DefaultPerformaceDuration'
EXEC RenameColumn 'Begin', 'DefaultPerformaceStartTime'
EXEC RenameColumn 'PremDat', 'PremiereDate'
EXEC RenameColumn 'TypID', 'GenreId'
EXEC RenameColumnInTable 'Productions', 'Sparte', 'DailyScheduleRehearsalSectionId'
EXEC RenameColumn 'Inszenierung', 'Identifier'

EXEC RenameTable 'StückeDienstplan', 'ProductionDeparmentData'
EXEC RenameColumn 'StückeDienstplanID', 'ProductionDeparmentDataId'

EXEC RenameTable 'StückeSPZ', 'ProductionInSeasons'
EXEC RenameColumn 'StückeSPZID', 'ProductionInSeasonID' --Ix
EXEC RenameColumn 'VorstAnz', 'ProjectedPerformanceCount'
EXEC RenameColumn 'ProbAnz', 'ProjectedRehearsalDayCount'

EXEC RenameTable 'StückeTeil', 'ProductionChilds'
EXEC RenameColumn 'StückeTeilID', 'ProductionChildId'
EXEC RenameColumn 'SnrTeil', 'ChildProductionId'

EXEC RenameTable 'TagSparteSort', 'DailyScheduleSections'
EXEC RenameColumnInTable 'DailyScheduleSections', 'ID', 'DailyScheduleSectionId'
EXEC DropColumn 'DailyScheduleSections' ,'Seite'
EXEC DropColumn 'DailyScheduleSections' ,'IsPerformanceSection'
EXEC RenameColumn 'KollDruck', 'CollectiveSection'

EXEC RenameTable 'Typ', 'Genres'
EXEC RenameColumn 'TypBez', 'Name'
EXEC RenameColumnInTable 'Genres', 'SparteID', 'MainGenreId'
EXEC RenameColumn 'Sonderveranstaltung', 'IsSpecialEvent'

EXEC RenameTable 'UrlaubsberechnungsModell', 'EntitlementRuleModels'
EXEC RenameColumn 'UrlaubsberechnungsModellID', 'EntitlementRuleModelId'

EXEC RenameTable 'Urlaubsberechnung', 'EntitlementRules'
EXEC RenameColumn 'UrlaubsberechnungID', 'EntitlementRuleId'
EXEC RenameColumn 'Tage', 'Days'
EXEC RenameColumn 'Jahr', 'FromYear'
EXEC DropColumn 'EntitlementRules' ,'ZeitKtoNr'

EXEC RenameTable 'UserForAccess', 'SeasonPermissions'
EXEC RenameColumn 'UserForAccessID', 'SeasonPermissionId'

EXEC RenameTable 'DistributionLists_Traits', 'MailingListAdditionalDataRules'
EXEC RenameColumn 'DistributionListTraitId', 'MailingListAdditionalDataRuleId'
EXEC RenameColumn 'DistributionListId', 'MailingListId'

EXEC RenameTable 'UserGruppe', 'Permissions'
EXEC RenameColumn 'UserGruppeID', 'PermissionId'
EXEC RenameColumnInTable 'Permissions','Schreiben','HasWritePermission'
EXEC RenameColumn 'BerechtigungsbereichID', 'PermissionArea'

EXEC RenameColumnInTable 'WorkVersionRoles','RoleCategoryId','RoleTypeId'

EXEC RenameTable 'UserPw', 'Users'
--EXEC RenameColumn 'UserName', 'Name'
EXEC RenameColumn 'PriGruppeID', 'PrimaryOwnerGroupId'
EXEC RenameColumn 'AdressId', 'AddressId'
EXEC RenameTable 'Verteiler', 'MailingList'
EXEC RenameColumn 'VerteilerID', 'MailingListId'
EXEC RenameColumn 'VerteilerName', 'Name'
EXEC RenameColumn 'TraitId', 'PersonAdditionalDataTypeId'
EXEC RenameTable 'Vertrag', 'Contracts'
EXEC RenameColumn 'VertragsNr', 'ContractId'
EXEC RenameColumn 'VorlagenID', 'ContractTypeId'
EXEC RenameColumn 'VertragsStatusNr', 'ContractApprovalStatusId'
--AufgabeNr
EXEC RenameColumn 'ExVertragsNr', 'ExternalContractNumber'
EXEC RenameColumn 'Urlaub', 'NonTariffLeaveDays'
EXEC RenameColumn 'vVon', 'StartDate'
EXEC RenameColumn 'vBis', 'EndDate'
EXEC RenameColumn 'ModulGruppeID', 'OwnerGroupId'

EXEC RenameTable 'VertragDetails', 'ContractDetails'
EXEC RenameColumn 'AgentProz', 'AgencyPercentThaeater'
EXEC RenameColumn 'AgentGast', 'AgencyPercentGuest'
EXEC RenameColumn 'Auszahlung' ,'PayType'

EXEC RenameColumn 'AuslaenderSteuer' ,'ForeignerTax'
EXEC RenameColumn 'AgPersNr' ,'AgencyPersonId'
EXEC RenameColumn 'GuestHoliday' ,'GuestLeavedays'

EXEC RenameTable 'VertragPerso', 'ContractDepartments'
EXEC RenameColumn 'ContractPersoId', 'ContractDepartmentId'
EXEC RenameColumn 'PersSort', 'Sort'
EXEC RenameColumn 'StdABGruppeId', 'DefaultWorkAreaGroupId'
EXEC RenameColumnInTable 'ContractDepartments','Start','StartDate'
EXEC RenameColumnInTable 'ContractDepartments','End','EndDate'

EXEC DropColumn 'ContractDepartment' ,'MaxStunden'

EXEC RenameTable 'VertragRolle', 'ContractEngagements'

EXEC DropColumn 'ContractEngagements' ,'AbrechnungProben'
EXEC RenameColumn 'ProbBezahltAnz', 'CompensatedRehearselDays'
EXEC DropColumn 'ContractEngagements' ,'ProbBezahltWert'
EXEC DropColumn 'ContractEngagements' ,'Honorar'
EXEC RenameColumn 'ProbBezahltAnz', 'GuaranteedCompensatedPerformances'
EXEC DropColumn 'ContractEngagements' ,'AbrechnungVs'
EXEC DropColumn 'ContractEngagements' ,'VorstAnzMin'
EXEC DropColumn 'ContractEngagements' ,'VorstAnzVortrag'
EXEC RenameColumn 'vrVon', 'StartDate'
EXEC RenameColumn 'vrBis', 'EndDate'
EXEC DropColumn 'ContractEngagements' ,'ExtraFee'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ContractRole_SalaryLevel') AND type = 'F') ALTER TABLE dbo.ContractEngagements	DROP CONSTRAINT FK_ContractRole_SalaryLevel
EXEC DropColumn 'ContractEngagements' ,'SalaryLevelId'
EXEC DropColumn 'ContractEngagements' ,'CoverFee'
EXEC DropColumn 'ContractEngagements' ,'DayFee'
EXEC DropColumn 'ContractEngagements' ,'OvernightExpensesFlat'
EXEC DropColumn 'ContractEngagements' ,'TravelExpensesFlat'
EXEC DropColumn 'ContractEngagements' ,'FeeComment'
EXEC DropColumn 'ContractEngagements' ,'RehearsalFeeComment'

EXEC RenameTable 'VertragsStatus', 'ContractApprovalStatus'
EXEC RenameColumn 'VertragsStatusNr', 'ContractApprovalStatusId'
EXEC RenameColumn 'VertragsStatusBez', 'Name'
EXEC RenameColumn 'VertragsStatusKurz', 'ShortName'

EXEC RenameTable 'VertragsVorlagen', 'ContractTypes'
EXEC RenameColumn 'VorlagenID', 'ContractTypeId'
EXEC RenameColumn 'VorlgenBez', 'Name'
EXEC RenameColumn 'VArt', 'ContractTypesCategory' --TINYINT
EXEC RenameColumn 'Abgaben', 'Dues'

EXEC RenameTable 'VKStatus', 'SaleStates'
EXEC RenameColumn 'VkStatusNr', 'SaleStateId'
EXEC RenameColumn 'VKStatusBez', 'Name'
EXEC RenameColumn 'VKStatusKurz', 'ShortName'
EXEC RenameColumn 'VKStatusBez_en', 'Name_en'

EXEC RenameTable 'VorlageDP', 'DutyRosterPrintLayouts'
EXEC RenameColumnInTable 'DutyRosterPrintLayouts', 'Id', 'DutyRosterPrintLayoutId'
EXEC RenameColumn 'DPName', 'Name'
EXEC RenameColumn 'VorlageDpId', 'DutyRosterPrintLayoutId'

EXEC RenameTable 'XHDelAufführg', 'ActivityHistory'
EXEC RenameColumnInTable 'ActivityHistory','Art','ActivityTypeId'
EXEC RenameColumnInTable 'ActivityHistory','BemKurz','ArtisticNote'
EXEC DropColumn 'ActivityHistory' ,'Bem'
EXEC DropColumn 'ActivityHistory' ,'BemKurz2'

EXEC RenameTable 'XHDelBasicCast', 'BasicCastHistory'
EXEC RenameTable 'XHDelBesetzung', 'CastHistory'

EXEC RenameColumnInTable 'BasicCastHistory','BesBem', 'CastNote'
EXEC RenameColumnInTable 'BasicCastHistory','Bem','Note'
EXEC RenameColumnInTable 'BasicCastHistory','XHDelBasicCastId','BasicCastHistoryId'

EXEC RenameColumnInTable 'CastHistory','Id','CastId'
EXEC RenameColumnInTable 'CastHistory','Bem','Note'

EXEC RenameTable 'Zeitkonten', 'TimeAccounts'
EXEC RenameColumn 'ZeitKtoNr', 'TimeAccountId'
EXEC RenameColumn 'TimeAccounts' ,'Arbeitszeit'
EXEC RenameColumn 'WoAbrechnung' ,'IsMonthWeekPeriod'
EXEC RenameColumn 'Einheit' ,'Unit'

EXEC RenameTable 'ZeitkontenMonat', 'TimeAccountMonthValues'
EXEC RenameColumn 'zmID', 'TimeAccountMonthValueId'
EXEC RenameColumn 'JahrMonat', 'YearMonth'
EXEC RenameColumn 'Wert', 'DataValue'
EXEC RenameTable 'StageAttachments', 'LocationAttachments'
EXEC RenameColumn 'StageAttachmentId', 'LocationAttachmentId'

EXEC RenameTable 'StageRates', 'LocationRates'
EXEC RenameColumn 'StageRateId', 'LocationRateId'
EXEC RenameTable 'Zr', 'Locations'
EXEC RenameColumn 'ZRBez', 'Name'
EXEC RenameColumn 'zrpl', 'Places'
EXEC RenameColumn 'ZRkurz', 'ShortName'
EXEC RenameColumn 'ZrAbschnitt', 'LocationGroupId'
EXEC RenameColumn 'Fahrt', 'TravelHours'
EXEC RenameColumn 'Gastspiel', 'Locality'
EXEC RenameColumn 'KollisionZrNr', 'NoOverlapCheck'
ALTER TABLE Locations ALTER COLUMN NoOverlapCheck BIT
EXEC RenameColumn 'AdressPersNr', 'PersonId'
EXEC DropColumn 'Locations' ,'Mandant'
EXEC DropColumn 'Locations' ,'Exid'

EXEC RenameTable 'ZrAbschnitte', 'LocationGroups'
EXEC RenameColumn 'ZrAbschnittBem', 'ShortName'
EXEC RenameColumn 'MemoA', 'Name'
EXEC RenameColumn 'MemoB', 'FooterText'
EXEC RenameColumn 'ZrAbschnittID', 'LocationGroupId'

EXEC RenameTable 'Zulagen', 'Bonus'
EXEC RenameColumn 'ZulagenNr', 'BonusId'
EXEC RenameColumn 'ZulagenBez', 'Name'

EXEC RenameColumn 'Einheit', 'UnitText'
EXEC RenameColumn 'ZulagenBezLang', 'LongName'
EXEC RenameColumn 'ZulagenBezKurz', 'Code'
EXEC RenameColumn 'ZeitKtoNr', 'TimeAccountId'
EXEC RenameColumn 'DruckDP', 'PrintInRoster'
EXEC DropColumn 'Bonus', 'Betrag'

EXEC RenameTable 'ZulagenDienstplan', 'BonusDutyRosterData'
EXEC RenameColumn 'ZulagenDienstplanId', 'BonusDutyRosterDataId'
EXEC RenameColumn 'DienstplanID', 'DutyRosterId'

EXEC DropColumn 'BonusInRoster', 'DienstplanArtenId'

EXEC RenameTable 'ZulagenDienstplanArt', 'BonusInDepartments'
EXEC RenameColumn 'ZulagenDienstplanArtId', 'BonusInDepartmentId'
EXEC RenameColumn 'Spalte', 'Sort'

EXEC RenameTable 'Zyklen', 'WorkingTimeModels'
EXEC RenameColumn 'ZyklusNr', 'WorkingTimeModelId'
EXEC RenameColumn 'ZyklusBez', 'Name'

EXEC RenameTable 'ZyklusWochen', 'WorkingTimeModelDays'
EXEC RenameColumn 'ZyklusWoID', 'WorkingTimeModelDayId'
EXEC RenameColumn 'ZyklusTag', 'Day'
EXEC RenameColumn 'AztNr', 'ShiftTypeId'
EXEC DropColumn 'WorkingTimeModelDays', 'ZyklusStatus'

EXEC RenameTable 'ContractPersoWorkingCycles', 'ContractWorkingTimeModels'
EXEC RenameColumn 'ContractPersoWorkingCycleId', 'ContractWorkingTimeModelId'
EXEC RenameColumn 'WorkingCycleId', 'WorkingTimeModelId'
EXEC RenameColumn 'ModuleGroupId', 'OwnerGroupId'


EXEC RenameTable 'BankAccount', 'BankAccounts'
EXEC RenameTable 'BudgetItem', 'BudgetItems'
EXEC RenameTable 'CashCommand', 'CashCommands'

EXEC RenameTable 'CostCenter', 'CostCenters'
EXEC RenameTable 'CostUnit', 'CostUnits'
EXEC RenameTable 'CostUnitProduction', 'CostUnitProductions'
EXEC RenameTable 'CostUnitWorkingTime', 'CostUnitWorkingTimes'
EXEC RenameTable 'CountDown', 'CountDowns'
EXEC RenameColumnInTable 'CountDowns', 'Bemerkung', 'ArtisticNote'

EXEC RenameColumnInTable 'CountDowns', 'BemerkungTechnik', 'TechnicalNote'
EXEC RenameColumnInTable 'CountDowns', 'NoteLong', 'LongNote'
EXEC RenameTable 'CountDownArt', 'CountDownTypes'
EXEC RenameColumn 'CountDownArtID', 'CountDownTypeID'
EXEC RenameColumn 'Bezeichung', 'Name'

EXEC RenameTable 'WageType', 'WageTypes'
EXEC RenameColumn 'Qualification', 'Qualifications'

EXEC RenameTable 'Dienstplan', 'DutyRoster'
EXEC RenameColumn 'V1', 'StartTime1'
EXEC RenameColumn 'B1', 'EndTime1'
EXEC RenameColumn 'V2', 'StartTime2'
EXEC RenameColumn 'B2', 'EndTime2'
EXEC RenameColumn 'V3', 'StartTime3'
EXEC RenameColumn 'B3', 'EndTime3'
EXEC RenameColumn 'AztNr1', 'ShiftTypeId1'
EXEC RenameColumn 'AztNr2', 'ShiftTypeId2'
EXEC RenameColumn 'ShiftType1', 'ShiftTypeId1'
EXEC RenameColumn 'ShiftType2', 'ShiftTypeId2'
EXEC RenameColumnInTable 'DutyRoster', 'Bemerkung', 'ShiftNote1'
EXEC RenameColumn 'Anmerkung', 'Note'
EXEC RenameColumn 'AzBerechnen', 'CalculateTimes'
EXEC RenameColumn 'SollAz', 'DebitWorkingMinutes'
EXEC RenameColumn 'NoPause', 'HasNoBreak'
EXEC RenameColumn 'Az', 'MiscWorkingMinutes'
EXEC RenameColumn 'Az1', 'WorkingMinutes1'
EXEC RenameColumn 'Az2', 'WorkingMinutes2'
EXEC RenameColumn 'Az3', 'WorkingMinutes3'
EXEC RenameColumnInTable 'DutyRoster', 'FT', 'HolidayCount'
EXEC RenameColumnInTable 'DutyRoster', 'CheckHoliday', 'IsHolidayCountManual'
EXEC RenameColumn 'IsPrivate', 'IsSecret'
EXEC RenameColumnInTable 'TimeAccountMonthValues', 'Bem', 'Note'
EXEC RenameColumn 'PersContractId', 'ContractId'
EXEC RenameColumn   'Bemerkung', 'Note'
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Activities_Activities') AND type = 'F') ALTER TABLE Activities DROP CONSTRAINT FK_Activities_Activities
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Contract_Departmentcontract') AND type = 'F') ALTER TABLE ContractDepartments DROP CONSTRAINT FK_Contract_Departmentcontract
GO

UPDATE HistoryConfirmations SET TableName = 'Activities' WHERE TableName = 'Aufführg'
UPDATE HistoryConfirmations SET TableName = 'Cast' WHERE TableName = 'Besetzung'
 DELETE FROM PlanExport WHERE ExportClass IN ('BSO v1.0','Theasoft flex v1.0')
GO
--#endregion

--#region Views

Print '####################### Alter Views 2.0  #######################'
IF EXISTS (SELECT * FROM sys.views WHERE [name]='Spielzeit')	DROP VIEW dbo.Spielzeit
IF EXISTS (SELECT * FROM sys.views WHERE [name]='AbSeasons')	DROP VIEW dbo.AbSeasons
GO

--#region AbSeasons
CREATE VIEW [dbo].[AbSeasons]
AS
SELECT DISTINCT spz.*
FROM  Seasons AS spz 
	LEFT JOIN SeasonPermissions AS us ON spz.SeasonId = us.SeasonId
	LEFT JOIN Users AS pw ON us.userid=pw.userid
WHERE  CURRENT_USER = UserName 
GO

GRANT SELECT ON AbSeasons to Public
GO
--#endregion AbSeasons

--#region AbActivities
ALTER VIEW [dbo].[AbActivities]
AS
	SELECT			act.*, p.Title, p.OwnerGroupId, p.GenreId
	FROM			Activities act
		INNER JOIN	Seasons AS s  ON act.Date <= s.EndDate AND act.Date >= s.StartDate
		INNER JOIN	SeasonPermissions    AS us ON s.SeasonId   = us.SeasonId
		INNER JOIN	Users           AS u  ON us.UserId = u.UserID
		INNER JOIN  Productions			 AS p ON act.ProductionId = p.ProductionId
		LEFT  JOIN  Permissions ug ON p.OwnerGroupId = ug.OwnerGroupId AND U.UserID = ug.UserID AND ug.PermissionArea = 2

	WHERE
		u.UserName  = CURRENT_USER
		AND (act.IsSecret = 0 OR  ug.OptionsFlag IS NULL OR ug.OptionsFlag & 1 = 1)
GO
--#endregion AbActivities

--#region AbActivities_Update
ALTER VIEW dbo.AbActivities_Update
	AS
	SELECT      a.*
	FROM        Activities AS a
	WHERE dbo.IsActivityWritable(a.Date, a.ProductionId, a.ActivityTypeId, a.Status, a.UC) = 1
WITH CHECK OPTION
GO
--#endregion AbActivities_Update

--#region AbActivitiesResourceObjects
ALTER VIEW [dbo].[AbActivitiesResourceObjects]
AS 
SELECT ARO.* FROM Activities_ResourceObjects ARO WHERE ARO.ResourceObjectId IN (
		SELECT  ro.ResourceObjectId FROM ResourceObjects AS ro
		INNER JOIN dbo.Resources AS r ON ro.ResourceId = r.ResourceId
		INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
		INNER JOIN Users AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER AND PermissionArea = 16 
	)
GO
--#endregion AbActivitiesResourceObjects

--#region AbActivitiesResourceObjects_Update
ALTER VIEW [dbo].[AbActivitiesResourceObjects_Update]
AS 
SELECT ARO.* FROM Activities_ResourceObjects ARO WHERE ARO.ResourceObjectId IN (
		SELECT ro.ResourceObjectId FROM dbo.ResourceObjects AS ro
		INNER JOIN Resources r ON r.ResourceId = ro.ResourceId
		INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
		INNER JOIN Users AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER AND PermissionArea = 16 AND Ug.OptionsFlag &1=1)
WITH CHECK OPTION;
GO
--#endregion AbActivitiesResourceObjects_Update

--#region AbActivitiesSubscriptions_Update
ALTER VIEW dbo.AbActivitiesSubscriptions_Update
	AS
	SELECT      *
	FROM       ActivitySubscriptions
	WHERE ActivitySubscriptions.ActivityId IN (SELECT ActivityId FROM Activities AS a WHERE  dbo.IsActivityWritable(a.Date, a.ProductionId, a.ActivityTypeId, a.Status, a.UC) = 1 OR IS_MEMBER('Vorverkauf ändern') = 1)
WITH CHECK OPTION
GO
--#endregion AbActivitiesSubscriptions_Update

--#region AbActivityDetails_Update
ALTER VIEW dbo.AbActivityDetails_Update
	AS
	SELECT      *
	FROM       ActivityDetails AS AD 
	WHERE ad.ActivityId IN (SELECT ActivityId FROM Activities AS a WHERE  dbo.IsActivityWritable(a.Date, a.ProductionId, a.ActivityTypeId, a.Status, a.UC) = 1 OR IS_MEMBER('Vorverkauf ändern') = 1 OR IS_MEMBER('CostsWrite') = 1)
WITH CHECK OPTION
GO
--#endregion AbActivityDetails_Update

--#region AbActivityProductionFieldData_Update
ALTER VIEW [dbo].AbActivityProductionFieldData_Update
AS
	SELECT p.* FROM ActivityProductionFieldData AS p
	WHERE p.ActivityId IN (
		SELECT act.ActivityId FROM Activities AS act
			INNER JOIN Productions AS st ON act.ProductionId = st.ProductionId
			INNER JOIN OwnerGroups AS gr ON st.OwnerGroupId = gr.OwnerGroupId
			INNER JOIN Permissions AS ug ON gr.OwnerGroupId = ug.OwnerGroupId   
			INNER JOIN Users ON Ug.Userid  = Users.Userid 
		WHERE ug.PermissionArea = 2 AND ug.OptionsFlag & 2 = 2 AND Users.Username = CURRENT_USER
	)
WITH CHECK OPTION
GO
--#endregion AbActivityProductionFieldData_Update

--#region AbActivityScenes_Update
ALTER VIEW dbo.AbActivityScenes_Update
	AS
	SELECT     *
	FROM       ActivityScenes
	WHERE ActivityScenes.ActivityId IN (SELECT ActivityId FROM Activities AS a WHERE  dbo.IsActivityWritable(a.Date, a.ProductionId, a.ActivityTypeId, a.Status, a.UC) = 1)
WITH CHECK OPTION
GO
--#endregion AbActivityScenes_Update

--#region AbAuffDienstplanArten
ALTER VIEW [dbo].AbAuffDienstplanArten
AS 
SELECT S.*
	FROM ActivityDepartmentData AS S 
	WHERE S.ActivityDepartmentDataId IN(
		SELECT S.ActivityDepartmentDataId FROM ActivityDepartmentData
		INNER JOIN Departments AS a ON a.DepartmentId = s.DepartmentId 
		INNER JOIN OwnerGroups AS G ON a.OwnerGroupId = G.OwnerGroupId
		INNER JOIN Permissions AS Ug ON G.OwnerGroupId = Ug.OwnerGroupId   
		INNER JOIN Users ON Ug.Userid  = Users.Userid 
		WHERE ug.PermissionArea = 5 AND Users.Username = CURRENT_USER
		)
GO
--#endregion AbAuffDienstplanArten

--#region AbAuffDienstplanArten_Update
ALTER VIEW [dbo].AbAuffDienstplanArten_Update
AS 
SELECT S.*
	FROM ActivityDepartmentData AS S 
	WHERE S.ActivityDepartmentDataId IN(
		SELECT S.ActivityDepartmentDataId FROM ActivityDepartmentData
		INNER JOIN Departments AS a ON a.DepartmentId = s.DepartmentId 
		INNER JOIN OwnerGroups AS G ON a.OwnerGroupId = G.OwnerGroupId
		INNER JOIN Permissions AS Ug ON G.OwnerGroupId = Ug.OwnerGroupId   
		INNER JOIN Users ON Ug.Userid  = Users.Userid 
		WHERE ug.PermissionArea = 5 AND ug.HasWritePermission = 1 AND Users.Username = CURRENT_USER
		)
WITH CHECK OPTION
GO
--#endregion AbAuffDienstplanArten_Update

--#region AbBodyMeasurementData
ALTER VIEW [dbo].AbBodyMeasurementData
AS 
SELECT  bs.*  FROM  BodyMeasurementData  AS bs WHERE Bs.BodyMeasurementId IN
	   (SELECT BodyMeasurements.BodyMeasurementId 
		FROM BodyMeasurements INNER JOIN Persons  ON BodyMeasurements.PersonId=Persons.PersonId
			INNER JOIN Permissions  ON Persons.OwnerGroupId     = Permissions.OwnerGroupId
			INNER JOIN Users        ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 6)
WITH CHECK OPTION
GO
--#endregion AbBodyMeasurementData

--#region AbBodyMeasurements
ALTER VIEW [dbo].AbBodyMeasurements
AS 
SELECT  bs.*  FROM  BodyMeasurements  AS bs WHERE Bs.PersonId IN
	   (SELECT Persons.PersonId 
		FROM Persons 
			INNER JOIN Permissions  ON Persons.OwnerGroupId     = Permissions.OwnerGroupId
			INNER JOIN Users        ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 6)
WITH CHECK OPTION
GO
--#endregion AbBodyMeasurements

--#region AbBudgets
ALTER VIEW [dbo].[AbBudgets]
AS 
--BUDGET SELECT VIEW
SELECT * FROM Budgets WHERE Budgets.CostCenterId IN(
SELECT CostCenterId FROM CostCenter_OwnerGroup AS CCG
INNER JOIN Permissions AS UG ON UG.OwnerGroupId = CCG.OwnerGroupId
INNER JOIN Users AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.PermissionArea IN (12,1))
WITH CHECK OPTION
GO
--#endregion AbBudgets

--#region AbCashCommand
ALTER VIEW [dbo].[AbCashCommand]
AS 
SELECT  cc.*  FROM  CashCommands  AS cc WHERE cc.OwnerGroupId IN
	   (SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7)
WITH CHECK OPTION
GO
--#endregion AbCashCommand

--#region AbCashCommand_Update
ALTER VIEW [dbo].[AbCashCommand_Update]
AS 
SELECT  cc.*  FROM  CashCommands  AS cc WHERE cc.OwnerGroupId IN
	   (SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7
			AND Permissions.HasWritePermission = 1)
WITH CHECK OPTION
GO
--#endregion AbCashCommand_Update

--#region AbCashCommandPos
ALTER VIEW [dbo].[AbCashCommandPos]
AS 
SELECT  ccp.*  FROM  CashCommandPos  AS ccp WHERE ccp.CashCommandId IN
	   (SELECT cc.CashCommandId
		FROM CashCommands AS cc INNER JOIN Permissions ON cc.OwnerGroupId = Permissions.OwnerGroupId 
		INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7)
WITH CHECK OPTION
GO
--#endregion AbCashCommandPos

--#region AbCashCommandPos_Cast_Update
ALTER VIEW [dbo].AbCashCommandPos_Cast_Update
AS 
SELECT  ccpc.*  FROM  CashCommandPos_Cast  AS ccpc WHERE ccpc.CashCommandPosId IN
	   (SELECT CashCommandPos.CashCommandPosId
		FROM CashCommands AS cc INNER JOIN Permissions ON cc.OwnerGroupId = Permissions.OwnerGroupId 
			INNER JOIN Users ON Permissions.Userid = Users.Userid 
			INNER JOIN CashCommandPos ON cc.CashCommandId = CashCommandPos.CashCommandId 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7)
WITH CHECK OPTION
GO
--#endregion AbCashCommandPos_Cast_Update

--#region AbCashCommandPos_ContractDate_Update
ALTER VIEW [dbo].AbCashCommandPos_ContractDate_Update
AS 
SELECT  ccpc.*  FROM  CashCommandPos_ContractDate  AS ccpc WHERE ccpc.CashCommandPosId IN
	   (SELECT CashCommandPos.CashCommandPosId
		FROM CashCommands AS cc INNER JOIN Permissions ON cc.OwnerGroupId = Permissions.OwnerGroupId 
			INNER JOIN Users ON Permissions.Userid = Users.Userid 
			INNER JOIN CashCommandPos ON cc.CashCommandId = CashCommandPos.CashCommandId 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7)
WITH CHECK OPTION
GO
--#endregion AbCashCommandPos_ContractDate_Update

--#region AbCashCommandPos_Update
ALTER VIEW [dbo].[AbCashCommandPos_Update]
AS 
SELECT  ccp.*  FROM  CashCommandPos  AS ccp WHERE ccp.CashCommandId IN
	   (SELECT cc.CashCommandId
		FROM CashCommands AS cc INNER JOIN Permissions ON cc.OwnerGroupId = Permissions.OwnerGroupId 
		INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7
		AND Permissions.HasWritePermission = 1)
WITH CHECK OPTION
GO
--#endregion AbCashCommandPos_Update

--#region AbCashFundPositions
ALTER VIEW [dbo].[AbCashFundPositions]
	AS 
	--CASHFUNDPOSITIONS SELECT VIEW
	SELECT * FROM CashFundPositions WHERE CashFundId IN(
	SELECT CashFundID FROM CashFunds AS CF
	INNER JOIN CostCenter_OwnerGroup AS CCG ON CF.CostCenterId = CCG.CostcenterId
	INNER JOIN Permissions AS UG ON UG.OwnerGroupId = CCG.OwnerGroupId
	INNER JOIN Users AS U ON U.Userid = UG.UserID
	WHERE U.UserName = CURRENT_USER AND UG.PermissionArea = 12
	OR CF.OwnerUserID IN (SELECT UserId FROM Users AS U
	WHERE U.UserName = CURRENT_USER))
	WITH CHECK OPTION
GO
--#endregion AbCashFundPositions

--#region AbCashFundPositions_Update
ALTER VIEW [dbo].[AbCashFundPositions_Update]
AS 
	SELECT * FROM CashFundPositions WHERE CashFundId IN(
		SELECT CashFundID FROM CashFunds AS CF
		INNER JOIN CostCenter_OwnerGroup AS CCG ON CF.CostCenterId = CCG.CostcenterId
		INNER JOIN Permissions AS UG ON UG.OwnerGroupId = CCG.OwnerGroupId
		INNER JOIN Users AS U ON U.Userid = UG.UserID
		WHERE U.UserName = CURRENT_USER AND UG.PermissionArea = 12 AND HasWritePermission = 1)
		WITH CHECK OPTION
GO
--#endregion AbCashFundPositions_Update

--#region AbCashFunds
ALTER VIEW [dbo].[AbCashFunds]
AS  
	SELECT * FROM CashFunds  AS CF WHERE CF.CostCenterId IN(
		SELECT CCG.CostCenterId FROM CostCenter_OwnerGroup AS CCG
		INNER JOIN Permissions AS UG ON UG.OwnerGroupId = CCG.OwnerGroupId
		INNER JOIN Users AS U ON U.Userid = UG.UserID
		WHERE U.UserName = CURRENT_USER AND UG.PermissionArea = 12)
		OR CF.OwnerUserID IN (SELECT UserId FROM Users AS U
		WHERE U.UserName = CURRENT_USER)
		WITH CHECK OPTION
GO
--#endregion AbCashFunds

--#region AbCashFunds_Update
ALTER VIEW [dbo].[AbCashFunds_Update]
AS 
	SELECT * FROM CashFunds  AS CF WHERE CF.CostCenterId IN(
		SELECT CCG.CostCenterId FROM CostCenter_OwnerGroup AS CCG
		INNER JOIN Permissions AS UG ON UG.OwnerGroupId = CCG.OwnerGroupId
		INNER JOIN Users AS U ON U.Userid = UG.UserID
		WHERE U.UserName = CURRENT_USER AND UG.PermissionArea = 12 AND UG.HasWritePermission = 1)
		WITH CHECK OPTION
GO
--#endregion AbCashFunds_Update

--#region AbCast
ALTER VIEW [dbo].[AbCast]
AS
	SELECT	c.*, r.RoleId AS Role_RoleId, r.RoleTypeId AS Role_TaskAreaId, r.RoleCategoryId AS Role_RoleCategoryId,
	        r.OwnerGroupId AS Role_OwnerId, r.PresseSort AS Role_PressSort
	FROM    Cast		AS c 
		INNER JOIN Roles		AS r ON c.RoleId = r.RoleId
		INNER JOIN Permissions AS Ug ON r.OwnerGroupId = Ug.OwnerGroupId   
		INNER JOIN Users ON Ug.Userid  = Users.Userid 
	WHERE (PermissionArea = 4 AND  (c.IsSecret = 0 OR (Ug.OptionsFlag&1 = 1)) AND Users.Username = CURRENT_USER) 
GO
--#endregion AbCast

--#region AbCast_Update
ALTER VIEW [dbo].[AbCast_Update]
AS
	SELECT C.*
	FROM  Cast	AS C 
	WHERE RoleId IN (
		SELECT RoleId FROM Roles		AS Ro
			INNER JOIN OwnerGroups			AS g  ON g.OwnerGroupId = ro.OwnerGroupId	
			INNER JOIN Permissions		AS Ug ON G.OwnerGroupId = Ug.OwnerGroupId   
			INNER JOIN Users				  ON Ug.Userid  = Users.Userid 
		WHERE (PermissionArea = 4 OR PermissionArea = 2) 
				AND  HasWritePermission <> 0 AND Users.Username = CURRENT_USER)
GO
--#endregion AbCast_Update

--#region AbCastActiveties
ALTER VIEW [dbo].[AbCastActiveties]
AS
	SELECT	ac.Date, ac.StartTime, ac.EndTime, ac.ProductionId, ac.LocationId, ac.ActivityTypeId, ac.ArtisticNote, ac.[Status], ca.*,
	        ro.RoleId AS Role_RoleId, ro.RoleTypeId AS Role_TaskAreaId,
	        ro.RoleCategoryId AS Role_RoleCategoryId, ro.OwnerGroupId AS Role_OwnerId, ro.PresseSort AS Role_PressSort, p.IsInactive AS IsInactive, ac.VariantId
	FROM	Activities				AS ac
			INNER JOIN Seasons AS s	ON ac.Date <= s.EndDate AND ac.Date >= s.StartDate
			INNER JOIN SeasonPermissions	AS us	ON s.SeasonId = us.SeasonId
			INNER JOIN Users			AS ua	ON us.UserId = ua.UserID
			INNER JOIN Productions			AS p	ON ac.ProductionId = p.ProductionId
			INNER JOIN Permissions		AS uga	ON p.OwnerGroupId = uga.OwnerGroupId AND ua.UserID = uga.UserID AND uga.PermissionArea = 2
			INNER JOIN Cast	AS ca	ON ac.ActivityId = ca.ActivityId
			INNER JOIN Roles		AS ro	ON ca.RoleId = ro.RoleId
			INNER JOIN Permissions		AS ugc	ON ro.OwnerGroupId = ugc.OwnerGroupId AND ugc.UserID = ua.UserID AND ugc.PermissionArea = 4
	WHERE
			ua.UserName = CURRENT_USER
			AND  (ac.IsSecret = 0 OR uga.OptionsFlag IS NULL OR uga.OptionsFlag & 1 = 1)
			AND ((ca.IsSecret = 0 OR (Ugc.OptionsFlag & 1 = 1)))
GO
--#endregion AbCastActiveties

--#region AbCastBonus
ALTER VIEW [dbo].AbCastBonus
AS
	SELECT   CB.*
		FROM  CastBonus		            AS CB 
			INNER JOIN Cast AS C   ON  cb.CastId = C.CastId
			INNER JOIN Contracts          AS Co  ON c.ContractId = Co.ContractId
			INNER JOIN Permissions       AS Ug  ON Co.OwnerGroupId = Ug.OwnerGroupId   
			INNER JOIN Users           AS UPW ON Ug.Userid  = UPW.Userid 

		WHERE
			Ug.PermissionArea = 1
			AND  (Ug.OptionsFlag&1 = 1)
			AND UPW.Username = CURRENT_USER
	UNION
	SELECT   CB.*
		FROM  CastBonus		            AS CB 
			INNER JOIN Cast AS C   ON  cb.CastId = C.CastId
			INNER JOIN Persons            AS P   ON C.PersonId = P.PersonId
			INNER JOIN Permissions       AS Ug  ON P.OwnerGroupId = Ug.OwnerGroupId   
			INNER JOIN Users           AS UPW ON Ug.Userid  = UPW.Userid 
		WHERE
			c.ContractId IS NULL
			AND Ug.PermissionArea = 1
			AND (Ug.OptionsFlag&1 = 1)
			AND UPW.Username = CURRENT_USER
GO
--#endregion AbCastBonus

--#region AbCastBonus_Update
ALTER VIEW [dbo].AbCastBonus_Update
AS
	SELECT   CB.*
		FROM  CastBonus		AS CB 
		WHERE cb.CastId  IN (
		SELECT c.CastId FROM Cast		AS C 
			INNER JOIN Contracts		AS Co ON c.ContractId = Co.ContractId
			INNER JOIN OwnerGroups           AS g  ON g.OwnerGroupId = Co.OwnerGroupId	
			INNER JOIN Permissions		AS Ug ON G.OwnerGroupId = Ug.OwnerGroupId   
			INNER JOIN Users				  ON Ug.Userid  = Users.Userid 
		WHERE PermissionArea = 1 AND  HasWritePermission <> 0 AND (OptionsFlag&1 = 1) AND Users.Username = CURRENT_USER)
WITH CHECK OPTION
GO
--#endregion AbCastBonus_Update

--#region AbCastCredits
ALTER VIEW dbo.AbCastCredits
AS 
	SELECT CC.*  
	FROM CastCredits AS CC 
		INNER JOIN Contracts AS c ON cc.ContractId = c.ContractId
		INNER JOIN Permissions AS ug ON c.OwnerGroupId = ug.OwnerGroupId
		INNER JOIN Users AS pw ON ug.UserId = pw.UserId
			WHERE Username = CURRENT_USER AND PermissionArea = 4 
GO
--#endregion AbCastCredits

--#region AbCastCredits_Update
ALTER VIEW dbo.AbCastCredits_Update
AS 
	SELECT CC.*  FROM CastCredits AS CC  WHERE CC.ContractId IN 
	(
		SELECT c.ContractId 
		FROM  Contracts AS c 
			INNER JOIN Permissions AS ug ON c.OwnerGroupId = ug.OwnerGroupId
			INNER JOIN Users AS pw ON ug.UserId = pw.UserId
				WHERE Username = CURRENT_USER AND PermissionArea = 4 
	)
WITH CHECK OPTION
GO
--#endregion AbCastCredits_Update

--#region AbCheckListItem
ALTER VIEW [dbo].[AbCheckListItem]
AS 
SELECT  cli.*  FROM  CheckListItem  AS cli WHERE cli.CheckListItemId IN
	   (SELECT S.CheckListItemId
		FROM CheckListItem AS S 
			INNER JOIN Permissions ON S.OwnerGroupId = Permissions.OwnerGroupId 
			INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 17)
WITH CHECK OPTION
GO
--#endregion AbCheckListItem

--#region AbCheckListItem_Update
ALTER VIEW [dbo].[AbCheckListItem_Update]
AS 
SELECT  cli.*  FROM  CheckListItem  AS cli WHERE cli.CheckListItemId IN
	   (SELECT S.CheckListItemId
		FROM CheckListItem AS S 
			INNER JOIN Permissions ON S.OwnerGroupId = Permissions.OwnerGroupId 
			INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 17 AND Permissions.HasWritePermission = 1)
WITH CHECK OPTION
GO
--#endregion AbCheckListItem_Update

--#region AbContract_Qualification_Person_Update
ALTER VIEW [dbo].AbContract_Qualification_Person_Update
AS 
SELECT * FROM Contract_Qualification_Person WHERE ContractId IN (

		SELECT Contracts.ContractId 
							FROM			Permissions 
								INNER JOIN	Users	ON Permissions.Userid = Users.Userid 
								INNER JOIN	Contracts	ON Contracts.OwnerGroupId = Permissions.OwnerGroupId 
							WHERE Username = CURRENT_USER  AND PermissionArea = 1 AND Permissions.HasWritePermission = 1) 
WITH CHECK OPTION
GO
--#endregion AbContract_Qualification_Person_Update

--#region AbContractBonus
ALTER VIEW [dbo].AbContractBonus
AS 
SELECT v.* FROM  ContractBonus AS v WHERE v.ContractId IN (  
	SELECT Contracts.ContractId FROM Contracts
	INNER JOIN  Permissions ON Contracts.OwnerGroupId = Permissions.OwnerGroupId
	INNER JOIN	Users ON Permissions.Userid = Users.Userid 
	WHERE Username = CURRENT_USER AND PermissionArea IN (1, 4, 5) --Contracts, Besetzung, DutyRoster
)
GO
--#endregion AbContractBonus

--#region AbContractBonus_Update
ALTER VIEW [dbo].AbContractBonus_Update
AS 
SELECT v.* FROM  ContractBonus AS v WHERE v.ContractId IN (
	SELECT Contracts.ContractId FROM Contracts
	INNER JOIN  Permissions ON Contracts.OwnerGroupId = Permissions.OwnerGroupId
	INNER JOIN	Users ON Permissions.Userid = Users.Userid 
	WHERE Username = CURRENT_USER AND PermissionArea = 1 AND Permissions.HasWritePermission = 1
)
GO
--#endregion AbContractBonus_Update

--#region AbContractConfirmations
ALTER VIEW [dbo].[AbContractConfirmations]
AS 
SELECT
	cc.*
FROM ContractConfirmations cc
	INNER JOIN Contracts AS v ON cc.ContractId = v.ContractId
	INNER JOIN	(SELECT OwnerGroupId, HasWritePermission
						FROM			Permissions 
						INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
						WHERE Username = CURRENT_USER AND PermissionArea = 1
						AND ( OptionsFlag&1 = 1 OR OptionsFlag & 2 = 2 OR OptionsFlag&4 = 4)) AS UG
				ON v.OwnerGroupId = UG.OwnerGroupId
GO
--#endregion AbContractConfirmations

--#region AbContractConfirmations_Update
ALTER VIEW [dbo].[AbContractConfirmations_Update]
AS 
SELECT
	cc.*
FROM ContractConfirmations cc WHERE cc.ContractId IN (
	SELECT v.ContractId FROM Contracts AS v 
	INNER JOIN	(SELECT OwnerGroupId, HasWritePermission
						FROM			Permissions 
						INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
						WHERE Username = CURRENT_USER AND PermissionArea = 1
						AND ( OptionsFlag&1 = 1)) AS UG
				ON v.OwnerGroupId = UG.OwnerGroupId
WHERE UG.HasWritePermission = 1)
WITH CHECK OPTION
GO
--#endregion AbContractConfirmations_Update

--#region AbContractDateConfirmations
ALTER VIEW [dbo].[AbContractDateConfirmations]
AS 
SELECT
	cdc.*
FROM
	ContractDateConfirmations cdc
	INNER JOIN ContractConfirmations cc ON cdc.ContractConfirmationId = cc.ContractConfirmationId
	INNER JOIN Contracts AS v ON cc.ContractId = v.ContractId
	INNER JOIN	(SELECT OwnerGroupId, HasWritePermission
						FROM			Permissions 
						INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
						WHERE Username = CURRENT_USER AND PermissionArea = 1
						AND ( OptionsFlag&1 = 1 OR OptionsFlag & 2 = 2 OR OptionsFlag&4 = 4)) AS UG
				ON v.OwnerGroupId = UG.OwnerGroupId
GO
--#endregion AbContractDateConfirmations

--#region AbContractDateConfirmations_Update
ALTER VIEW [dbo].[AbContractDateConfirmations_Update]
AS 
SELECT
	cdc.*
FROM ContractDateConfirmations cdc
WHERE cdc.ContractConfirmationId IN (
	SELECT cc.ContractConfirmationId FROM ContractConfirmations cc
	INNER JOIN Contracts AS v ON cc.ContractId = v.ContractId
	INNER JOIN	(SELECT OwnerGroupId, HasWritePermission
						FROM			Permissions 
						INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
						WHERE Username = CURRENT_USER AND PermissionArea = 1
						AND ( OptionsFlag&1 = 1 OR OptionsFlag&4 = 4)) AS UG
				ON v.OwnerGroupId = UG.OwnerGroupId
WHERE UG.HasWritePermission = 1)
WITH CHECK OPTION
GO
--#endregion AbContractDateConfirmations_Update

--#region AbContractDateMaturities
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 ContractEngagements vr ON cd.ContractEngagementId = vr.ContractEngagementId
	INNER JOIN Contracts AS v ON VR.ContractId = v.ContractId  
	INNER JOIN	(SELECT OwnerGroupId, HasWritePermission, (CASE WHEN OptionsFlag & 1 <> 1 THEN 0 ELSE 1 END) AS HasFeesPermission
						FROM			Permissions 
						INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
						WHERE Username = CURRENT_USER AND PermissionArea = 1) AS UG
				ON v.OwnerGroupId = UG.OwnerGroupId
GO
--#endregion AbContractDateMaturities

--#region AbContractDateMaturities_Update
ALTER VIEW [dbo].[AbContractDateMaturities_Update]
AS 
SELECT
	cdm.*
FROM
	ContractDateMaturities cdm
WHERE 
	cdm.ContractDateId IN (
	SELECT cd.ContractDateId FROM
	ContractDates cd
	INNER JOIN ContractEngagements vr ON cd.ContractEngagementId = vr.ContractEngagementId
	INNER JOIN Contracts v ON vr.ContractId = v.ContractId
	INNER JOIN (SELECT DISTINCT OwnerGroupId, HasWritePermission 
						FROM			Permissions 
						INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
						WHERE Username = CURRENT_USER AND PermissionArea = 1 AND (OptionsFlag&1) = 1) AS UG
				ON v.OwnerGroupId = UG.OwnerGroupId
		WHERE UG.HasWritePermission = 1)
GO
--#endregion AbContractDateMaturities_Update

--#region AbContractDates
ALTER VIEW [dbo].[AbContractDates]
AS 
SELECT
	cd.*
FROM  
	ContractDates cd
	INNER JOIN ContractEngagements vr ON cd.ContractEngagementId = vr.ContractEngagementId
	INNER JOIN Contracts v ON vr.ContractId = v.ContractId
	INNER JOIN	(SELECT OwnerGroupId, HasWritePermission
						FROM			Permissions 
						INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
						WHERE Username = CURRENT_USER AND PermissionArea = 1) AS UG
				ON v.OwnerGroupId = UG.OwnerGroupId
GO
--#endregion AbContractDates

--#region AbContractDates_Update
ALTER VIEW dbo.AbContractDates_Update
AS 
	SELECT
		cd.*
	FROM  
		ContractDates cd
	WHERE 
		cd.ContractEngagementId IN (
		SELECT vr.ContractEngagementId FROM ContractEngagements AS vr
			INNER JOIN Contracts v ON vr.ContractId = v.ContractId
			INNER JOIN	(SELECT DISTINCT OwnerGroupId, HasWritePermission 
							FROM			Permissions 
								INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
							WHERE	Username = CURRENT_USER AND 
									PermissionArea = 1 AND 
									((HasWritePermission = 1 AND (OptionsFlag&1) = 1) OR (OptionsFlag&4) = 4)) AS UG
					ON v.OwnerGroupId = UG.OwnerGroupId)
					--Schreibrecht + Honorara lesen oder Contracttracking HasWritePermission
GO
--#endregion AbContractDates_Update

--#region AbContractFields
ALTER VIEW [dbo].AbContractFields
AS 
SELECT * FROM ContractFields WHERE ContractId IN (

		SELECT Contracts.ContractId 
							FROM			Permissions 
								INNER JOIN	Users	ON Permissions.Userid = Users.Userid 
								INNER JOIN	Contracts	ON Contracts.OwnerGroupId = Permissions.OwnerGroupId 
							WHERE Username = CURRENT_USER  AND PermissionArea = 1 ) 
WITH CHECK OPTION
GO
--#endregion AbContractFields

--#region AbContractFields_Update
ALTER VIEW [dbo].AbContractFields_Update
AS 
SELECT * FROM ContractFields WHERE ContractId IN (

		SELECT Contracts.ContractId 
							FROM			Permissions 
								INNER JOIN	Users	ON Permissions.Userid = Users.Userid 
								INNER JOIN	Contracts	ON Contracts.OwnerGroupId = Permissions.OwnerGroupId 
							WHERE Username = CURRENT_USER  AND PermissionArea = 1 AND Permissions.HasWritePermission = 1) 
WITH CHECK OPTION
GO
--#endregion AbContractFields_Update

--#region AbContractPartTimePeriods_Update
ALTER VIEW [dbo].AbContractPartTimePeriods_Update
AS 
SELECT * FROM ContractPartTimePeriods WHERE ContractId IN (

		SELECT Contracts.ContractId 
							FROM			Permissions 
								INNER JOIN	Users	ON Permissions.Userid = Users.Userid 
								INNER JOIN	Contracts	ON Contracts.OwnerGroupId = Permissions.OwnerGroupId 
							WHERE Username = CURRENT_USER  AND PermissionArea = 1 AND Permissions.HasWritePermission = 1) 
WITH CHECK OPTION
GO
--#endregion AbContractPartTimePeriods_Update

--#region AbContractPersoWorkingCycles_Update
ALTER VIEW [dbo].[AbContractPersoWorkingCycles_Update]
AS
	SELECT * FROM ContractWorkingTimeModels WHERE ContractId IN (
		SELECT Contracts.ContractId FROM Permissions 
		INNER JOIN	Users		 ON Permissions.Userid = Users.Userid 
		INNER JOIN	Contracts		 ON Contracts.OwnerGroupId = Permissions.OwnerGroupId 
		WHERE Username = CURRENT_USER  AND PermissionArea IN (1,5) AND Permissions.HasWritePermission = 1) 
WITH CHECK OPTION
GO
--#endregion AbContractPersoWorkingCycles_Update

--#region AbContractSalaryRules
ALTER VIEW dbo.AbContractSalaryRules
AS 
SELECT csr.*
FROM ContractSalaryRules AS csr 
WHERE csr.ContractId IN (
		SELECT  c.ContractId FROM Contracts AS C 
			INNER JOIN Permissions AS ug ON c.OwnerGroupId = ug.OwnerGroupId
			INNER JOIN Users AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER AND ug.PermissionArea = 1 AND ug.OptionsFlag&1 = 1)
GO
--#endregion AbContractSalaryRules

--#region AbContractSalaryRules_Update
ALTER VIEW dbo.AbContractSalaryRules_Update
AS 
SELECT csr.*
FROM ContractSalaryRules AS csr 
WHERE csr.ContractId IN (
		SELECT  c.ContractId FROM Contracts AS C 
			INNER JOIN Permissions AS ug ON c.OwnerGroupId = ug.OwnerGroupId
			INNER JOIN Users AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER AND ug.HasWritePermission = 1 AND ug.PermissionArea = 1 AND ug.OptionsFlag&1 = 1)
		WITH CHECK OPTION
GO
--#endregion AbContractSalaryRules_Update

--#region AbContractTrackings
ALTER VIEW [dbo].[AbContractTrackings]
AS 
SELECT
	ct.*
FROM
	ContractTracking ct
	INNER JOIN ContractConfirmations cc ON ct.ContractConfirmationId = cc.ContractConfirmationId
	INNER JOIN Contracts v ON cc.ContractId = v.ContractId
	INNER JOIN	(SELECT OwnerGroupId, HasWritePermission
						FROM			Permissions 
						INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
						WHERE Username = CURRENT_USER AND PermissionArea = 1 AND
						(OptionsFlag&2 = 2 OR OptionsFlag&4 = 4)) AS UG
				ON v.OwnerGroupId = UG.OwnerGroupId
GO
--#endregion AbContractTrackings

--#region AbContractTrackings_Update
ALTER VIEW [dbo].[AbContractTrackings_Update]
AS 
SELECT
	ct.*
FROM
	ContractTracking ct
WHERE 
	ct.ContractConfirmationId IN (
	SELECT cc.ContractConfirmationId FROM
	ContractConfirmations cc
	INNER JOIN Contracts v ON cc.ContractId = v.ContractId
	INNER JOIN (SELECT DISTINCT OwnerGroupId, HasWritePermission 
						FROM			Permissions 
						INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
						WHERE Username = CURRENT_USER AND PermissionArea = 1 AND
						(OptionsFlag&4) = 4) AS UG
				ON v.OwnerGroupId = UG.OwnerGroupId
		WHERE UG.HasWritePermission = 1)
GO
--#endregion AbContractTrackings_Update

--#region AbDutyCashCommandPos
ALTER VIEW [dbo].[AbDutyCashCommandPos]
AS
	SELECT  ccp.*  FROM  DutyCashCommandPos  AS ccp WHERE ccp.CashCommandId IN
	   (SELECT cc.CashCommandId
		FROM CashCommands AS cc INNER JOIN Permissions ON cc.OwnerGroupId = Permissions.OwnerGroupId 
		INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7)
GO
--#endregion AbDutyCashCommandPos

--#region AbDutyCashCommandPos_Update
ALTER VIEW [dbo].[AbDutyCashCommandPos_Update]
AS
	SELECT  ccp.*  FROM  DutyCashCommandPos  AS ccp WHERE ccp.CashCommandId IN
	   (SELECT cc.CashCommandId
		FROM CashCommands AS cc INNER JOIN Permissions ON cc.OwnerGroupId = Permissions.OwnerGroupId 
		INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7
		AND Permissions.HasWritePermission = 1)
	WITH CHECK OPTION
GO
--#endregion AbDutyCashCommandPos_Update

--#region AbExportProfiles
ALTER VIEW [dbo].[AbExportProfiles]
AS 
SELECT
	ep.*
FROM
	ExportProfiles ep
	INNER JOIN	(
		SELECT OwnerGroupId, HasWritePermission, OptionsFlag FROM Permissions 
		INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
		WHERE Username = CURRENT_USER AND PermissionArea = 14
	) AS UG ON ep.OwnerGroupId = UG.OwnerGroupId AND (ep.ExportArea & UG.OptionsFlag) <> 0
GO
--#endregion AbExportProfiles

----#region AbXHDelBasicCast
--ALTER VIEW dbo.AbXHDelBasicCast
--	AS
--	SELECT * FROM BasicCastHistory WHERE BasicCastId IN (SELECT BasicCastId FROM AbBasicCast)
--GO
----#endregion AbXHDelBasicCast

----#region AbXHDelBasicCast_Update
--ALTER VIEW dbo.AbXHDelBasicCast_Update
--	AS
--	SELECT * FROM BasicCastHistory WHERE BasicCastId IN (SELECT BasicCastId FROM AbBasicCast_Update)
--WITH CHECK OPTION
--GO
----#endregion AbXHDelBasicCast_Update

--#endregion

--2017-01-26 tk
--#region In AbExportProfiles_Update konnten kein Deletes ausgeführt werden
ALTER VIEW [dbo].[AbExportProfiles_Update]
AS 
	SELECT 	ep.*
	FROM ExportProfiles AS ep  
	WHERE ep.OwnerGroupId IN 
		   (SELECT OwnerGroupId 
			FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
			WHERE Username = CURRENT_USER AND PermissionArea = 14 AND HasWritePermission = 1 AND (ep.ExportArea & OptionsFlag) <> 0) 	


GO

ALTER VIEW [dbo].[ABGroupSettings]
		AS
	SELECT	OwnerGroupSettings.*
	FROM	OwnerGroupSettings
	WHERE EXISTS (
			SELECT * FROM OwnerGroupSettings AS R
					INNER JOIN OwnerGroups AS G ON R.OwnerGroupId  = G.OwnerGroupId
					INNER JOIN Permissions AS Ug ON G.OwnerGroupId = Ug.OwnerGroupId   
					INNER JOIN Users ON Ug.Userid  = Users.Userid 
					WHERE ug.PermissionArea = 11 AND Users.Username = CURRENT_USER  AND R.GroupSettingId = OwnerGroupSettings.GroupSettingId)

GO
ALTER VIEW [dbo].[ABGroupSettings_Update]
		AS
	SELECT	OwnerGroupSettings.*
	FROM	OwnerGroupSettings
	WHERE EXISTS (
			SELECT * FROM OwnerGroupSettings AS R
					INNER JOIN OwnerGroups AS G ON R.OwnerGroupId  = G.OwnerGroupId
					INNER JOIN Permissions AS Ug ON G.OwnerGroupId = Ug.OwnerGroupId   
					INNER JOIN Users ON Ug.Userid  = Users.Userid 
					WHERE ug.PermissionArea = 11 AND ug.HasWritePermission = 1  AND Users.Username = CURRENT_USER  AND R.GroupSettingId = OwnerGroupSettings.GroupSettingId ) 
WITH CHECK OPTION

GO

ALTER VIEW [dbo].[AbJahresabschluss_Update]
AS
	SELECT j.* FROM YearClosePeriods AS j WHERE j.DepartmentId IN (
		SELECT dpa.DepartmentId FROM Departments AS dpa
	INNER JOIN Permissions AS ug ON dpa.OwnerGroupId = ug.OwnerGroupId
	INNER JOIN Users AS u ON ug.UserID = u.UserID
	WHERE u.UserName = CURRENT_USER AND ug.PermissionArea = 5 AND ug.OptionsFlag & 2 = 2
	)
	WITH CHECK OPTION

GO
ALTER VIEW dbo.AbJourneyTimetabl_Update
	AS
	SELECT      *
	FROM       JourneyTimetables AS AD 
	WHERE ad.ActivityId IN (SELECT ActivityId FROM Activities AS a WHERE  dbo.IsActivityWritable(a.Date, a.ProductionId, a.ActivityTypeId, a.Status, a.UC) = 1)

	WITH CHECK OPTION

GO
--ORDERPOSITIONS SELECT VIEW
ALTER VIEW [dbo].[AbOrderPositions]
AS 
SELECT * FROM OrderPos  AS OP WHERE OP.OrderId IN(
SELECT OrderId FROM Orders AS O
INNER JOIN CostCenter_OwnerGroup AS CCG ON O.CostCenterId = CCG.CostCenterId
INNER JOIN Permissions AS UG ON UG.OwnerGroupId = CCG.OwnerGroupId
INNER JOIN Users AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.PermissionArea = 12)
OR OP.OrderId IN (
SELECT O.OrderID FROM Orders AS O
INNER JOIN  CashFunds AS CF ON CF.CashFundId = O.CashFundId
INNER JOIN Users AS U ON U.Userid = CF.OwnerUserID
WHERE U.UserName = CURRENT_USER)
WITH CHECK OPTION

GO
--ORDERPOSITIONS UPDATE VIEW
ALTER VIEW [dbo].[AbOrderPositions_Update]
AS 
SELECT * FROM OrderPos  AS OP WHERE OP.OrderId IN(
SELECT OrderId FROM Orders AS O
INNER JOIN CostCenter_OwnerGroup AS CCG ON O.CostCenterId = CCG.CostCenterId
INNER JOIN Permissions AS UG ON UG.OwnerGroupId = CCG.OwnerGroupId
INNER JOIN Users AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.PermissionArea = 12 AND UG.HasWritePermission = 1)
OR OP.OrderId IN (
SELECT O.OrderID FROM Orders AS O
INNER JOIN  CashFunds AS CF ON CF.CashFundId = O.CashFundId
INNER JOIN Users AS U ON U.Userid = CF.OwnerUserID
WHERE U.UserName = CURRENT_USER)
WITH CHECK OPTION

GO
--ORDERS SELECT VIEW
ALTER VIEW [dbo].[AbOrders]
AS 
SELECT * FROM Orders  AS O WHERE O.CostCenterId IN(
SELECT CCG.CostCenterId FROM CostCenter_OwnerGroup AS CCG
INNER JOIN Permissions AS UG ON UG.OwnerGroupId = CCG.OwnerGroupId
INNER JOIN Users AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.PermissionArea = 12)
OR O.CashFundId IN (
SELECT CF.CashFundId FROM CashFunds AS CF INNER JOIN Users AS U ON U.Userid = CF.OwnerUserID
WHERE U.UserName = CURRENT_USER)
WITH CHECK OPTION


GO
ALTER VIEW [dbo].[AbOrders_Update]
AS 
--ORDERS UPDATE VIEW
SELECT * FROM Orders  AS O WHERE O.CostCenterId IN(
SELECT CCG.CostCenterId FROM CostCenter_OwnerGroup AS CCG
INNER JOIN Permissions AS UG ON UG.OwnerGroupId = CCG.OwnerGroupId
INNER JOIN Users AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.PermissionArea = 12 AND UG.HasWritePermission = 1)
OR O.CashFundId IN (
SELECT CF.CashFundId FROM CashFunds AS CF INNER JOIN Users AS U ON U.Userid = CF.OwnerUserID
WHERE U.UserName = CURRENT_USER)
WITH CHECK OPTION

GO
		
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbPersAdressKom'))			DROP VIEW dbo.AbPersAdressKom
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbPressetext'))			DROP VIEW dbo.AbPressetext
GO

ALTER VIEW [dbo].[AbPersonAttachments]
AS 

SELECT pa.* FROM PersonAttachments pa 
WHERE pa.PublicPermission = 1
OR pa.PublicPermission = 2
OR (
	pa.PublicPermission = 0
	AND pa.OwnerGroupId IN (
		SELECT OwnerGroupId FROM Permissions AS UG 
		INNER JOIN Users AS U ON U.Userid = UG.UserID
		WHERE U.UserName = CURRENT_USER AND UG.PermissionArea = 13
	)
) 
WITH CHECK OPTION

GO
ALTER VIEW [dbo].[AbPersonAttachments_Update]
AS 
--PersonAttachments UPDATE VIEW
SELECT * FROM PersonAttachments WHERE PersonAttachments.OwnerGroupId IN(
SELECT OwnerGroupId FROM Permissions AS UG 
INNER JOIN Users AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.PermissionArea = 13 AND UG.HasWritePermission = 1)
WITH CHECK OPTION

GO

ALTER VIEW [dbo].[AbPersP]
AS
SELECT PersonId, InWeb, MemoExtern_en, MemoExtern, UM, LM, LC, UC
FROM PersonDetails

GO
ALTER VIEW [dbo].[AbPersStatus]
AS 
SELECT PersonStatusId,
	CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN sr.PersonStatusTypeId ELSE -1 END AS PersonStatusTypeId,
	CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN sr.Note  ELSE NULL END AS Note,
	CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN st.TimeAccountId  ELSE -1 END AS TimeAccountId,

	CASE WHEN z.Formel IN (1, 2) THEN 2  WHEN z.Formel = 4050 THEN 4 ELSE 1 END AS AvailableStatus,
	CASE WHEN NOT st.TemplateStartTime IS NULL OR NOT st.TemplateEndTime IS NULL THEN 1  ELSE 0 END AS IsHalfDayType,
	sr.ApprovalStatus, sr.PersonId, ContractId, StartDate, EndDate, StartTime, EndTime, ManualDayCount, DateOfRequest, sr.LM, sr.UM, sr.LC, sr.UC,
	p.KeyName, p.OwnerGroupId, p.PersonCategoryId
FROM PersonStatus AS sr
	INNER JOIN Persons AS p ON sr.PersonId = p.PersonId 
	INNER JOIN PersonStatusTypes AS st ON sr.PersonStatusTypeId = st.PersonStatusTypeId 
	INNER JOIN TimeAccounts AS z ON st.TimeAccountId = z.TimeAccountId
	INNER JOIN Permissions AS ug ON p.OwnerGroupId = ug.OwnerGroupId
	INNER JOIN Users ON ug.Userid = Users.Userid
WHERE Users.Username = CURRENT_USER AND PermissionArea = 8 

GO
ALTER VIEW [dbo].AbPersStatus_Update
AS 
SELECT  sr.*  FROM  PersonStatus  AS sr  WHERE sr.PersonId IN
	   (SELECT p.PersonId
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid INNER JOIN Persons AS p ON Permissions.OwnerGroupId = p.OwnerGroupId
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 8 AND Permissions.HasWritePermission=1)
WITH CHECK OPTION

GO

--Alle nicht gesperrten und alle Kontakte auf die min. Kontaktdaten lesen
ALTER VIEW [dbo].[AbPersZusatzDaten]
AS 
SELECT PersonAdditionalDataId, zd.PersonId, zd.PersonAdditionalDataTypeId, zd.ParentPersZusatzDatenId, zd.ZDText, zd.ZDInt, zd.ZDDate, zd.LM, zd.UM, zd.LC, zd.UC 
FROM			PersonAdditionalData				AS zd 
WHERE zd.PersonAdditionalDataId  IN 
		(SELECT PersonAdditionalDataId FROM PersonAdditionalData
			INNER JOIN	PersonAdditionalDataTypes			AS zdt	ON zd.PersonAdditionalDataTypeId = zdt.PersonAdditionalDataTypeId
			LEFT  JOIN	PersonPermissions	AS gp	ON zd.PersonId = gp.PersonId
			INNER JOIN  Permissions					AS ug	ON zdt.OwnerGroupId = ug.OwnerGroupId
			INNER JOIN	Users								ON ug.Userid = Users.Userid 
		WHERE 
			zdt.IsSecret = 0 OR 
			(ug.PermissionArea = 0 AND Users.Username = current_user))

GO
--Alle mit Schreibrecht	
ALTER VIEW [dbo].[AbPersZusatzDaten_Update]
AS 		
SELECT zd.PersonAdditionalDataId, zd.PersonId, zd.PersonAdditionalDataTypeId, zd.ParentPersZusatzDatenId, zd.ZDText, zd.ZDInt, zd.ZDDate, zd.LM, zd.UM, zd.LC, zd.UC 
FROM			PersonAdditionalData				AS zd 
WHERE zd.PersonAdditionalDataId  IN 
		(SELECT PersonAdditionalDataId FROM PersonAdditionalData
			INNER JOIN	PersonAdditionalDataTypes			AS zdt	ON zd.PersonAdditionalDataTypeId = zdt.PersonAdditionalDataTypeId
			LEFT  JOIN	PersonPermissions	AS gp	ON zd.PersonId = gp.PersonId
			INNER JOIN  Permissions					AS ug	ON zdt.OwnerGroupId = ug.OwnerGroupId
			INNER JOIN	Users								ON ug.Userid = Users.Userid 
		WHERE 
			ug.PermissionArea = 0 AND Users.Username = current_user AND gp.HasWritePermission = 1 AND ug.HasWritePermission = 1 )

GO

ALTER VIEW [dbo].[AbPersZusatzDatenTyp]
AS 
 SELECT  PersonAdditionalDataTypes.* 
 FROM  PersonAdditionalDataTypes  LEFT  JOIN 
		(SELECT OwnerGroupId 
		 FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		 WHERE  PermissionArea=0 AND  Username = CURRENT_USER) UG ON (PersonAdditionalDataTypes.OwnerGroupId = UG.OwnerGroupId )
WHERE PersonAdditionalDataTypes.IsSecret =0 or not  UG.OwnerGroupId IS NULL

GO
ALTER VIEW [dbo].[AbPersZusatzDatenTyp_Update]
AS 
SELECT  * FROM PersonAdditionalDataTypes 
WHERE PersonAdditionalDataTypeId in (
	SELECT PersonAdditionalDataTypeId 
	FROM  PersonAdditionalDataTypes  LEFT JOIN (SELECT OwnerGroupId, HasWritePermission 
											FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
											WHERE  PermissionArea=0 AND  Username = CURRENT_USER) UG ON (PersonAdditionalDataTypes.OwnerGroupId = UG.OwnerGroupId )
	WHERE HasWritePermission=1
)

GO
ALTER VIEW [dbo].[AbPlanColumn]
AS 
SELECT  ps.*  FROM [PlanColumns] ps INNER JOIN PlanLayouts  AS p on ps.PlanLayoutId = p.PlanLayoutId WHERE p.OwnerGroupId IN
	   (SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 11
			)
WITH CHECK OPTION

GO

ALTER VIEW [dbo].[AbPlanColumn_update]
AS 
SELECT  ps.*  FROM [PlanColumns] ps WHERE ps.PlanLayoutId IN (
	SELECT p.PlanLayoutId FROM PlanLayouts p
	INNER JOIN Permissions ug ON p.OwnerGroupId = ug.OwnerGroupId
	INNER JOIN Users u ON ug.UserID = u.Userid 
	WHERE u.Username = CURRENT_USER AND ug.PermissionArea = 11 and ug.HasWritePermission=1
)
WITH CHECK OPTION

GO

GO
ALTER VIEW [dbo].[UsersInGroups]
		AS 
		WITH mg (memberuid, groupuid) AS(
			SELECT uid, uid 
			FROM sysusers  
			WHERE name not like '[_]%' 
			
			UNION all	
			
			SELECT mg.memberuid, g.groupuid
			FROM  sysmembers   AS g
				INNER JOIN sysusers ON g.groupuid = CAST(sysusers.uid AS INT)
				INNER JOIN mg		ON g.memberuid  = mg.groupuid 
				WHERE name like '[_]%' 
		)
			
		SELECT DISTINCT  pwG.UserID AS GroupId, pwU.UserID AS UserId FROM mg
				INNER JOIN  sysusers AS  u	ON  mg.memberuid = u.uid
				INNER JOIN  sysusers AS  g	ON  mg.groupuid = g.uid
				INNER JOIN	Users	 AS pwU	ON u.name = pwU.UserName
				INNER JOIN  Users	 AS pwG	ON g.name = pwG.UserName
		WHERE memberuid<>groupuid

		GO

ALTER VIEW [dbo].[AbPlanConfiguration]
AS 
SELECT  p.* FROM PlanLayouts AS p
WHERE p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 11
	)
	OR p.PlanLayoutId IN (
		SELECT pps.PlanLayoutId FROM PlanLayoutPermissions pps
		INNER JOIN Users g ON pps.UserId = g.UserID
		INNER JOIN UsersInGroups uig ON g.UserId = uig.GroupId  
		INNER JOIN Users u on uig.UserId = u.UserID AND u.UserName = CURRENT_USER
	)
WITH CHECK OPTION

GO

ALTER VIEW [dbo].[AbPlanConfiguration_Update]
AS 
SELECT  p.*  FROM  PlanLayouts  AS p WHERE p.OwnerGroupId IN
	   (SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 11 AND Permissions.HasWritePermission = 1)
WITH CHECK OPTION

GO
ALTER VIEW [dbo].[AbPlanPermissionSettings]
AS
	SELECT pps.* FROM PlanLayoutPermissions AS PPS
		INNER JOIN PlanLayouts AS P ON pps.PlanLayoutId=p.PlanLayoutId		
		INNER JOIN OwnerGroups AS gr ON p.OwnerGroupId = gr.OwnerGroupId
		INNER JOIN Permissions AS ug ON gr.OwnerGroupId = ug.OwnerGroupId   
		INNER JOIN Users ON Ug.Userid  = Users.Userid 
	WHERE ug.PermissionArea = 11 AND ug.OptionsFlag & 1 = 1 AND Users.Username = CURRENT_USER


GO
ALTER VIEW [dbo].[AbPlanPermissionSettings_Update]
AS
	SELECT pps.* FROM PlanLayoutPermissions AS PPS WHERE PPS.PlanLayoutId IN (
		SELECT P.PlanLayoutId FROM PlanLayouts AS P		
		INNER JOIN OwnerGroups AS gr ON p.OwnerGroupId = gr.OwnerGroupId
		INNER JOIN Permissions AS ug ON gr.OwnerGroupId = ug.OwnerGroupId   
		INNER JOIN Users ON Ug.Userid  = Users.Userid 
		WHERE ug.PermissionArea = 11 AND ug.OptionsFlag & 2 = 2 AND Users.Username = CURRENT_USER)
	

	WITH CHECK OPTION

GO
ALTER VIEW [dbo].[AbPlanSort]
AS 
SELECT  pso.*  FROM PlanColumnContent pso 
			INNER JOIN  PlanColumns ps ON pso.PlanColumnId = ps.PlanColumnId 
			INNER JOIN  PlanLayouts AS p ON ps.PlanLayoutId = p.PlanLayoutId 
		WHERE p.OwnerGroupId IN
		   (SELECT Permissions.OwnerGroupId 
			FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
			WHERE Users.Username = CURRENT_USER AND PermissionArea = 11
			)
WITH CHECK OPTION

GO

ALTER VIEW [dbo].[AbPlanSort_update]
AS 
SELECT  pso.*  FROM PlanColumnContent pso WHERE pso.PlanColumnId IN (
	SELECT ps.PlanColumnId FROM PlanColumns ps
		INNER JOIN PlanLayouts p ON ps.PlanLayoutId=p.PlanLayoutId
		INNER JOIN Permissions ug ON ug.OwnerGroupId = p.OwnerGroupId
		INNER JOIN Users u ON ug.Userid = u.Userid 
	WHERE u.Username = CURRENT_USER AND ug.PermissionArea = 11 AND ug.HasWritePermission=1
)
WITH CHECK OPTION
go
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbPlanStages'))			DROP VIEW dbo.AbPlanStages
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbPlanStages_update'))			DROP VIEW dbo.AbPlanStages_update
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbPressetext'))			DROP VIEW dbo.AbPressetext
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbPressetext_Update'))			DROP VIEW dbo.AbPressetext_Update

go
ALTER VIEW dbo.AbProductionBonus_Update
AS 
SELECT
	pb.*
FROM
	ProductionBonus AS pb WHERE pb.DepartmentId IN (
		SELECT Dp.DepartmentId FROM Permissions 
		INNER JOIN          Users                            ON Permissions.Userid   = Users.Userid 
		INNER JOIN          Departments AS DP      ON Permissions.OwnerGroupId = DP.OwnerGroupId 
		WHERE Username = CURRENT_USER AND PermissionArea = 4 AND HasWritePermission = 1
	)

GO
ALTER VIEW dbo.AbProductionDepartment_Update
AS
	SELECT  *  
	FROM  ProductionDeparmentData AS pd
	WHERE pd.DepartmentId IN (SELECT d.DepartmentId
	FROM Departments AS d
		INNER JOIN Permissions AS UG ON d.OwnerGroupId =  UG.OwnerGroupId 
		INNER JOIN Users ON Ug.Userid = Users.Userid 
	WHERE ug.PermissionArea = 5 AND ug.HasWritePermission = 1 AND Username = CURRENT_USER )

	WITH CHECK OPTION

GO

ALTER VIEW AbProductionFieldData_Update
AS 
SELECT * FROM ProductionFieldData WHERE ProductionId IN (
	SELECT p.ProductionId
	FROM Permissions ug
		INNER JOIN Users u ON ug.Userid = u.Userid
		INNER JOIN Productions p ON p.OwnerGroupId = ug.OwnerGroupId
	WHERE u.Username = CURRENT_USER
		AND ug.PermissionArea = 3
		AND (ug.HasWritePermission = 1 OR ug.OptionsFlag & 1 = 1)
)
WITH CHECK OPTION

GO
ALTER VIEW dbo.AbProductionSeasons_Update 
AS
SELECT * FROM ProductionInSeasons WHERE ProductionId IN (
SELECT ProductionId 
FROM Productions AS S 
INNER JOIN Permissions AS UG ON S.OwnerGroupId = UG.OwnerGroupId
INNER JOIN Users AS U ON U.UserID = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.HasWritePermission = 1 AND UG.PermissionArea = 3)

WITH CHECK OPTION

GO
ALTER VIEW dbo.AbProductionsWorkVersions_Update
AS 
	SELECT
		pwv.*
	FROM  
		ProductionsWorkVersions pwv
	WHERE 
		pwv.ProductionId IN (
		SELECT P.ProductionId FROM dbo.Productions AS P			
			INNER JOIN	(SELECT DISTINCT OwnerGroupId, HasWritePermission,OptionsFlag&2 Write
							FROM			Permissions 
								INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
							WHERE	Username = CURRENT_USER AND 
									PermissionArea = 3 AND 
									(HasWritePermission = 1 OR (OptionsFlag&2) = 2) ) AS UG
					ON P.OwnerGroupId = UG.OwnerGroupId) 
	WITH CHECK OPTION
					--Schreibrecht oder Werke Zuweisen

GO
ALTER 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

ALTER VIEW dbo.AbQualification_Role_Update
AS
	SELECT  Qualification_Role.*  FROM  Qualification_Role WHERE Qualification_Role.RoleId IN (SELECT pp.RoleId 
	FROM Roles AS PP
		INNER JOIN Permissions AS UG ON pp.OwnerGroupId =  UG.OwnerGroupId 
		INNER JOIN Users ON Ug.Userid = Users.Userid 
	WHERE  (ug.PermissionArea = 2 OR ug.PermissionArea = 4) AND ug.HasWritePermission = 1 AND Username = CURRENT_USER GROUP BY pp.RoleId)

	WITH CHECK OPTION

GO
ALTER VIEW [dbo].AbResourceBlockPeriods
AS 
SELECT  rb.* FROM ResourceBlockPeriods AS rb INNER JOIN dbo.Resources AS r ON rb.ResourceId = r.ResourceId
				INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
				INNER JOIN Users AS pw ON ug.UserId = pw.UserId
			WHERE Username = CURRENT_USER AND PermissionArea = 16 

GO

ALTER VIEW [dbo].AbResourceBlockPeriods_Update
AS 
SELECT  rb.* FROM dbo.ResourceBlockPeriods AS rb
		 WHERE  rb.ResourceId IN (SELECT r.ResourceId FROM Resources AS r 
														INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
														INNER JOIN Users AS pw ON ug.UserId = pw.UserId
									WHERE Username = CURRENT_USER AND PermissionArea = 16 AND HasWritePermission = 1)
WITH CHECK	OPTION

GO

ALTER VIEW [dbo].[AbResourceContainer]
AS 
SELECT  r.* FROM dbo.ResourceContainer AS r
				INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
				INNER JOIN Users AS pw ON ug.UserId = pw.UserId
			WHERE Username = CURRENT_USER AND PermissionArea = 16 

GO

ALTER VIEW [dbo].[AbResourceContainer_Update]
AS 
SELECT  r.* FROM dbo.ResourceContainer AS r
		 WHERE r.OwnerGroupId IN ( SELECT OwnerGroupId FROM Permissions AS ug
				INNER JOIN Users AS pw ON ug.UserId = pw.UserId
			WHERE Username = CURRENT_USER AND PermissionArea = 16 AND HasWritePermission = 1)
WITH CHECK OPTION
GO
GO
ALTER VIEW [dbo].AbResourceObjects
AS 
SELECT  ro.* FROM ResourceObjects AS ro INNER JOIN dbo.Resources AS r ON ro.ResourceId = r.ResourceId
				INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
				INNER JOIN Users AS pw ON ug.UserId = pw.UserId
			WHERE Username = CURRENT_USER AND PermissionArea = 16 

GO
ALTER VIEW [dbo].AbResourceObjects_Update
AS 
SELECT  ro.* FROM dbo.ResourceObjects AS ro
		 WHERE  ro.ResourceId IN (SELECT r.ResourceId FROM Resources AS r 
														INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
														INNER JOIN Users AS pw ON ug.UserId = pw.UserId
									WHERE Username = CURRENT_USER AND PermissionArea = 16 AND HasWritePermission = 1)
WITH CHECK OPTION
GO
ALTER VIEW dbo.AbResourceObjectBorrows
AS
	SELECT * FROM ResourceObjectBorrows WHERE ResourceObjectId IN (SELECT ResourceObjectId FROM AbResourceObjects)

GO
ALTER VIEW dbo.AbResourceObjectBorrows_Update
AS
	SELECT * FROM ResourceObjectBorrows WHERE ResourceObjectId IN (SELECT ResourceObjectId FROM AbResourceObjects_Update)
	WITH CHECK OPTION

GO
ALTER VIEW [dbo].AbResourceObjectInsurances
AS 
SELECT roi.* FROM ResourceObjectInsurances roi WHERE roi.ResourceObjectId IN (
		SELECT  ro.ResourceObjectId FROM ResourceObjects AS ro
		INNER JOIN dbo.Resources AS r ON ro.ResourceId = r.ResourceId
		INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
		INNER JOIN Users AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER AND PermissionArea = 16 
	)

GO
ALTER VIEW [dbo].AbResourceObjectInsurances_Update
AS 
SELECT roi.* FROM ResourceObjectInsurances roi WHERE roi.ResourceObjectId IN (
		SELECT ro.ResourceObjectId FROM dbo.ResourceObjects AS ro
		INNER JOIN Resources r ON r.ResourceId = ro.ResourceId
		INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
		INNER JOIN Users AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER AND PermissionArea = 16 AND HasWritePermission = 1
	)
WITH CHECK OPTION

GO
ALTER VIEW [dbo].AbResourceObjectMonetaryValues
AS 
SELECT romv.* FROM ResourceObjectMonetaryValues romv WHERE romv.ResourceObjectId IN (
		SELECT  ro.ResourceObjectId FROM ResourceObjects AS ro
		INNER JOIN dbo.Resources AS r ON ro.ResourceId = r.ResourceId
		INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
		INNER JOIN Users AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER AND PermissionArea = 16 
	)

GO
ALTER VIEW [dbo].AbResourceObjectMonetaryValues_Update
AS 
SELECT romv.* FROM ResourceObjectMonetaryValues romv WHERE romv.ResourceObjectId IN (
		SELECT ro.ResourceObjectId FROM dbo.ResourceObjects AS ro
		INNER JOIN Resources r ON r.ResourceId = ro.ResourceId
		INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
		INNER JOIN Users AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER AND PermissionArea = 16 AND HasWritePermission = 1
	)
WITH CHECK OPTION



GO
ALTER VIEW [dbo].AbResourceObjectsWithTodaysInsurancesAndMonetaryValue
AS 	
	SELECT  ro.*,
			roip.ResourceObjectInsuranceId AS CurrentPrivateResourceObjectInsuranceId,
			roip.InsuredPersonId AS CurrentPrivateInsuredPersonId,
	        rois.ResourceObjectInsuranceId AS CurrentDutyResourceObjectInsuranceId,
			rois.InsuredPersonId AS CurrentDutyInsuredPersonId,
			romv.ResourceObjectMonetaryValueId AS CurrentResourceObjectMonetaryValueId
	FROM ResourceObjects AS ro 
	INNER JOIN dbo.Resources AS r ON ro.ResourceId = r.ResourceId
	INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
	INNER JOIN Users AS pw ON ug.UserId = pw.UserID
	LEFT JOIN ResourceObjectInsurances roip ON roip.ResourceObjectId = ro.ResourceObjectId
		 AND roip.IsPrivateInsurance = 1 AND ([roip].[Start] IS NULL OR [roip].[Start] <= GETDATE()) AND ([roip].[End] IS NULL OR [roip].[End] >= GETDATE())
	LEFT JOIN ResourceObjectInsurances rois ON rois.ResourceObjectId = ro.ResourceObjectId
		 AND rois.IsPrivateInsurance = 0 AND ([rois].[Start] IS NULL OR [rois].[Start] <= GETDATE()) AND ([rois].[End] IS NULL OR [rois].[End] >= GETDATE())
	LEFT JOIN ResourceObjectMonetaryValues romv ON romv.ResourceObjectId = ro.ResourceObjectId 
		 AND ([romv].[Start] IS NULL OR [romv].[Start] <= GETDATE()) AND ([romv].[End] IS NULL OR [romv].[End] >= GETDATE())
	WHERE pw.Username = CURRENT_USER AND ug.PermissionArea = 16 

GO
ALTER VIEW [dbo].AbResources
AS 
SELECT  r.* FROM dbo.Resources AS r
				INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
				INNER JOIN Users AS pw ON ug.UserId = pw.UserId
			WHERE Username = CURRENT_USER AND PermissionArea = 16 

GO
ALTER VIEW [dbo].AbResources_Update
AS 
SELECT  r.* FROM dbo.Resources AS r
		 WHERE r.OwnerGroupId IN ( SELECT OwnerGroupId FROM Permissions AS ug
				INNER JOIN Users AS pw ON ug.UserId = pw.UserId
			WHERE Username = CURRENT_USER AND PermissionArea = 16 AND HasWritePermission = 1)
WITH CHECK OPTION

GO

ALTER 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.OwnerGroupId IS NULL THEN -1 ELSE Fee END AS Fee,
		CASE WHEN p.OwnerGroupId IS NULL THEN -1 ELSE OvernightFeeFlat END AS OvernightFeeFlat,
		CASE WHEN p.OwnerGroupId IS NULL THEN -1 ELSE TravelFeeFlat END AS TravelFeeFlat,
		CASE WHEN p.OwnerGroupId IS NULL THEN -1 ELSE OvernightFeePerformance END AS OvernightFeePerformance,
		CASE WHEN p.OwnerGroupId IS NULL THEN -1 ELSE EnsembleCount END AS EnsembleCount,
		CASE WHEN p.OwnerGroupId IS NULL THEN NULL ELSE FeeNote END AS TravelFeePerformance

	FROM        Role_Season AS S 
						INNER JOIN  Roles AS R ON s.RoleId = r.RoleId
						LEFT JOIN  ( SELECT ug.* FROM Permissions AS Ug  
										INNER JOIN Users ON Ug.Userid  = Users.Userid 	
										WHERE ug.PermissionArea = 1 AND ug.HasWritePermission = 1  AND Users.Username = CURRENT_USER) AS p
						ON r.OwnerGroupId = p.OwnerGroupId  

GO

ALTER VIEW dbo.AbRole_Season_Update
	AS
	SELECT      S.*
	FROM        Role_Season AS S 
	WHERE S.RoleId IN(
	SELECT RoleId FROM  Roles AS R
					INNER JOIN Permissions AS Ug ON r.OwnerGroupId = Ug.OwnerGroupId   
					INNER JOIN Users ON Ug.Userid  = Users.Userid 
					WHERE ug.PermissionArea = 4 AND ug.HasWritePermission = 1  AND Users.Username = CURRENT_USER)
	WITH CHECK OPTION

GO

ALTER VIEW dbo.AbRoleBonus_Update
AS 
SELECT
	rb.*
FROM
	RoleBonus AS rb WHERE rb.RoleId IN (
		SELECT R.RoleId FROM Permissions 
		INNER JOIN		Users            ON Permissions.Userid   = Users.Userid 
		INNER JOIN		Roles AS R ON Permissions.OwnerGroupId = r.OwnerGroupId
		WHERE Username = CURRENT_USER AND PermissionArea = 4 AND HasWritePermission = 1 
	) 

GO


ALTER VIEW [dbo].[AbTechnicalPersonalRequirements]
AS 

	SELECT auff.Date, auff.StartTime, auff.EndTime, aufgabe.PersonCount AS SollZahl, aufgabe.WorkAreaGroupId, Count(cuwt.ActivityJobId) as IstZahl, aufgabe.Pos,aufgabe.Name as Info, auff.ActivityId as ActivityId

		FROM TechnicalJobs as aufgabe
		INNER JOIN Activities AS auff ON auff.ActivityId = aufgabe.ActivityId
		LEFT JOIN CostUnitWorkingTimes AS cuwt ON cuwt.ActivityJobId = aufgabe.TechnicalJobId and cuwt.ActivityID = auff.ActivityId

	WHERE auff.[Status] >= 0 AND auff.VariantId = 0 -- Invalid column name 'Status'.
	GROUP BY auff.ActivityId, aufgabe.TechnicalJobId, auff.Date, auff.StartTime, auff.EndTime, aufgabe.PersonCount, aufgabe.WorkAreaGroupId, aufgabe.Pos, aufgabe.Name, auff.ProductionId

GO
ALTER VIEW [dbo].AbTimeAccountUsage_Update
AS 
SELECT * FROM TimeAccountUsage WHERE ContractId IN (

		SELECT Contracts.ContractId 
							FROM			Permissions 
								INNER JOIN	Users	ON Permissions.Userid = Users.Userid 
								INNER JOIN	Contracts	ON Contracts.OwnerGroupId = Permissions.OwnerGroupId 
							WHERE Username = CURRENT_USER  AND PermissionArea = 1 AND Permissions.HasWritePermission = 1) 
WITH CHECK OPTION

GO
ALTER VIEW [dbo].AbTours
AS 
SELECT  t.*  FROM  Tours AS t WHERE t.OwnerGroupId IN (
	SELECT Permissions.OwnerGroupId 
	FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
	WHERE Users.Username = CURRENT_USER AND PermissionArea = 10
)
WITH CHECK OPTION


GO
ALTER VIEW [dbo].AbTours_Update
AS 
SELECT  t.*  FROM  Tours AS t WHERE t.OwnerGroupId IN (
	SELECT Permissions.OwnerGroupId 
	FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
	WHERE Users.Username = CURRENT_USER AND PermissionArea = 10 AND Permissions.HasWritePermission = 1
)
WITH CHECK OPTION
GO
GO
ALTER VIEW dbo.AbTours_InventoryItems
AS
	SELECT * FROM Tours_InventoryItems WHERE TourId IN (SELECT TourId FROM AbTours)

GO
ALTER VIEW dbo.AbTours_InventoryItems_Update
AS
	SELECT * FROM Tours_InventoryItems WHERE TourId IN (SELECT TourId FROM AbTours_Update)
	WITH CHECK OPTION

GO
ALTER VIEW [dbo].AbToursBonuses
AS 
SELECT  tb.*  FROM  Tours_Bonuses AS tb WHERE tb.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN OwnerGroups g ON t.OwnerGroupId = g.OwnerGroupId
	INNER JOIN Permissions AS ug ON g.OwnerGroupId = ug.OwnerGroupId AND ug.PermissionArea = 10
	INNER JOIN Users AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER 
)
WITH CHECK OPTION

GO
ALTER VIEW [dbo].AbToursBonuses_Update
AS 
SELECT  tb.*  FROM  Tours_Bonuses AS tb WHERE tb.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN OwnerGroups g ON t.OwnerGroupId = g.OwnerGroupId
	INNER JOIN Permissions AS ug ON g.OwnerGroupId = ug.OwnerGroupId AND ug.PermissionArea = 10
	INNER JOIN Users AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER AND ug.HasWritePermission = 1
)
WITH CHECK OPTION

GO
ALTER VIEW [dbo].AbToursContracts
AS 
SELECT  tc.* FROM  Tours_Contracts AS tc WHERE tc.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN OwnerGroups g ON t.OwnerGroupId = g.OwnerGroupId
	INNER JOIN Permissions AS ug ON g.OwnerGroupId = ug.OwnerGroupId AND ug.PermissionArea = 10
	INNER JOIN Users AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER 
)
WITH CHECK OPTION

GO
ALTER VIEW [dbo].AbToursContracts_Update
AS 
SELECT  tc.* FROM  Tours_Contracts AS tc WHERE tc.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN OwnerGroups g ON t.OwnerGroupId = g.OwnerGroupId
	INNER JOIN Permissions AS ug ON g.OwnerGroupId = ug.OwnerGroupId AND ug.PermissionArea = 10
	INNER JOIN Users AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER AND ug.HasWritePermission = 1
)
WITH CHECK OPTION

GO
ALTER VIEW [dbo].AbToursCosts
AS 
SELECT  tc.* FROM  Tours_Costs AS tc WHERE tc.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN OwnerGroups g ON t.OwnerGroupId = g.OwnerGroupId
	INNER JOIN Permissions AS ug ON g.OwnerGroupId = ug.OwnerGroupId AND ug.PermissionArea = 10
	INNER JOIN Users AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER 
)
WITH CHECK OPTION

GO
ALTER VIEW [dbo].AbToursCosts_Update
AS 
SELECT  tc.* FROM  Tours_Costs AS tc WHERE tc.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN OwnerGroups g ON t.OwnerGroupId = g.OwnerGroupId
	INNER JOIN Permissions AS ug ON g.OwnerGroupId = ug.OwnerGroupId AND ug.PermissionArea = 10
	INNER JOIN Users AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER AND ug.HasWritePermission = 1
)
WITH CHECK OPTION

GO

ALTER VIEW [dbo].[AbTravels]
AS 
SELECT 	T.*
FROM	Travels AS T
			INNER JOIN	(
			SELECT OwnerGroupId, HasWritePermission FROM Permissions 
			INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
			WHERE Username = CURRENT_USER AND PermissionArea = 15
		) AS UG ON T.OwnerGroupId = UG.OwnerGroupId 

GO
ALTER VIEW [dbo].[AbTravels_Update]
AS 
SELECT * FROM Travels WHERE TravelId IN (
	SELECT ts.TravelId FROM Travels AS ts
	INNER  JOIN	(SELECT DISTINCT OwnerGroupId, HasWritePermission 
						FROM			Permissions 
						INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
						WHERE Username = CURRENT_USER  AND PermissionArea = 15) AS UG
				ON ts.OwnerGroupId = UG.OwnerGroupId
	WHERE UG.HasWritePermission = 1)

	WITH CHECK OPTION
GO


ALTER VIEW [dbo].[AbTravelsteps_Update]
AS 
SELECT ts.* FROM TravelSteps AS ts 
	WHERE ts.TravelId IN (SELECT TravelId
							FROM  Travels AS t
								INNER JOIN  Permissions AS ug ON t.OwnerGroupId = ug.OwnerGroupId
								INNER JOIN		Users 		 ON ug.Userid = Users.Userid 
							WHERE Username = CURRENT_USER AND PermissionArea = 15 AND ug.HasWritePermission = 1) 
	WITH CHECK OPTION

GO
ALTER VIEW [dbo].[AbTravelSteps]
AS 
SELECT ts.* FROM TravelSteps AS ts INNER JOIN Travels AS t on t.TravelId =ts.TravelId INNER JOIN (
		SELECT OwnerGroupId, HasWritePermission FROM Permissions 
		INNER JOIN		Users 		ON Permissions.Userid = Users.Userid 
		WHERE Username = CURRENT_USER AND PermissionArea = 15		
	) AS UG ON T.OwnerGroupId = UG.OwnerGroupId 

GO
ALTER VIEW [dbo].[AbTravelStepAttachments]
AS 
	SELECT * FROM TravelStepAttachments WHERE TravelStepId IN (SELECT TravelStepId FROM AbTravelSteps)

GO
GO
ALTER VIEW [dbo].[AbTravelStepAttachments_Update]
AS 
	SELECT * FROM TravelStepAttachments WHERE TravelStepId IN (SELECT TravelStepId FROM AbTravelSteps_Update)
	WITH CHECK OPTION
GO

ALTER VIEW dbo.AbUpdatelog
AS 
	SELECT  Updatelog.*
	FROM  	Updatelog INNER JOIN Users ON Updatelog.UC = Users.UserId
	WHERE	Username = CURRENT_USER 

GO
ALTER VIEW [dbo].[AbVertrag]
AS 
SELECT  v.*  FROM  Contracts AS v  
	INNER  JOIN	
		(SELECT DISTINCT OwnerGroupId 
		FROM Permissions 
			INNER JOIN	Users ON Permissions.Userid = Users.Userid 
		WHERE Username = CURRENT_USER AND (PermissionArea = 1 OR PermissionArea = 5)
		) AS UG	ON v.OwnerGroupId = UG.OwnerGroupId

GO
ALTER VIEW [dbo].AbVertrag_Update
AS 
SELECT * FROM Contracts WHERE ContractId IN (
	SELECT  v.ContractId  FROM  
		Contracts AS v  
		INNER  JOIN	(SELECT DISTINCT OwnerGroupId, HasWritePermission 
							FROM			Permissions 
							INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
							WHERE Username = CURRENT_USER  AND PermissionArea = 1) AS UG
					ON v.OwnerGroupId = UG.OwnerGroupId
		WHERE UG.HasWritePermission = 1)


GO
ALTER VIEW [dbo].[AbVertragDetails]
AS 
SELECT  v.*  FROM  ContractDetails AS v  
	WHERE EXISTS
		(SELECT Contracts.ContractId 
		FROM Permissions 
			INNER JOIN	Users ON Permissions.Userid = Users.Userid 
			INNER JOIN	Contracts ON Contracts.OwnerGroupId = Permissions.OwnerGroupId 
		WHERE Username = CURRENT_USER AND (PermissionArea = 1 OR PermissionArea = 5) and v.ContractId = Contracts.ContractId) 
GO
ALTER VIEW [dbo].[AbVertragDetails_Update]
AS 
SELECT * FROM ContractDetails WHERE ContractId IN (

		SELECT Contracts.ContractId 
							FROM			Permissions 
							INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
										INNER JOIN	Contracts ON Contracts.OwnerGroupId = Permissions.OwnerGroupId 
							WHERE Username = CURRENT_USER  AND PermissionArea = 1 AND Permissions.HasWritePermission = 1) 

GO
ALTER VIEW [dbo].[AbVertragPerso_Update]
AS 
SELECT * FROM ContractDepartments WHERE ContractId IN (

		SELECT Contracts.ContractId 
							FROM			Permissions 
								INNER JOIN	Users		ON Permissions.Userid = Users.Userid 
								INNER JOIN	Contracts		ON Contracts.OwnerGroupId = Permissions.OwnerGroupId 
							WHERE Username = CURRENT_USER  AND PermissionArea IN (1,5) AND Permissions.HasWritePermission = 1) 
WITH CHECK OPTION

GO

ALTER VIEW [dbo].[AbVertragRolle]
AS 
SELECT	vr.ContractId, vr.RoleId, vr.ContractEngagementId, vr.ProductionId, vr.StartDate, vr.EndDate, vr.RehearsalsCompensatedByPerformance, vr.CompensatedRehearselDays, vr.ProjectedPerformanceCount, vr.LM, vr.UM, vr.LC, vr.UC 
FROM 	ContractEngagements AS vr 
		INNER JOIN Contracts AS v ON VR.ContractId = v.ContractId  
		INNER JOIN	 Permissions as ug ON v.OwnerGroupId = UG.OwnerGroupId
		INNER JOIN	Users	ON ug.Userid = Users.Userid 
	WHERE Username = CURRENT_USER AND PermissionArea = 1

GO
ALTER VIEW [dbo].[AbVertragRolle_Update]
AS 
SELECT vr.ContractId, vr.RoleId, vr.ContractEngagementId, vr.ProductionId, vr.StartDate, vr.EndDate, vr.RehearsalsCompensatedByPerformance, vr.CompensatedRehearselDays, vr.ProjectedPerformanceCount,  vr.LM, vr.UM, vr.LC, vr.UC 
	FROM 	ContractEngagements AS vr 
	WHERE vr.ContractId IN (
		SELECT v.ContractId 
			FROM Contracts   as v
			INNER JOIN	(SELECT DISTINCT OwnerGroupId, HasWritePermission 
							FROM			Permissions 
							INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
							WHERE Username = CURRENT_USER AND PermissionArea = 1 AND (OptionsFlag&1) = 1) AS UG
					ON v.OwnerGroupId = UG.OwnerGroupId
			WHERE UG.HasWritePermission = 1)

GO

ALTER VIEW [dbo].[AbZeitkontenMonat]
AS
SELECT * FROM TimeAccountMonthValues WHERE TimeAccountMonthValueId IN (
	SELECT ZM.TimeAccountMonthValueId
	FROM TimeAccountMonthValues AS ZM
		INNER JOIN Contracts AS V ON V.ContractId = ZM.ContractId
		INNER JOIN ContractDepartments AS VP ON VP.ContractId = V.ContractId
		INNER JOIN WorkAreas ON WorkAreas.WorkAreaId = VP.WorkAreaId
		INNER JOIN Departments AS DP ON DP.DepartmentId = WorkAreas.DepartmentId
		INNER JOIN Permissions AS UG ON 
			   (UG.OwnerGroupId = V.OwnerGroupId AND UG.PermissionArea = 1) 
			OR (UG.OwnerGroupId = DP.OwnerGroupId AND UG.PermissionArea = 5)
		INNER JOIN Users AS UP ON UP.UserID = UG.UserID
	WHERE UP.UserName = CURRENT_USER)

GO

ALTER VIEW [dbo].[AbZeitkontenMonat_Update]
AS
SELECT * FROM TimeAccountMonthValues WHERE TimeAccountMonthValueId IN (
	SELECT ZM.TimeAccountMonthValueId
	FROM TimeAccountMonthValues AS ZM
		INNER JOIN Contracts AS V ON V.ContractId = ZM.ContractId
		INNER JOIN ContractDepartments AS VP ON VP.ContractId = V.ContractId
		INNER JOIN WorkAreas ON WorkAreas.WorkAreaId = VP.WorkAreaId
		INNER JOIN Departments AS DP ON DP.DepartmentId = WorkAreas.DepartmentId
		INNER JOIN Permissions AS UG ON 
			   (UG.OwnerGroupId = V.OwnerGroupId AND UG.PermissionArea = 1) 
			OR (UG.OwnerGroupId = DP.OwnerGroupId AND UG.PermissionArea = 5 AND OptionsFlag & 2 = 2)
		INNER JOIN Users AS UP ON UP.UserID = UG.UserID
	WHERE UP.UserName = CURRENT_USER)

GO

IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.ActivitiesProtected'))				DROP VIEW dbo.ActivitiesProtected
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.ActivitiesPublic'))				DROP VIEW dbo.ActivitiesPublic
GO
ALTER VIEW [dbo].[ActivitiesUpdate]
AS
SELECT * 
FROM Activities AS Auff 
WHERE Auff.Date <= dbo.AccessDatum() 
AND ActivityId IN(
			SELECT DISTINCT A.ActivityId FROM Activities AS A
			INNER JOIN ActivityTypes AS AT ON AT.ActivityTypeId = A.ActivityTypeId
			LEFT JOIN ActivityTypeGroups AS ATG ON AT.ActivityTypeId = ATG.ActivityTypeId
			LEFT JOIN Productions AS S ON S.ProductionId = A.ProductionId
			LEFT JOIN Permissions AS UGBB2 ON UGBB2.PermissionArea = 2 AND UGBB2.HasWritePermission <> 0 AND UGBB2.OwnerGroupId = S.OwnerGroupId
			LEFT JOIN Users AS UPBB2 ON UGBB2.Userid  = UPBB2.Userid AND UPBB2.Username = CURRENT_USER
			LEFT JOIN Permissions AS UGBB9 ON UGBB9.PermissionArea = 9 AND UGBB9.HasWritePermission <> 0 AND UGBB9.OwnerGroupId = ATG.OwnerGroupId
			LEFT JOIN Users AS UPBB9 ON UGBB9.Userid  = UPBB9.Userid AND UPBB9.Username = CURRENT_USER
			LEFT JOIN Users AS UPC ON UPC.UserId = A.UC
			WHERE (ATG.ActivityTypeId IS NULL OR UPBB9.UserID IS NOT NULL) AND UPBB2.UserID IS NOT NULL OR 
			(1 = IS_MEMBER('db_owner') OR (UPC.UserName = CURRENT_USER))
		)
WITH CHECK OPTION

GO
ALTER VIEW [dbo].[ActivityType_Update]
AS
SELECT a.*
	FROM ActivityTypes AS a
	WHERE EXISTS  
		(SELECT g.Modul FROM  OwnerGroups AS g 
			INNER JOIN Permissions AS ug ON g.OwnerGroupId = ug.OwnerGroupId
			INNER JOIN Users AS u ON ug.UserID = u.UserID
			
			WHERE Module & g.Modul = g.Modul and ug.PermissionArea = 2 AND u.UserName = CURRENT_USER
		)
		OR  Module = 0
WITH CHECK OPTION

GO

ALTER VIEW [dbo].[Aufführg]
AS
SELECT a.*
FROM  Activities a
	INNER JOIN  Seasons AS s ON a.Date <= s.EndDate AND a.Date >= s.StartDate
	INNER JOIN  SeasonPermissions AS us ON s.SeasonId=us.SeasonId
	INNER JOIN  Users AS pw ON us.userid=pw.userid
	INNER JOIN  ActivityTypes AS at ON a.ActivityTypeId=at.ActivityTypeId
WHERE	UserName = CURRENT_USER 
	AND at.KatNr NOT IN (3, 99)
	AND a.VariantId = 0  
	AND IsSecret = 0 
WITH CHECK OPTION

GO

IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AufführgAlle'))				DROP VIEW dbo.AufführgAlle
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.BasicCastPublic'))				DROP VIEW dbo.BasicCastPublic
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.Besetzung'))				DROP VIEW dbo.Besetzung
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.Besetzung_Update'))				DROP VIEW dbo.Besetzung_Update
GO

ALTER VIEW [dbo].[BesetzungStd_Update] 
	AS
SELECT Roles.* FROM Roles WHERE OwnerGroupId IN (
	SELECT  Permissions.OwnerGroupId
	FROM Permissions INNER JOIN Users ON Permissions.UserID = Users.UserID
	WHERE Permissions.HasWritePermission = 1 and Users.UserName = CURRENT_USER  	AND (PermissionArea = 2 OR PermissionArea = 4)
) 
WITH CHECK OPTION

GO
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.BesetzungStdSoli'))				DROP VIEW dbo.BesetzungStdSoli

GO
ALTER VIEW [dbo].[Birthdays] AS
	SELECT pd.PersonId, Month(pd.DateOfBirth) AS BirthMonth, Day(pd.DateOfBirth) AS Birthday, p.KeyName AS Searchname, p.OwnerGroupId AS OwnerGroupId, p.IsInactive AS Inactive
	FROM PersonDetails pd INNER JOIN Persons p ON p.PersonId = pd.PersonId 
	WHERE NOT DateOfBirth IS NULL 

GO

ALTER VIEW [dbo].[CastActiveties] 
AS
	SELECT	ac.Date, ac.StartTime, ac.EndTime, ac.ProductionId, ac.LocationId, ac.ActivityTypeId, ac.ArtisticNote, at.KatNr, ac.Status,ac.VariantId, ca.*,st.IsInactive
	FROM	Activities				AS ac
			INNER JOIN ActivityTypes		AS at	ON ac.ActivityTypeId = at.ActivityTypeId
			INNER JOIN Seasons AS s	ON ac.Date <= s.EndDate AND ac.Date >= s.StartDate
			INNER JOIN SeasonPermissions	AS us	ON s.SeasonId = us.SeasonId
			INNER JOIN Users			AS ua	ON us.UserId = ua.UserID
			INNER JOIN Productions			AS p	ON ac.ProductionId = p.ProductionId
			LEFT JOIN Permissions		AS uga	ON p.OwnerGroupId = uga.OwnerGroupId AND ua.UserID = uga.UserID AND uga.PermissionArea = 2
			INNER JOIN Cast	AS ca	ON ac.ActivityId = ca.ActivityId
			LEFT  JOIN Roles		AS ro	ON ca.RoleId = ro.RoleId
			INNER  JOIN OwnerGroups			AS g	ON g.OwnerGroupId = ro.OwnerGroupId	
			INNER  JOIN Permissions		AS ugc	ON G.OwnerGroupId = ugc.OwnerGroupId AND ugc.UserID = ua.UserID AND ugc.PermissionArea = 4
			LEFT JOIN Productions			AS st	ON ac.ProductionId=st.ProductionId 
	WHERE
			ua.UserName = CURRENT_USER
			AND  (ac.IsSecret = 0 OR uga.OptionsFlag IS NULL OR uga.OptionsFlag & 1 = 1)
			AND ((ca.IsSecret = 0 OR (Ugc.OptionsFlag & 1 = 1)))

GO
ALTER VIEW [dbo].CollectiveStatus
AS
SELECT			st.*,
				pk.PersonCategoryType,
				P.LastName, P.KeyName
FROM			PersonStatus st
	INNER JOIN  Persons			AS P	ON st.PersonId = P.PersonId
	INNER JOIN  PersonCategories			AS pk	ON P.PersonCategoryId = pk.PersonCategoryId
WHERE    
	pk.PersonCategoryType BETWEEN 100 AND 200

GO
ALTER VIEW dbo.CountDownRoles_Update
		AS
	SELECT	CountDownRoles.*
	FROM	CountDownRoles
	WHERE EXISTS (
			SELECT * FROM Roles AS R
					INNER JOIN OwnerGroups AS G ON R.OwnerGroupId = G.OwnerGroupId
					INNER JOIN Permissions AS Ug ON G.OwnerGroupId = Ug.OwnerGroupId   
					INNER JOIN Users ON Ug.Userid  = Users.Userid 
					WHERE ug.PermissionArea = 4 AND ug.HasWritePermission = 1  AND Users.Username = CURRENT_USER  AND R.RoleId = CountDownRoles.RoleId ) 
WITH CHECK OPTION

GO
ALTER VIEW [dbo].[DienstplanArten]
AS
	SELECT * FROM Departments dat WHERE dat.DepartmentId IN (
		SELECT
			da.DepartmentId
		FROM
			Departments  AS da	
			LEFT JOIN (SELECT * FROM Permissions WHERE PermissionArea = 5) AS ug ON da.OwnerGroupId = ug.OwnerGroupId
			LEFT JOIN Users AS up ON ug.UserID = up.UserID 
		WHERE
			up.UserName = CURRENT_USER
	)

GO
ALTER VIEW [dbo].[DienstplanArten_Update] 
	AS 
	SELECT  dbo.Departments.*
	FROM	dbo.Departments WHERE DepartmentId IN 
		(SELECT da.DepartmentId
			FROM			Departments  AS da		
				LEFT JOIN	(SELECT * FROM Permissions WHERE PermissionArea = 5) AS UG ON da.OwnerGroupId = UG.OwnerGroupId
				--LEFT JOIN	DienstplanUser			AS du	ON da.DepartmentId = du.DepartmentId 
				LEFT JOIN	Users					AS up	ON up.UserID= UG.UserID 
			WHERE up.UserName = CURRENT_USER 
					OR CURRENT_USER = 'dbo'
					OR (SELECT IS_MEMBER('PersoAdmin'))=1)


GO
			
ALTER VIEW [dbo].[IntervalTaskActivities]
AS
SELECT			act.*
FROM			Activities act 
WHERE			act.ProductionId = -2 AND act.Date <= '19000101'

GO

ALTER VIEW [dbo].[PersonModulGroupPermission_Update]
AS
	SELECT * FROM PersonPermissions 
	WHERE PersonId IN 
		(SELECT p.PersonId 
			FROM Persons AS P 
				INNER JOIN Permissions AS UG ON p.OwnerGroupId = UG.OwnerGroupId 
				INNER JOIN Users as PW ON UG.UserID = PW.UserID 
			WHERE ug.PermissionArea = 0 AND PW.UserName = CURRENT_USER AND ug.HasWritePermission = 1)
WITH CHECK OPTION

GO
ALTER VIEW [dbo].[ProductionParts_Update]
AS 
SELECT *
FROM ProductionChilds 
WHERE ProductionId IN 
		(SELECT ProductionId 
		 FROM	Permissions 	INNER JOIN Users ON Permissions.Userid = Users.Userid 
					 INNER JOIN Productions AS P ON P.OwnerGroupId = Permissions.OwnerGroupId
		 WHERE Username = CURRENT_USER  AND PermissionArea = 3 ANd HasWritePermission = 1)	
WITH CHECK OPTION


GO

ALTER VIEW [dbo].[ProductionResources_Update]
AS 
SELECT * FROM ProductionResources WHERE ProductionId IN (
	SELECT  p.ProductionId  FROM  Productions AS p
		INNER  JOIN	(SELECT DISTINCT OwnerGroupId, HasWritePermission 
					 FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
					 WHERE Username = CURRENT_USER  AND PermissionArea = 3 AND HasWritePermission = 1) AS UG
					  ON p.OwnerGroupId = ug.OwnerGroupId)
WITH CHECK OPTION

GO

ALTER VIEW [dbo].Productions_Seasons_Update
AS 
SELECT * FROM ProductionInSeasons WHERE ProductionId IN (
	SELECT  p.ProductionId  FROM  Productions AS P INNER  JOIN(SELECT DISTINCT OwnerGroupId, HasWritePermission FROM Permissions 
					INNER JOIN	Users	ON Permissions.Userid = Users.Userid 
					WHERE Username = CURRENT_USER  AND PermissionArea = 3 AND HasWritePermission = 1) AS UG
	ON p.OwnerGroupId = ug.OwnerGroupId)
WITH CHECK OPTION

GO
ALTER VIEW [dbo].[Productions_Update]
AS 
SELECT *
FROM Productions 
WHERE ProductionId IN 
		(SELECT ProductionId 
		 FROM	Permissions 	INNER JOIN Users ON Permissions.Userid = Users.Userid 
					 INNER JOIN Productions AS P ON P.OwnerGroupId = Permissions.OwnerGroupId
		 WHERE Username = CURRENT_USER  AND PermissionArea = 3 ANd HasWritePermission = 1)	


GO

ALTER VIEW [dbo].[ProductionsDetails_Update]
AS 
SELECT * FROM ProductionDetails WHERE ProductionId IN (
	SELECT p.ProductionId
	FROM Permissions ug
	INNER JOIN Users u ON ug.Userid = u.Userid
	INNER JOIN Productions p ON p.OwnerGroupId = ug.OwnerGroupId
	WHERE u.Username = CURRENT_USER
	      AND ug.PermissionArea = 3
	      AND (ug.HasWritePermission = 1 OR ug.OptionsFlag & 1 = 1)
)
WITH CHECK OPTION

GO

ALTER VIEW [dbo].ProductionTimeFlow_Update
AS 
SELECT * FROM ProductionTimeFlow WHERE ProductionId IN (
	SELECT  p.ProductionId  FROM  Productions AS P INNER  JOIN(SELECT DISTINCT OwnerGroupId, HasWritePermission FROM Permissions 
					INNER JOIN	Users	ON Permissions.Userid = Users.Userid 
					WHERE Username = CURRENT_USER  AND PermissionArea = 3 AND HasWritePermission = 1) AS UG
	ON p.OwnerGroupId = ug.OwnerGroupId)
WITH CHECK OPTION

GO
ALTER VIEW [dbo].[PublicStatus]
AS
	SELECT			st.*, p.KeyName, p.OwnerGroupId, p.PersonCategoryId, TimeAccountId,
	1 AS AvailableStatus,
	CASE WHEN NOT sr.TemplateStartTime IS NULL OR NOT sr.TemplateEndTime IS NULL THEN 1  ELSE 0 END AS IsHalfDayType
	FROM			PersonStatus st
		INNER JOIN  Persons			AS P	ON st.PersonId = P.PersonId
		INNER JOIN  PersonCategories			AS pk	ON P.PersonCategoryId = pk.PersonCategoryId
		INNER JOIN  PersonStatusTypes		AS sr	ON st.PersonStatusTypeId = sr.PersonStatusTypeId
	WHERE    
		pk.PersonCategoryType BETWEEN 10 AND 200 

GO
ALTER VIEW [dbo].[RoleQualifications_Update] 
	AS
SELECT CastRepertoire.* FROM CastRepertoire WHERE CastRepertoire.RoleId IN 
(
	SELECT   Roles.RoleId
	FROM     Roles  WHERE OwnerGroupId IN (SELECT Permissions.OwnerGroupId
						FROM Permissions INNER JOIN Users ON Permissions.UserID = Users.UserID
						WHERE HasWritePermission = 1 AND Users.UserName = CURRENT_USER  AND PermissionArea = 4) 
							
)
WITH CHECK OPTION
GO

ALTER VIEW [dbo].[Roles_Scenes_Update]
AS 
SELECT * FROM Roles_Scenes WHERE RoleId IN (
	SELECT RoleId FROM Roles AS R 
		INNER  JOIN	(SELECT DISTINCT OwnerGroupId, HasWritePermission FROM Permissions INNER JOIN	Users	ON Permissions.Userid = Users.Userid 
					 WHERE Username = CURRENT_USER  AND PermissionArea = 4 AND HasWritePermission = 1) AS UG
				ON r.OwnerGroupId = ug.OwnerGroupId)
WITH CHECK OPTION


GO

ALTER VIEW [dbo].[Scenes_Update]
AS 
SELECT * FROM Scenes WHERE ActId IN (
	SELECT  ptf.ProductionTimeFlowId  FROM 	ProductionTimeFlow AS ptf 
		INNER JOIN Productions AS P ON ptf.ProductionId= P.ProductionId
		INNER  JOIN	(SELECT DISTINCT OwnerGroupId, HasWritePermission FROM Permissions 
						INNER JOIN		Users		ON Permissions.Userid = Users.Userid 
					WHERE Username = CURRENT_USER  AND PermissionArea = 3 AND HasWritePermission = 1) AS UG
				ON p.OwnerGroupId = ug.OwnerGroupId)
WITH CHECK OPTION


GO
	

		
--#endregion

--#region Pocedures
Print '####################### Alter Procedures 2.0 #######################'
GO

--idFilterTable zuerst, damit views/proceduren den typen auch verwenden können
--#region IdFilterTable

IF NOT EXISTS (SELECT * FROM systypes WHERE name = 'IdFilterTable')	 CREATE TYPE IdFilterTable AS TABLE (Id INT NOT NULL)
GO
GRANT EXEC ON TYPE::IdFilterTable TO [public]
GO

--#endregion IdFilterTable

--#region AbBuenenProbenNr

ALTER PROCEDURE [dbo].[AbBuenenProbenNr]
@lSnr int,
@DDatum  Datetime, 
@dVon  Datetime, 
@dspzStart  Datetime, 
@lZrNr As int
As

SELECT
	Count(*) AS [Anz]
FROM
	Activities a
	INNER JOIN ActivityTypes at ON a.ActivityTypeId = at.ActivityTypeId
WHERE
	a.ProductionId= @lSnr
	AND a.[Status] >= 0
	AND a.[VariantId] = 0
	AND a.LocationId= @lZrNr
	AND at.Category = 800 --Proben
	AND (
		(a.Date < @DDatum  and a.Date>= @dspzStart)
		OR (a.Date= @DDatum AND  CONVERT(varchar(5), a.StartTime, 8)<= CONVERT(varchar(5), @dvon, 8))
	)
go

--#endregion AbBuenenProbenNr

--#region AbProbenNr

ALTER PROCEDURE [dbo].[AbProbenNr]
	@lSnr INT,
	@DDatum DATE,
	@dVon  SMALLDATETIME,
	@dspzStart DATE,
	@lArt As INT
AS
	SELECT Count(*) AS Anz
	FROM Activities
	WHERE ProductionId = @lSnr
		AND [Status] >= 0
		AND VariantId = 0
		AND ActivityTypeId = @lArt 
		AND Date >= @dspzStart
		AND (Date < @DDatum OR  (Date = @DDatum AND StartTime <= @dvon))
GO

--#endregion AbProbenNr

--#region AddCurrentUser

ALTER PROCEDURE dbo.AddCurrentUser
AS
BEGIN
	DECLARE @id INT
	IF  NOT EXISTS (SELECT * FROM  Users WHERE UserName = Current_User)
		BEGIN
			DECLARE @authorizedByGroup BIT
			SET @authorizedByGroup = 0

			SELECT @authorizedByGroup =
				CASE 
					WHEN EXISTS (SELECT * FROM [sys].[database_principals] dp WHERE dp.[type] IN ('S', 'U') AND IS_MEMBER(dp.name) = 1)
					THEN 0
					ELSE 1
				END

			INSERT INTO Users( UserName, lm, lc, Um, uc, IsAuthorizedByWindowsGroup) VALUES (Current_User, GetDate(), GetDate(), 0, 0, @authorizedByGroup)
			SELECT @id = ISNULL(scope_identity(), 0)
			UPDATE Users SET um = @id, uc = @id WHERE UserId =  @id
		END
	SET NOCOUNT ON;
END
go

--#endregion AddCurrentUser

--#region ClearOldAbsences

ALTER PROCEDURE ClearOldAbsences
		@enddate datetime,
		@AbsenceTypes [IdFilterTable] READONLY,
		@infoOnly bit
		AS
		BEGIN
		declare @nocount bit
		select @nocount=count(Id) from @AbsenceTypes;			
		--TEMPORÄRE TABELLE MIT DEN DIENSTPLANEINTRÄGEN, DIE GELÖSCHT WERDEN SOLLEN.
		SELECT DISTINCT s.PersonStatusId,s.EndDate 
		INTO #TempAbsences 
		FROM PersonStatus s 
		 left join @AbsenceTypes a on s.PersonStatusTypeId = a.Id		
		WHERE      s.StartDate < @enddate								
				   AND (a.Id IS NOT NULL OR @noCount=0)

		IF(@infoOnly=0)
		BEGIN
			SELECT COUNT(*) FROM #TempAbsences
			DELETE FROM PersonStatus  where PersonStatusId IN (select PersonStatusId from #TempAbsences)
			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempAbsences
		END
		DROP TABLE #TempAbsences
END
GO

--#endregion ClearOldAbsences

--#region ClearOldCashCommands

ALTER PROCEDURE [dbo].[ClearOldCashCommands]
@cashdatebefore DateTime,
@billingDateBefore DateTime,
@infoOnly bit
AS
BEGIN
		SELECT DISTINCT c.CashCommandId 
		INTO #TempCashCommands
		FROM CashCommands c 
		WHERE
			c.CashDate < @cashdatebefore	
			AND c.BillingPeriodEnd < @billingDateBefore

		IF(@infoOnly=0)
		BEGIN
			SELECT COUNT(*) FROM #TempCashCommands
			DELETE FROM  CashCommandPos_Cast where CashCommandPosId in (select cashcommandposid from CashCommandPos cp inner join  #TempCashCommands t on t.CashCommandId=cp.CashCommandId);
			DELETE FROM  CashCommandPos_ContractDate where CashCommandPosId in (select cashcommandposid from CashCommandPos cp inner join  #TempCashCommands t on t.CashCommandId=cp.CashCommandId);
			DELETE FROM  CashCommandPos where CashCommandPosId in (select cashcommandposid from CashCommandPos cp inner join  #TempCashCommands t on t.CashCommandId=cp.CashCommandId);
			DELETE FROM CashCommands  where CashCommandId in (select CashCommandId from #TempCashCommands);
			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempCashCommands
		END
		DROP TABLE #TempCashCommands	
END
GO

--#endregion ClearOldCashCommands

--#region ClearOldCasts

ALTER PROCEDURE ClearOldCasts
		@enddate datetime,
		@activityTypes [IdFilterTable] READONLY,
		@infoOnly bit
		AS
		BEGIN
		declare @nocount bit
		select @nocount=count(Id) from @activityTypes;
		--TEMPORÄRE TABELLE MIT DEN DIENSTPLANEINTRÄGEN, DIE GELÖSCHT WERDEN SOLLEN.
		SELECT DISTINCT s.CastId 
		INTO #TempCasts
		FROM Cast s 
		inner join Activities a on s.ActivityId=a.ActivityId
		left join @activityTypes act on act.Id=a.ActivityTypeId
		WHERE	a.Date < @enddate
				AND (act.Id is not null OR @nocount=0)

		IF(@infoOnly=0)
		BEGIN
			SELECT COUNT(*) FROM #TempCasts
			DELETE FROM  CashCommandPos_Cast where castid in (select CastId from #TempCasts);
			DELETE FROM CastBonus where castid in (select CastId from #TempCasts);
			DELETE FROM CastCredits  where ServiceCastId in (select CastId from #TempCasts); 
			DELETE FROM CastCredits  where ReplacementCastId in (select CastId from #TempCasts);
			DELETE FROM Cast  where CastId in (select CastId from #TempCasts);
			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempCasts
		END
		DROP TABLE #TempCasts
END
go

--#endregion ClearOldCasts

--#region ClearOldContacts

ALTER PROCEDURE ClearOldContacts
@lastModifiedBefore DateTime,
@infoOnly bit
as
Begin
		SELECT DISTINCT p.PersonId 
		INTO #TempContacts
		FROM Persons p 
		WHERE     p.LM <@lastModifiedBefore and p.IsInactive=1	
		and not exists (select PersonId from Contracts where PersonId=p.PersonId) 
		and not exists (select PersonId from Cast b where b.PersonId=p.PersonId )
		and not exists (select PersonId from PersonStatus s where s.PersonId= p.PersonId);
		IF(@infoOnly=0)
		BEGIN
			SELECT COUNT(*) FROM #TempContacts
			Delete from PersonDetails where PersonId in (select PersonId from #tempcontacts);	
			Delete from PersonEmployee where PersonId in (select PersonId from #TempContacts);
			DELETE FROM BankAccounts where PersonId in (select PersonId from #TempContacts);
			Delete from CastRepertoire where PersonId in (select PersonId from #TempContacts);
			delete from BodyMeasurementData where BodyMeasurementId in (select BodyMeasurementId from BodyMeasurements v where  v.PersonId in (select PersonId from #TempContacts));
			delete from BodyMeasurements  where  PersonId in (select PersonId from #TempContacts);
			update CheckListItem set PersonId= null where personid in (select PersonId from #tempcontacts);
			update CheckListItemTemplate set PersonId = null where personid in (select PersonId from #tempcontacts);
			delete from MailingListEntries where PersonId in (select PersonId from #tempcontacts);
			delete from PersonContactData where PersonId in (select PersonId from #tempcontacts);
			delete from PersonAddress where PersonId in (select PersonId from #tempcontacts);
			delete from PersonRelations where PersonId in (select PersonId from #tempcontacts) or ChildPersonId in (select PersonId from #tempcontacts);
			delete from PersonFieldData where PersonId in (select PersonId from #tempcontacts);
			delete from PersonEmployee where personid in (select PersonId from #tempcontacts);
			delete from PersonDetails where PersonId in (select PersonId from #tempcontacts);
			delete from PersonAdditionalData where PersonId in (select PersonId from #tempcontacts);
			delete from PersonAttachments where PersonId in (select PersonId from #tempcontacts);
			delete from PersonMemo where PersonId in (select PersonId from #tempcontacts);
			Delete from PersonFeeNotes where PersonId in (select PersonId from #tempcontacts);
			delete from Qualification_Person where PersonId in (select PersonId from #tempcontacts);
			delete from ResourceObjects where PersonId in (select PersonId from #tempcontacts);
			delete from PersonPermissions where PersonId in (select PersonId from #tempcontacts);
			delete from BasicCastHistory where PersonOldId in(select PersonId from #tempcontacts) or PersonNewId in (select PersonId from #tempcontacts);
			delete from Persons where PersonId in (select PersonId from #tempcontacts);
			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempContacts
		END
		DROP TABLE #TempContacts	
End
GO

--#endregion ClearOldContacts

--#region ClearOldContracts

ALTER PROCEDURE ClearOldContracts
@contractEndBefore DateTime,
@infoOnly bit
AS
BEGIN
		SELECT DISTINCT v.ContractId 
		INTO #TempContracts
		FROM Contracts v 
		WHERE      v.EndDate < @contractEndBefore	

		IF(@infoOnly=0)
		BEGIN	
			SELECT DISTINCT d.DutyRosterId,d.Date 
			INTO #TempDutyRosterEntrys 
			FROM DutyRoster d 
				INNER JOIN  ContractDepartments as vp ON d.ContractId = vp.ContractId where vp.ContractId in  (select ContractId from #TempContracts);
			DELETE FROM CostUnitWorkingTimes where ShiftDayId in (select DutyRosterId from #TempDutyRosterEntrys)
			DELETE FROM BonusDutyRosterData where DutyRosterId in (select DutyRosterId from #TempDutyRosterEntrys)
			DELETE FROM DutyRoster  where DutyRosterId in (select DutyRosterId from #TempDutyRosterEntrys)
			SELECT COUNT(*) FROM #TempContracts
			DELETE FROM CastCredits where ContractId in (select ContractId from #TempContracts);
			DELETE FROM  Contract_Qualification_Person where ContractId in (select ContractId from #TempContracts);
			DELETE FROM  ContractBonus where ContractId in (select ContractId from #TempContracts);
			DELETE FROM ContractDateConfirmations where ContractConfirmationId in (SELECT ContractConfirmationId FROM ContractConfirmations WHERE ContractId in (select ContractId from #TempContracts));
			DELETE FROM ContractDocumentAttachments where ContractDocumentId in ((SELECT ContractConfirmationId FROM ContractConfirmations WHERE ContractId in (select ContractId from #TempContracts)));
			DELETE FROM ContractConfirmations WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractFields WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractPartTimePeriods WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractSeasonInformation WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM TimeAccountUsage WHERE ContractId in (SELECT ContractId from #TempContracts);			
			DELETE FROM Tours_Contracts WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM Tours_InventoryItems WHERE ContractId in (SELECT ContractId from #TempContracts);	
			DELETE FROM Travels WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractDetails WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractWorkingTimeModels where ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractDepartments WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractDateMaturities Where ContractDateId in (SELECT ContractDateId FROM ContractDates WHERE ContractEngagementId in (select ContractEngagementId FROM ContractEngagements WHERE ContractId in (select ContractId from #TempContracts)));
			DELETE FROM ContractDateConfirmations where ContractDateId in (SELECT ContractDateId FROM ContractDates WHERE ContractEngagementId in (select ContractEngagementId FROM ContractEngagements WHERE ContractId in (select ContractId from #TempContracts)));
			DELETE FROM ContractDates WHERE ContractEngagementId in (SELECT ContractEngagementId FROM ContractEngagements WHERE ContractId in (select ContractId from #TempContracts));	
			DELETE FROM ContractEngagements WHERE ContractId in (SELECT ContractId from #TempContracts);			
			DELETE FROM Contracts  where ContractId in (SELECT ContractId from #TempContracts);
			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempContracts
		END
		DROP TABLE #TempContracts	
End
GO

--#endregion ClearOldContracts

--#region ClearOldDutyRosterData

ALTER PROCEDURE [dbo].[ClearOldDutyRosterData]
@enddate datetime,
@monthclosedfor int,
@YearClosed bit, 
@infoOnly bit
AS
BEGIN
	IF @enddate is NULL set @enddate = getdate()

	--TEMPORÄRE TABELLE MIT DEN DIENSTPLANEINTRÄGEN, DIE GELÖSCHT WERDEN SOLLEN.
	SELECT DISTINCT d.DutyRosterId,d.Date 
	INTO #TempDutyRosterEntries 
	FROM DutyRoster d 
		INNER JOIN  ContractDepartments as vp ON d.ContractId = vp.ContractId
		INNER JOIN  WorkAreas ON vp.WorkAreaId=WorkAreas.WorkAreaId 
		INNER JOIN Departments da ON WorkAreas.DepartmentId = da.DepartmentId
	WHERE
		d.Date < @endDate 
		AND (DATEPART(YEAR, d.Date)*100 + DATEPART(MONTH, d.Date)) <= (COALESCE(da.LastClosedYearMonth, 190001) - @monthclosedfor)
		AND (@YearClosed=0 
			    OR NOT EXISTS(SELECT * FROM YearClosePeriods j
				            WHERE (DATEPART(YEAR, d.Date)*100 + DATEPART(MONTH, d.Date)) BETWEEN j.StartYearMonth AND j.EndYearMonth
							        AND j.IsClosed = 0
			    )
		)

	IF(@infoOnly=0)
	BEGIN
		SELECT COUNT(*) FROM #TempDutyRosterEntries
		DELETE FROM CostUnitWorkingTimes where ShiftDayId in (select DutyRosterId from #TempDutyRosterEntries)
		DELETE FROM BonusDutyRosterData where DutyRosterId in (select DutyRosterId from #TempDutyRosterEntries)
		DELETE FROM DutyRoster  where DutyRosterId in (select DutyRosterId from #TempDutyRosterEntries)
	END
	ELSE
	BEGIN
		SELECT COUNT(*) FROM #TempDutyRosterEntries
	END
	DROP TABLE #TempDutyRosterEntries
END
GO

--#endregion ClearOldDutyRosterData

--#region ClearOldTimeAccountMonth

ALTER PROCEDURE ClearOldTimeAccountMonth
		@enddate datetime,
		@YearClosed bit, 
		@infoOnly bit
		AS
		BEGIN
		declare @currentYearmonth int;
		declare @endYearMonth int;
		set @endYearMonth= datepart(year,@enddate)*100+datepart(month,@enddate);
		set @currentYearmonth=datepart(year,getdate())*100+datepart(month,getdate());
		
		--TEMPORÄRE TABELLE MIT DEN TimeAccounts Monat, DIE GELÖSCHT WERDEN SOLLEN.
		SELECT DISTINCT d.TimeAccountMonthValueId,d.YearMonth 
		INTO #TempTimeAccountMonths 
		FROM TimeAccountMonthValues d 
				INNER JOIN  ContractDepartments as vp ON d.ContractId = vp.ContractId
				INNER JOIN  WorkAreas ON vp.WorkAreaId = WorkAreas.WorkAreaId 
				INNER JOIN Departments da ON WorkAreas.DepartmentId = da.DepartmentId
				INNER JOIN TimeAccounts z on d.TimeAccountId=z.TimeAccountId
				LEFT JOIN YearClosePeriods j on j.DepartmentId=da.DepartmentId 
					AND d.YearMonth 
					BETWEEN  COALESCE(j.StartYearMonth, 190001) AND COALESCE(j.EndYearMonth, 210001) AND z.YearCloseTypeId=j.YearCloseTypeId
		WHERE      d.YearMonth < COALESCE(@endYearMonth, @currentYearmonth) 
								
				AND ((j.IsClosed=1 AND @YearClosed=1) OR @YearClosed=0)

		IF(@infoOnly=0)
		BEGIN
			SELECT COUNT(*) FROM #TempTimeAccountMonths
			DELETE FROM TimeAccountMonthValues  where TimeAccountMonthValueId in (select TimeAccountMonthValueId from #TempTimeAccountMonths)
			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempTimeAccountMonths
		END
		DROP TABLE #TempTimeAccountMonths
END
GO

--#endregion ClearOldTimeAccountMonth

--#region CloseMonth

ALTER PROCEDURE dbo.CloseMonth
	@dienstplanartID INT, 
	@month INT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE 
	@userId INT
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
	EXECUTE CloseMonthInternal @dienstplanartID, @month, @userId
END
go

--#endregion CloseMonth

--#region CloseMonthInternal

ALTER PROCEDURE CloseMonthInternal 
	@dienstplanartID INT, 
	@month INT,
	@userID int
WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON;
	UPDATE Departments
	SET LastClosedYearMonth=@month
	WHERE 
		DepartmentId=@dienstplanartID 
		AND DepartmentId IN (
			SELECT da.DepartmentId
			FROM Departments  AS da		
				LEFT JOIN	(
					SELECT * FROM Permissions WHERE PermissionArea = 5 AND OptionsFlag&2 = 2) AS UG ON da.OwnerGroupId = UG.OwnerGroupId
				LEFT JOIN	Users AS up	ON up.UserID= UG.UserID 
			WHERE up.UserID = @userID)
		
END
go

--#endregion CloseMonthInternal

--#region CountActivetyContractDates

--Anzahl der zugesagte Vertragstermine 
ALTER PROCEDURE dbo.CountActivetyContractDates 
	@ActivetyId INT
AS

SET NOCOUNT ON
BEGIN
	
	SELECT Count(*) 
	FROM ContractDates AS cd 
		INNER JOIN Cast AS c ON cd.CastId = c.CastId 
	WHERE cd.IsCanceled = 0 AND c.ActivityId = @ActivetyId 
END	
GO

--#endregion CountActivetyContractDates

--#region CountCast

ALTER PROCEDURE [dbo].[CountCast]
	@countType INT,
	@start Datetime, @end Datetime,
	@departmentId INT,
	@groupIds NVARCHAR(4000),
	@personIds NVARCHAR(4000),
	@activitytypIds NVARCHAR(4000)
AS
BEGIN
	SET NOCOUNT ON;
/*
@countType
0 = Anzahl
1 = Anrechenbare
2 = Zeit
*/

--Spielzeitberechtigungen prüfen und ggf Zeitraum anpassen
DECLARE @permissionPeriodStart DATETIME
DECLARE @permissionPeriodEnd DATETIME

SELECT @permissionPeriodStart = MIN(s.SeasonId) , @permissionPeriodEnd = MAX(s.EndDate)
	FROM Seasons AS s	
	INNER JOIN SeasonPermissions	AS us	ON s.SeasonId = us.SeasonId
	INNER JOIN Users			AS U	ON us.UserId =u.UserId
WHERE u.UserName  = CURRENT_USER

IF (@start < @permissionPeriodStart)  SELECT @start = @permissionPeriodStart
IF (@end > @permissionPeriodEnd)  SELECT @end = @permissionPeriodEnd

--Unterscheidung ob die Anzahl oder die anrechenbare Zahl der Dienste gezählt wird(
--z.B. Creditable = 2 als zwei Dienste)

CREATE TABLE #groupIds (id INT  PRIMARY KEY)
INSERT INTO #groupIds SELECT * FROM [dbo].[SplitIDs] ( @groupIds)
CREATE TABLE #personIds (id INT  PRIMARY KEY)
INSERT INTO #personIds SELECT * FROM [dbo].[SplitIDs] ( @personIds)

IF @activitytypIds IS NOT NULL
BEGIN
	CREATE TABLE #activitytypIds (id int  PRIMARY KEY)
	INSERT INTO #activitytypIds SELECT * FROM [dbo].[SplitIDs] ( @activitytypIds)
END

IF @countType = 0
	--Anzahl
	BEGIN
		IF @activitytypIds IS NULL
			--ohne Aufftypfilter
			BEGIN 
				SELECT ca.PersonId, CAST(COUNT (DISTINCT ca.ActivityId) AS float) AS Sum  
				FROM		Activities ac
					INNER JOIN Cast	AS ca	ON ac.ActivityId =ca.ActivityId
					INNER JOIN Roles		AS r	ON ca.RoleId =r.Roleid
					INNER JOIN #personIds				ON ca.PersonId = #personIds.id
					INNER JOIN #groupIds				ON r.OwnerGroupId = #groupIds.id
				WHERE Date BETWEEN @start AND @end 
					AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
					AND ac.Status BETWEEN 0 AND 99 	
				GROUP BY PersonId
			END
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT ca.PersonId, CAST(COUNT (DISTINCT ca.ActivityId) AS float) AS Sum  
				FROM		Activities ac
					INNER JOIN Cast	AS ca	ON ac.ActivityId =ca.ActivityId
					INNER JOIN Roles		AS r	ON ca.RoleId =r.Roleid
					INNER JOIN #personIds				ON ca.PersonId = #personIds.id
					INNER JOIN #groupIds				ON r.OwnerGroupId = #groupIds.id
					INNER JOIN #activitytypIds			ON ac.ActivityTypeId = #activitytypIds.id
				WHERE Date BETWEEN @start AND @end 
					AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
					AND ac.Status BETWEEN 0 AND 99 
				GROUP BY PersonId
			END
		END
	ELSE IF @countType = 1
		--Anrechenbare
		BEGIN
		IF @activitytypIds IS NULL
		--ohne Aufftypfilter
			BEGIN 
				SELECT PersonId, SUM(Sum1) FROM (SELECT PersonId, ca.ActivityId, 
					MAX(ISNULL(ca.Creditable,
						ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr > 10 THEN ISNULL(ProdDep.ShiftCount ,1) ELSE 1 END))) AS Sum1 
				FROM		Activities			AS ac
					INNER JOIN ActivityTypes			AS at		ON at.ActivityTypeId = ac.ActivityTypeId
					INNER JOIN Cast		AS ca		ON ac.ActivityId =ca.ActivityId
					INNER JOIN Roles			AS r		ON ca.RoleId =r.RoleId
					LEFT JOIN ActivityDepartmentData	AS ActDep	ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
					LEFT JOIN ProductionDeparmentData		AS ProdDep	ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId
					INNER JOIN #personIds						ON ca.PersonId = #personIds.id
					INNER JOIN #groupIds						ON r.OwnerGroupId = #groupIds.id
					WHERE Date BETWEEN @start AND @end 
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY PersonId, ca.ActivityId) AS SubSQL GROUP BY PersonId 
			END
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT PersonId, SUM(Sum1) FROM (SELECT PersonId, ca.ActivityId, MAX(ISNULL(ca.Creditable,
						ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr > 10 THEN ISNULL(ProdDep.ShiftCount ,1) ELSE 1 END))) AS Sum1 
				FROM		Activities			AS ac
					INNER JOIN ActivityTypes			AS at		ON at.ActivityTypeId = ac.ActivityTypeId
					INNER JOIN Cast		AS ca		ON ac.ActivityId = ca.ActivityId
					INNER JOIN Roles			AS r		ON ca.RoleId = r.RoleId
					LEFT JOIN ActivityDepartmentData	AS ActDep	ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
					LEFT JOIN ProductionDeparmentData		AS ProdDep	ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId
					INNER JOIN #personIds						ON ca.PersonId = #personIds.id
					INNER JOIN #groupIds						ON r.OwnerGroupId = #groupIds.id
					INNER JOIN #activitytypIds					ON ac.ActivityTypeId = #activitytypIds.id
					WHERE Date BETWEEN @start AND @end 
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY PersonId, ca.ActivityId) AS SubSQL GROUP BY PersonId 
			END	
		END
ELSE IF @countType = 2
	BEGIN
	--Zählen pro Tag max 2 Dienst  (morgens < 14:00 und abends)
			IF @activitytypIds IS NULL
		--ohne Aufftypfilter
			BEGIN 
				SELECT PersonId, SUM(Sum1) FROM (SELECT PersonId, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, 
					MAX(ISNULL(ca.Creditable, ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr > 10 THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
				FROM		Activities			AS ac
					INNER JOIN ActivityTypes			AS at	ON at.ActivityTypeId = ac.ActivityTypeId
					INNER JOIN Cast		AS ca	ON ac.ActivityId = ca.ActivityId
					INNER JOIN Roles			AS r	ON ca.RoleId = r.RoleId
					LEFT JOIN ActivityDepartmentData	AS ActDep ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
					LEFT JOIN ProductionDeparmentData		AS ProdDep ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId
					INNER JOIN #personIds				ON ca.PersonId = #personIds.id
					INNER JOIN #groupIds				ON r.OwnerGroupId = #groupIds.id
					WHERE Date BETWEEN @start AND @end 
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY PersonId, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END) AS SubSQL GROUP BY PersonId 
			END
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT PersonId, SUM(Sum1) FROM (SELECT PersonId, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, MAX(ISNULL(ca.Creditable,
						ISNULL(ActDep.ShiftCount, CASE WHEN at.KatNr > 10 THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
				FROM		Activities			AS ac
					INNER JOIN ActivityTypes			AS at	ON at.ActivityTypeId = ac.ActivityTypeId
					INNER JOIN Cast		AS ca	ON ac.ActivityId = ca.ActivityId
					INNER JOIN Roles			AS r	ON ca.RoleId = r.RoleId
					LEFT JOIN ActivityDepartmentData	AS ActDep ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
					LEFT JOIN ProductionDeparmentData		AS ProdDep ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId
					INNER JOIN #personIds				ON ca.PersonId = #personIds.id
					INNER JOIN #groupIds				ON r.OwnerGroupId = #groupIds.id
					INNER JOIN #activitytypIds			ON ac.ActivityTypeId = #activitytypIds.id
					WHERE Date BETWEEN @start AND @end 
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY PersonId, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END) AS SubSQL GROUP BY PersonId 
			END		
	END
ELSE IF @countType = 3
	BEGIN
	--Zählen pro Tag max 2 Dienst  (morgens < 14:00 und abends)
			IF @activitytypIds IS NULL
		--ohne Aufftypfilter
			BEGIN 
				SELECT PersNrDay, SUM(SumDay) FROM(
				SELECT PersonId AS PersNrDay, Date, SUM(Sum1)-1  AS [SumDay]
				FROM (
					SELECT PersonId, ac.Date, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, 
						MAX(ISNULL(ca.Creditable, ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr > 10 
							THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
					FROM		Activities			AS ac
					INNER JOIN ActivityTypes			AS at	ON at.ActivityTypeId = ac.ActivityTypeId
					INNER JOIN Cast		AS ca	ON ac.ActivityId = ca.ActivityId
					INNER JOIN Roles			AS r	ON ca.RoleId = r.RoleId
					LEFT JOIN ActivityDepartmentData	AS ActDep ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId =@departmentId
					LEFT JOIN ProductionDeparmentData		AS ProdDep ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId
					INNER JOIN #personIds				ON ca.PersonId = #personIds.id
					INNER JOIN #groupIds				ON r.OwnerGroupId = #groupIds.id
					WHERE Date BETWEEN @start AND @end
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY PersonId, ac.Date, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END) AS SubSQL 
				GROUP BY PersonId, Date)  AS subDay Group By PersNrDay
END		
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT PersNrDay, SUM(SumDay) FROM(
				SELECT PersonId AS PersNrDay, Date, SUM(Sum1)-1  AS [SumDay]
				FROM (
					SELECT PersonId, ac.Date, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, 
						MAX(ISNULL(ca.Creditable, ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr > 10 
							THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
					FROM		Activities			AS ac
					INNER JOIN ActivityTypes			AS at	ON at.ActivityTypeId = ac.ActivityTypeId
					INNER JOIN Cast		AS ca	ON ac.ActivityId = ca.ActivityId
					INNER JOIN Roles			AS r	ON ca.RoleId = r.RoleId
					LEFT JOIN ActivityDepartmentData	AS ActDep ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId =@departmentId
					LEFT JOIN ProductionDeparmentData		AS ProdDep ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId
					INNER JOIN #personIds				ON ca.PersonId = #personIds.id
					INNER JOIN #groupIds				ON r.OwnerGroupId = #groupIds.id
					INNER JOIN #activitytypIds			ON ac.ActivityTypeId = #activitytypIds.id
					WHERE Date BETWEEN @start AND @end
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY PersonId, ac.Date, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END) AS SubSQL 
				GROUP BY PersonId, Date)  AS subDay Group By PersNrDay
			END		
	END
ELSE IF @countType = 4
	BEGIN
		IF @activitytypIds IS NULL
			--ohne Aufftypfilter
			BEGIN 
				SELECT ca.PersonId, CAST(COUNT (DISTINCT ac.Date) AS float) AS Sum  
				FROM		Activities ac
					INNER JOIN Cast	AS ca	ON ac.ActivityId =ca.ActivityId
					INNER JOIN Roles		AS r	ON ca.RoleId = r.Roleid
					INNER JOIN #personIds				ON ca.PersonId = #personIds.id
					INNER JOIN #groupIds				ON r.OwnerGroupId = #groupIds.id
				WHERE Date BETWEEN @start AND @end 
					AND ca.IsCanceled = 0 
					AND ac.Status BETWEEN 0 AND 99 	
				GROUP BY PersonId
			END
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT ca.PersonId, CAST(COUNT (DISTINCT ac.Date) AS float) AS Sum  
				FROM		Activities ac
					INNER JOIN Cast	AS ca	ON ac.ActivityId =ca.ActivityId
					INNER JOIN Roles		AS r	ON ca.RoleId =r.Roleid
					INNER JOIN #personIds				ON ca.PersonId = #personIds.id
					INNER JOIN #groupIds				ON r.OwnerGroupId = #groupIds.id
					INNER JOIN #activitytypIds			ON ac.ActivityTypeId = #activitytypIds.id
				WHERE Date BETWEEN @start AND @end 
					AND ca.IsCanceled = 0 
					AND ac.Status BETWEEN 0 AND 99 
				GROUP BY PersonId
			END
		END
END		
	DROP TABLE #groupIds
	DROP TABLE  #personIds
	IF @activitytypIds IS NOT NULL
	BEGIN
		DROP TABLE #activitytypIds
	END
GO

--#endregion CountCast

--#region CountCastShiftByContract

ALTER PROCEDURE dbo.CountCastShiftByContract
	@countType INT,
	@start Datetime, 
	@end Datetime,
	@contractIds NVARCHAR(4000),
	@departmentId INT,
	@activitytypIds NVARCHAR(4000)
AS
BEGIN
	SET NOCOUNT ON;
/*
@countType
0 = Anzahl
1 = Anrechenbare
2 = Zeit
*/

--Spielzeitberechtigungen prüfen und ggf Zeitraum anpassen
DECLARE @permissionPeriodStart DATETIME
DECLARE @permissionPeriodEnd DATETIME

SELECT @permissionPeriodStart = MIN(s.SeasonId) , @permissionPeriodEnd = MAX(s.EndDate)
	FROM Seasons AS s	
	INNER JOIN SeasonPermissions	AS us	ON s.SeasonId = us.SeasonId
	INNER JOIN Users			AS U	ON us.UserId =u.UserId
WHERE u.UserName  = CURRENT_USER

IF (@start < @permissionPeriodStart)  SELECT @start = @permissionPeriodStart
IF (@end > @permissionPeriodEnd)  SELECT @end = @permissionPeriodEnd

--Unterscheidung ob die Anzahl oder die anrechenbare Zahl der Dienste gezählt wird(
--z.B. Creditable = 2 als zwei Dienste)

CREATE TABLE #contractIds (id INT  PRIMARY KEY)
INSERT INTO #contractIds SELECT * FROM [dbo].[SplitIDs] ( @contractIds)

IF @activitytypIds IS NOT NULL
BEGIN
	CREATE TABLE #activitytypIds (id int  PRIMARY KEY)
	INSERT INTO #activitytypIds SELECT * FROM [dbo].[SplitIDs] ( @activitytypIds)
END

IF @countType = 0
	--Anzahl
	BEGIN
		IF @activitytypIds IS NULL
			--ohne Aufftypfilter
			BEGIN 
				SELECT ca.ContractId, CAST(COUNT (DISTINCT ca.ActivityId) AS float) AS Sum  
				FROM			Activities ac
					INNER JOIN Cast	AS ca	ON ac.ActivityId = ca.ActivityId
					INNER JOIN Roles		AS r	ON ca.RoleId = r.RoleId
					INNER JOIN #contractIds				ON ca.ContractId = #contractIds.id
				WHERE Date BETWEEN @start AND @end 
					AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
					AND ac.Status BETWEEN 0 AND 99 
				GROUP BY ca.ContractId
			END
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT ca.ContractId, CAST(COUNT (DISTINCT ca.ActivityId) AS float) AS Sum  
				FROM		Activities ac
					INNER JOIN Cast	AS ca	ON ac.ActivityId =ca.ActivityId
					INNER JOIN Roles		AS r	ON ca.RoleId =r.RoleId
					INNER JOIN #contractIds				ON ca.ContractId = #contractIds.id
					INNER JOIN #activitytypIds			ON ac.ActivityTypeId = #activitytypIds.id
				WHERE Date BETWEEN @start AND @end 
					AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
					AND ac.Status BETWEEN 0 AND 99 
				GROUP BY ca.ContractId
			END
		END
	ELSE IF @countType = 1
		--Anrechenbare
		BEGIN
		IF @activitytypIds IS NULL
		--ohne Aufftypfilter
			BEGIN 
				SELECT ContractId, SUM(Sum1) FROM (SELECT ca.ContractId, ca.ActivityId, 
					MAX(ISNULL(ca.Creditable,
						ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr = 0 THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
				FROM		Activities			AS ac
					INNER JOIN ActivityTypes			AS at		ON at.ActivityTypeId = ac.ActivityTypeId
					INNER JOIN Cast		AS ca		ON ac.ActivityId =ca.ActivityId
					INNER JOIN Roles			AS r		ON ca.RoleId =r.RoleId
					LEFT JOIN ActivityDepartmentData	AS ActDep	ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
					LEFT JOIN ProductionDeparmentData		AS ProdDep	ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId AND ProdDep.SeasonId IS NULL
					INNER JOIN #contractIds						ON ca.ContractId = #contractIds.id
					WHERE Date BETWEEN @start AND @end 
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY ContractId, ca.ActivityId) AS SubSQL GROUP BY ContractId 
			END
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT ContractId, SUM(Sum1) FROM (SELECT ContractId, ca.ActivityId, MAX(ISNULL(ca.Creditable,
						ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr = 0 THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
				FROM		Activities			AS ac
					INNER JOIN ActivityTypes			AS at		ON at.ActivityTypeId = ac.ActivityTypeId
					INNER JOIN Cast		AS ca		ON ac.ActivityId = ca.ActivityId
					INNER JOIN Roles			AS r		ON ca.RoleId = r.RoleId
					LEFT JOIN ActivityDepartmentData	AS ActDep	ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
					LEFT JOIN ProductionDeparmentData		AS ProdDep	ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId AND ProdDep.SeasonId IS NULL
					INNER JOIN #contractIds				ON ca.ContractId = #contractIds.id
					INNER JOIN #activitytypIds					ON ac.ActivityTypeId = #activitytypIds.id
					WHERE Date BETWEEN @start AND @end 
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY ContractId, ca.ActivityId) AS SubSQL GROUP BY ContractId 
			END	
		END
ELSE IF @countType = 2
	BEGIN
	--Zählen pro Tag max 2 Dienst  (morgens < 14:00 und abends)
			IF @activitytypIds IS NULL
		--ohne Aufftypfilter
			BEGIN 
				SELECT ContractId, SUM(Sum1) FROM (SELECT ContractId, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, 
					MAX(ISNULL(ca.Creditable, ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr = 0 THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
				FROM		Activities			AS ac
					INNER JOIN ActivityTypes			AS at	ON at.ActivityTypeId = ac.ActivityTypeId
					INNER JOIN Cast		AS ca	ON ac.ActivityId = ca.ActivityId
					INNER JOIN Roles			AS r	ON ca.RoleId = r.RoleId
					LEFT JOIN ActivityDepartmentData	AS ActDep ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
					LEFT JOIN ProductionDeparmentData		AS ProdDep ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId AND ProdDep.SeasonId IS NULL
					INNER JOIN #contractIds				ON ca.ContractId = #contractIds.id
					WHERE Date BETWEEN @start AND @end 
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY ContractId, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END) AS SubSQL GROUP BY ContractId 
			END
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT ContractId, SUM(Sum1) FROM (SELECT ContractId, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, MAX(ISNULL(ca.Creditable,
						ISNULL(ActDep.ShiftCount, CASE WHEN at.KatNr = 0 THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
				FROM		Activities			AS ac
					INNER JOIN ActivityTypes			AS at	ON at.ActivityTypeId = ac.ActivityTypeId
					INNER JOIN Cast		AS ca	ON ac.ActivityId = ca.ActivityId
					INNER JOIN Roles			AS r	ON ca.RoleId = r.RoleId
					LEFT JOIN ActivityDepartmentData	AS ActDep ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
					LEFT JOIN ProductionDeparmentData		AS ProdDep ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId AND ProdDep.SeasonId IS NULL
					INNER JOIN #contractIds				ON ca.ContractId = #contractIds.id
					INNER JOIN #activitytypIds			ON ac.ActivityTypeId = #activitytypIds.id
					WHERE Date BETWEEN @start AND @end 
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY ContractId, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END) AS SubSQL GROUP BY ContractId 
			END		
	END
ELSE IF @countType = 3
	BEGIN
	--Zählen pro Tag max 2 Dienst  (morgens < 14:00 und abends)
			IF @activitytypIds IS NULL
		--ohne Aufftypfilter
			BEGIN 
				SELECT ContractIdDay, SUM(SumDay) FROM(
				SELECT ContractId AS ContractIdDay, Date, SUM(Sum1)-1  AS [SumDay]
				FROM (
					SELECT ContractId, ac.Date, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, 
						MAX(ISNULL(ca.Creditable, ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr = 0 
							THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
					FROM		Activities			AS ac
					INNER JOIN ActivityTypes			AS at	ON at.ActivityTypeId = ac.ActivityTypeId
					INNER JOIN Cast		AS ca	ON ac.ActivityId = ca.ActivityId
					INNER JOIN Roles			AS r	ON ca.RoleId = r.RoleId
					LEFT JOIN ActivityDepartmentData	AS ActDep ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId =@departmentId
					LEFT JOIN ProductionDeparmentData		AS ProdDep ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId AND ProdDep.SeasonId IS NULL
					INNER JOIN #contractIds				ON ca.ContractId = #contractIds.id
					WHERE Date BETWEEN @start AND @end
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY ContractId, ac.Date, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END) AS SubSQL 
				GROUP BY ContractId, Date)  AS subDay Group By ContractIdDay
END		
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT ContractIdDay, SUM(SumDay) FROM(
				SELECT ContractId AS ContractIdDay, Date, SUM(Sum1)-1  AS [SumDay]
				FROM (
					SELECT ContractId, ac.Date, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, 
						MAX(ISNULL(ca.Creditable, ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr = 0 
							THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
					FROM		Activities			AS ac
					INNER JOIN ActivityTypes			AS at	ON at.ActivityTypeId = ac.ActivityTypeId
					INNER JOIN Cast		AS ca	ON ac.ActivityId = ca.ActivityId
					INNER JOIN Roles			AS r	ON ca.RoleId = r.RoleId
					LEFT JOIN ActivityDepartmentData	AS ActDep ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId =@departmentId
					LEFT JOIN ProductionDeparmentData		AS ProdDep ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId AND ProdDep.SeasonId IS NULL
					INNER JOIN #contractIds				ON ca.ContractId = #contractIds.id
					INNER JOIN #activitytypIds			ON ac.ActivityTypeId = #activitytypIds.id
					WHERE Date BETWEEN @start AND @end
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY ContractId, ac.Date, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END) AS SubSQL 
				GROUP BY ContractId, Date)  AS subDay Group By ContractIdDay
			END		
	END
ELSE IF @countType = 4
	BEGIN
		IF @activitytypIds IS NULL
			--ohne Aufftypfilter
			BEGIN 
				SELECT ca.ContractId, CAST(COUNT (DISTINCT ac.Date) AS float) AS Sum  
				FROM		Activities ac
					INNER JOIN Cast	AS ca	ON ac.ActivityId =ca.ActivityId
					INNER JOIN Roles		AS r	ON ca.RoleId =r.RoleId
					INNER JOIN #contractIds				ON ca.ContractId = #contractIds.id
				WHERE Date BETWEEN @start AND @end 
					AND ca.IsCanceled = 0 
					AND ac.Status BETWEEN 0 AND 99 	
				GROUP BY ContractId
			END
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT ca.ContractId, CAST(COUNT (DISTINCT ac.Date) AS float) AS Sum  
				FROM		Activities ac
					INNER JOIN Cast	AS ca	ON ac.ActivityId =ca.ActivityId
					INNER JOIN Roles		AS r	ON ca.RoleId =r.RoleId
					INNER JOIN #contractIds				ON ca.ContractId = #contractIds.id
					INNER JOIN #activitytypIds			ON ac.ActivityTypeId = #activitytypIds.id
				WHERE Date BETWEEN @start AND @end 
					AND ca.IsCanceled = 0 
					AND ac.Status BETWEEN 0 AND 99 
				GROUP BY ContractId
			END
		END

END
	DROP TABLE  #contractIds
	IF @activitytypIds IS NOT NULL
	BEGIN
		DROP TABLE #activitytypIds
	END
go

--#endregion CountCastShiftByContract

--#region DeleteActivityRelations

--Löscht keine Abos u. Auff.-Details
--Fehlende Tabelle entfernt.
ALTER PROCEDURE [dbo].[DeleteActivityRelations]
	@ActivityId INT
AS
BEGIN
SET NOCOUNT ON
	IF NOT EXISTS (SELECT * FROM ActivitiesUpdate WHERE ActivityId= @ActivityId)
		BEGIN
				SELECT 1 AS Attribut, 'No Permissions' AS MSG
			END
		ELSE
	BEGIN
			
		DELETE FROM CastCredits WHERE ServiceCastId IN (SELECT CastId FROM Cast WHERE ActivityId = @activityId)
		DELETE FROM CastCredits WHERE ReplacementCastId IN (SELECT CastId FROM Cast WHERE ActivityId = @activityId)
		DELETE FROM CastBonus WHERE CastBonus.CastId IN (SELECT CastId FROM Cast WHERE ActivityId = @activityId)
		DELETE FROM CashCommandPos_Cast WHERE CastId IN (SELECT CastId FROM Cast WHERE ActivityId = @activityId)
		UPDATE ContractDates SET CastId = NULL WHERE CastId IN (SELECT CastId FROM Cast WHERE ActivityId = @activityId)
		DELETE FROM Cast WHERE ActivityId = @activityId
		DELETE FROM ActivityScenes WHERE ActivityId = @activityId
		DELETE FROM ActivityDepartmentData WHERE ActivityId = @activityId
		DELETE FROM TechnicalJobs WHERE ActivityId = @activityId
		DELETE FROM ActivityCosts WHERE ActivityId = @activityId
		DELETE FROM PresseText WHERE ActivityId = @activityId
		DELETE FROM ActivityDetails WHERE ActivityId = @activityId
		DELETE FROM JourneyTimetables WHERE ActivityId = @ActivityId
		DELETE FROM CostUnitWorkingTimes WHERE ActivityId = @activityId
		DELETE FROM ActivityScenes WHERE ActivityId = @activityId
		UPDATE Activities SET LinkedActivityId = NULL WHERE LinkedActivityId = @ActivityId
		DELETE FROM Activities_ResourceObjects WHERE ActivityId = @ActivityId
	END	
END	
GO

--#endregion DeleteActivityRelations

--#region DeleteCast

ALTER PROCEDURE [dbo].[DeleteCast] 
	@CastId INT
AS
BEGIN
SET NOCOUNT ON
 
	DECLARE @UserGroupId INT 
			
	--BesitzerId der Name
	SELECT @UserGroupId = OwnerGroupId
		FROM Roles AS R INNER JOIN Cast AS C ON r.RoleId = c.RoleId
		WHERE c.CastId = @CastId

	IF (dbo.GetCurrentPermission(@UserGroupId, 4) < 2) 
		BEGIN
			SELECT 1 AS Attribut, 'No Permissions' 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 Cast WHERE CastId = @CastId
		END
	END	
go

--#endregion DeleteCast

--#region DeleteCastFromProductionPart

ALTER PROCEDURE [dbo].[DeleteCastFromProductionPart]
		@ParentProductionId int,
		@ProductionPartId int 
	AS
		BEGIN   
			DELETE c FROM Cast AS c
			INNER JOIN Activities AS a ON c.ActivityId = a.ActivityId
			INNER JOIN Roles AS s ON c.RoleId = s.RoleId
			INNER JOIN Productions AS p ON @ParentProductionId = p.ProductionId
			INNER JOIN Permissions AS g ON p.OwnerGroupId = g.OwnerGroupId
			INNER JOIN Users AS u ON g.UserID = u.UserID
			WHERE a.ProductionId = @ParentProductionId
			AND s.ProductionId = @ProductionPartId
			AND u.UserName = CURRENT_USER 
			AND g.PermissionArea = 3 
			AND g.HasWritePermission = 1
		END
go

--#endregion DeleteCastFromProductionPart

--#region DeleteGroup
ALTER PROCEDURE [dbo].[DeleteGroup] 
	@Id INT
AS
BEGIN
	SET NOCOUNT ON

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

	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Contacts'		FROM Persons			WHERE  OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Productions'	FROM Productions			WHERE  OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Contracts'	FROM Contracts		WHERE  OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Roles'		FROM Roles	WHERE  OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Departments'	FROM Departments WHERE  OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Tours'		FROM Tours WHERE OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Exports'		FROM ExportProfiles WHERE OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'ResourceContainer' FROM ResourceContainer  WHERE OwnerGroupId = @id

	IF NOT EXISTS (SELECT * FROM  #Msg WHERE cnt > 0) 
		BEGIN
			DELETE FROM Permissions WHERE OwnerGroupId = @id
			DELETE FROM Permissions WHERE OwnerGroupId = @id
			DELETE FROM CostCenter_OwnerGroup WHERE OwnerGroupId = @id
			DELETE FROM ActivityTypeGroups WHERE OwnerGroupId = @id
			DELETE FROM OwnerGroups WHERE OwnerGroupId = @id
		END
	ELSE 
		BEGIN 
			SELECT * FROM #Msg  WHERE cnt > 0
		END
END
GO
GRANT EXECUTE ON DeleteGroup TO  SecurityAdmin 
go

--#endregion DeleteGroup

-- SH 2019-11-12
-- DeletePersonReference verschoben in Bereich SH 2019-11-13 OptionsFlag in PersonPermissions
-- Grund sind Abhängigkeiten von Views, die in dem Bereich erstellt/modifiziert werden.



--#region DeleteRole

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

DECLARE @UserGroup int
SELECT @UserGroup = OwnerGroupId FROM Roles WHERE RoleId = @RoleId

--Berechtigungsprüfung
IF (dbo.GetCurrentPermission(@UserGroup, 4) < 2 ) 
	BEGIN
		SELECT 1 AS Attribut, 'No Permissions' AS MSG
	END
ELSE
	BEGIN 
		IF (@RoleId = 0)	
			BEGIN
				SELECT 0 AS Attribut,'Keine gültige Name übergeben (Id 0)' AS MSG
			END
		ELSE
			BEGIN
				DELETE FROM BasicCast WHERE RoleId = @RoleId
				DELETE FROM ContractEngagements WHERE RoleId=@RoleId
				DELETE FROM CastRepertoire WHERE RoleId=@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 CastId FROM Cast WHERE RoleId=@RoleId))
				DELETE FROM ContractDates WHERE CastId IN (SELECT CastId FROM Cast WHERE RoleId=@RoleId)
				DELETE FROM CastBonus WHERE CastId IN (SELECT CastId FROM Cast WHERE RoleId=@RoleId)
				DELETE FROM Cast WHERE RoleId=@RoleId
				DELETE FROM TechnicalJobs WHERE RoleId=@RoleId
				DELETE FROM Roles WHERE RoleId=@RoleId	
			END
		END
END
go

--#endregion DeleteRole

--#region DeleteUsagesOfUserModified

ALTER PROCEDURE [dbo].[DeleteUsagesOfUserModified]
 @Userid   INT
 WITH EXECUTE AS 'dbo'
  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 DeleteUsagesOfUserModified

--#region FindUsagesOfUserModified

ALTER PROCEDURE [dbo].[FindUsagesOfUserModified]
 @Userid INT
 with EXECUTE AS 'dbo'
  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

--#endregion FindUsagesOfUserModified

--#region GetActivities

ALTER PROCEDURE [dbo].[GetActivities]
	@start DATETIME,
	@end DATETIME,
	@condition VARCHAR(MAX),
	@order VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowActivitiesWithoutRights BIT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
	EXECUTE GetActivitiesInternal @start, @end, @condition, @order, @joins, @include, @userId, @ShowActivitiesWithoutRights
END
go

--#endregion GetActivities

--#region GetActivityCountForProduction

ALTER PROCEDURE [dbo].[GetActivityCountForProduction]
	@productionId int
As
	SELECT Count(*)
	FROM Activities 
	WHERE ProductionId = @productionId
GO

--#endregion GetActivityCountForProduction

--#region GetActivityPerformanceNumber

ALTER PROCEDURE dbo.GetActivityPerformanceNumber(
		@productionId INT,
		@seasonStart DATE,
		@date DATE,
		@startTime SMALLDATETIME)
	AS
		SELECT COUNT(*) AS Anz
		FROM Activities AS a
			INNER JOIN ActivityTypes AS At ON a.ActivityTypeId = At.ActivityTypeId
		WHERE a.ProductionId = @productionId 
			AND Category >= 2000
			AND ((a.Date < @date AND a.Date >= @seasonStart) OR (a.Date = @date AND StartTime <= @startTime))
			AND a.[Status] >= 3
			AND VariantId = 0
go

--#endregion GetActivityPerformanceNumber

--#region GetCastByActivityId

ALTER 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 Users WHERE UserName  = CURRENT_USER
	EXECUTE GetCastByActivityIdInternal @ActivityId, @condition, @joins, @include, @userId, @ShowCastWithoutRights
END
go

--#endregion GetCastByActivityId

--#region GetCastByCastId

ALTER PROCEDURE dbo.GetCastByCastId
	@CastId VARCHAR(MAX),
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
	EXECUTE GetCastByCastIdInternal @CastId, @condition, @joins, @include, @userId
END
go

--#endregion GetCastByCastId

--#region GetCastByCastIdInternal

ALTER PROCEDURE [dbo].[GetCastByCastIdInternal]
	@CastId VARCHAR(MAX),
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN

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

	if (@include <> 0)  CREATE TABLE #Cast (CastId INT NOT NULL)
	
	DECLARE @fields VARCHAR(MAX)
	SET @fields  = 'B.CastId, B.RoleId, B.PersonId, B.ActivityId, B.StartOffset, B.EndOffset, B.Note, B.PrintMode, B.LM, B.UM, B.LC, B.UC, B.IsSecret, B.GroupPosition, B.CastStatusId, 
					B.IsCover, B.IsCanceled, B.Creditable, B.BackColorArgb, B.IsReplacement, B.ContractId '

	--Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben
	if (@include <> 0) 
		SET @SQLQuery = 'INSERT INTO #Cast '
	ELSE
		SET @SQLQuery = 'SELECT ' + @fields
					
	 SET @SQLQuery =  @SQLQuery + '	 FROM  Cast AS B '
			
		IF (@joins&1 = 1) 
			SET @SQLQuery = @SQLQuery + 'INNER JOIN (SELECT * FROM ContractDates WHERE IsCanceled = 0) AS cd ON b.CastId = cd.CastID  '

		SET @SQLQuery = @SQLQuery + ' WHERE b.CastId IN (' + @CastId + ')'
			
				print @SQLQuery
		 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 ' + @fields +' FROM Cast AS b 
														INNER JOIN  #Cast ON b.CastId = #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 ContractEngagements vr ON cd.ContractEngagementId = vr.ContractEngagementId
			INNER JOIN Contracts v ON vr.ContractId = v.ContractId
			INNER JOIN Permissions ug ON ug.OwnerGroupId = v.OwnerGroupId AND ug.PermissionArea = 1 AND ug.UserID = @userId

		--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
	END
END
go

--#endregion GetCastByCastIdInternal

--#region GetCastByPeriod

ALTER 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 Users WHERE UserName  = CURRENT_USER
	EXECUTE GetCastByPeriodInternal @start, @end, @condition, @joins, @include, @userId, @ShowCastWithoutRights

END
go

--#endregion GetCastByPeriod

--#region GetCastCountByContract

ALTER PROCEDURE [dbo].[GetCastCountByContract]
		@ContractId INT
AS
BEGIN
	SELECT COUNT(B.RoleId) FROM Cast AS B
	INNER JOIN Activities AS A ON A.ActivityId = B.ActivityId
	AND B.IsCanceled = 0
	AND A.[Status] >= 0
	AND B.ContractId = @ContractId
END
GO

--#endregion GetCastCountByContract

--#region GetCastWithContractPermission

ALTER 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 Cast AS c
	INNER JOIN Roles	AS r ON c.RoleId = r.RoleId
	INNER JOIN Activities AS a ON c.ActivityId = a.ActivityId
	INNER JOIN Permissions AS Ug ON r.OwnerGroupId IN (ISNULL(@groupIdList, r.OwnerGroupId))   
	INNER JOIN Users ON Ug.Userid  = Users.Userid 
	WHERE ug.PermissionArea = 1 /*Es soll der PermissionArea 1 (Vertragsdaten) verwendet werden*/
	AND ug.HasWritePermission = 1
	AND Users.Username = CURRENT_USER
	AND c.PersonId IN (ISNULL(@persNrList, c.PersonId))
	AND a.Date >= ISNULL(@startDate, a.Date)
	AND a.Date <= ISNULL(@endDate, a.Date)

	SELECT * FROM #Cast

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

	IF (@include&1 = 1) -- Bonus der Besetzungen
		SELECT NULL AS [#1], cb.* 
		FROM CastBonus AS cb
		INNER JOIN #Cast ON cb.CastId = #Cast.CastId
	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.CastId
	IF (@include&4 = 4) -- Aktivitäten der Besetzungen
		SELECT NULL AS [#4], a.*
		FROM Activities AS a 
		WHERE EXISTS (SELECT * FROM #Cast AS c WHERE c.ActivityId = a.ActivityId)
	IF (@include&8 = 8) -- Verträge der Besetzungen
		SELECT NULL AS [#8], v.*
		FROM Contracts AS v
		WHERE EXISTS (SELECT * FROM #Cast AS c WHERE c.ContractId = v.ContractId)
	IF (@include&16 = 16) -- Rollen der Besetzungen
		SELECT NULL AS [#16], r.*
		FROM Roles AS r 
		WHERE EXISTS (SELECT * FROM #Cast AS c WHERE c.RoleId = r.RoleId)
	IF (@include&32 = 32)  -- Personen der Besetzungen
		SELECT NULL AS [#32], p.*
		FROM Persons AS p 
		WHERE EXISTS (SELECT * FROM #Cast AS c WHERE c.PersonId = p.PersonId)
	IF (@include&96 = 96) -- Alle Verträge der besetzen Personen (PreLoading von Person.Contracts)
		SELECT NULL AS [#96], v.*
		FROM Contracts AS v
		WHERE EXISTS (SELECT * FROM #Cast AS c WHERE c.PersonId = v.PersonId)
	IF (@include&224 = 224)  -- Alle Rollenverträge (auch Spielzeithonorare etc.) der besetzten Personen (PreLoading von Contract.ContractRolle)
		SELECT NULL AS [#224], vr.*
		FROM ContractEngagements AS vr
		INNER JOIN Contracts AS v ON vr.ContractId = v.ContractId
		WHERE EXISTS (SELECT * FROM #Cast AS c WHERE c.PersonId = v.PersonId)
END
GO

--#endregion GetCastWithContractPermission

--#region GetContracts

ALTER PROCEDURE dbo.GetContracts
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @userId INT
	DECLARE @orContact INT

	SELECT @userId = UserId, @orContact = PersonId FROM Users WHERE UserName = CURRENT_USER

	IF (IS_MEMBER('PersoWriteOwnRegularRoster') = 0 AND IS_MEMBER('PersoWriteOwnRoster') = 0) 
		OR IS_MEMBER('db_owner') = 1 SET @orContact = 0

	EXECUTE GetContractsInternal @condition, @joins, @include, @userId, @orContact
END
GO

--#endregion GetContracts

--#region GetContractsInternal

ALTER PROCEDURE dbo.GetContractsInternal
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@userId INT,
	@orContact INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SQLQuery AS NVARCHAR(MAX)

	IF (@include <> 0)
	BEGIN 
		CREATE TABLE #Contract (ContractId INT NOT NULL PRIMARY KEY , OwnerGroupId INT NOT NULL)
	END

	--Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben
	if (@include <> 0) 
		BEGIN
			SET @SQLQuery = 'INSERT INTO #Contract SELECT v.ContractId, v.OwnerGroupId   '
		END	
	ELSE
		BEGIN
			SET @SQLQuery = 'SELECT *'
		END

	SET @SQLQuery = @SQLQuery + ' FROM Contracts AS v '

	IF (@joins&1 = 1)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN Persons AS P ON v.PersonId = p.PersonId '

	IF (@joins&2 = 2)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN OwnerGroups AS g ON v.OwnerGroupId = g.OwnerGroupId '

	IF (@joins&4 = 4)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN ContractTypes AS vv ON vv.ContractTypeId = v.ContractTypeId '

	IF (@joins&8 = 8)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN ContractDetails vd ON vd.ContractId = v.ContractId '

	IF (@joins&16 = 16)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN PersonDetails pd ON v.PersonId = pd.PersonId '

	DECLARE @securetyWhere AS NVARCHAR(MAX)
	SET @securetyWhere = ' EXISTS (SELECT * FROM Permissions WHERE UserId = ' + CAST(@userId AS VARCHAR(MAX)) +' AND v.OwnerGroupId = Permissions.OwnerGroupId AND PermissionArea IN (1, 5))'
	IF (@orContact <> 0)	SET @securetyWhere = '(' + @securetyWhere + ' OR v.PersonId = ' + CAST(@orContact AS VARCHAR(MAX)) + ')'

	SET @SQLQuery = @SQLQuery+ ' WHERE ' + @securetyWhere

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

	EXECUTE sp_Executesql @SQLQuery

	--Wenn keine weiteren Daten mitgeladen werden wurde das Ergebnis bereits zurückgeben
	IF (@include <> 0) 
	BEGIN
		SELECT * FROM Contracts AS V INNER JOIN #Contract ON v.ContractId = #Contract.ContractId 
	END
	ELSE
	BEGIN
		RETURN 
	END

	IF (@include&1 = 1) --Alle zugeordneten Perso Verträge
		SELECT NULL AS [#1], ContractDepartments.*
		FROM ContractDepartments
			INNER JOIN #Contract ON ContractDepartments.ContractId = #Contract.ContractId

	IF (@include&4 = 4)
	SELECT NULL AS [#4],
		vr.ContractId, vr.RoleId, vr.ContractEngagementId, vr.ProductionId, vr.StartDate, vr.EndDate, vr.RehearsalsCompensatedByPerformance, vr.CompensatedRehearselDays, vr.ProjectedPerformanceCount, vr.LM, vr.UM, vr.LC, vr.UC 
	FROM  
		ContractEngagements AS vr 
				INNER JOIN #Contract ON vr.ContractId = #Contract.ContractId
				INNER JOIN Permissions AS u ON u.UserId = @userId AND #Contract.OwnerGroupId = u.OwnerGroupId AND u.PermissionArea = 1

	IF (@include&8 = 8) 
		SELECT NULL AS [#8], ContractDetails.*
		FROM ContractDetails
			INNER JOIN #Contract ON ContractDetails.ContractId = #Contract.ContractId

	IF (@include&16 = 16)
		SELECT NULL AS [#16], ContractBonus.* 
		FROM ContractBonus 
			INNER JOIN #Contract ON ContractBonus.ContractId = #Contract.ContractId

	IF (@include&32 = 32)
		SELECT NULL AS [#32], Contract_Qualification_Person.*
		FROM Contract_Qualification_Person
			INNER JOIN #Contract ON Contract_Qualification_Person.ContractId = #Contract.ContractId

	IF (@include&64 = 64)
		SELECT NULL AS [#64], ContractFields.*
		FROM ContractFields
			INNER JOIN #Contract ON ContractFields.ContractId = #Contract.ContractId

	IF (@include&128 = 128)
		SELECT NULL AS [#128], TimeAccountUsage.*
		FROM TimeAccountUsage
			INNER JOIN #Contract ON TimeAccountUsage.ContractId = #Contract.ContractId

	IF (@include&256 = 256)
		SELECT NULL AS [#256], ContractPartTimePeriods.*
		FROM ContractPartTimePeriods
			INNER JOIN #Contract ON ContractPartTimePeriods.ContractId = #Contract.ContractId

	IF (@include&512 = 512)
		SELECT NULL AS [#512], ContractWorkingTimeModels.*
		FROM ContractWorkingTimeModels
			INNER JOIN #Contract ON ContractWorkingTimeModels.ContractId = #Contract.ContractId

	IF (@include&1024 = 1024)
		SELECT NULL AS [#1024], ContractSalaryRules.*
		FROM ContractSalaryRules
			INNER JOIN #Contract ON ContractSalaryRules.ContractId = #Contract.ContractId
			INNER JOIN Permissions AS u ON u.UserId = @userId AND #Contract.OwnerGroupId = u.OwnerGroupId 
		WHERE u.PermissionArea = 1 AND u.OptionsFlag&1 = 1

	DROP TABLE #Contract
END
GO

--#endregion GetContractsInternal

--#region GetMaxOrderNumber

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 GetMaxOrderNumber

--#region InheritPermissions

-- =============================================
-- 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 Users 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 
-- =============================================
ALTER 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 Users WHERE UserName = CURRENT_USER
	IF @currentUserId = 0 
	BEGIN
		EXEC AddCurrentUser
		SELECT @currentUserId = UserId, @authorizedByGroup = IsAuthorizedByWindowsGroup FROM Users 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 Users 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 Users up WHERE up.IsAuthorizedByWindowsGroup = 1 AND up.UserID <> @currentUserId
    END
	
	--neue Berechtigungen einfügen
	INSERT INTO Permissions (OwnerGroupId, UserID, PermissionArea, HasWritePermission, OptionsFlag, IsInherited, LM, UM, LC, UC)
	SELECT  soll.OwnerGroupId, ugs.UserID, soll.PermissionArea, CAST(COUNT(soll.HasWritePermission) 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	Permissions AS soll	ON ugs.GroupID = soll.UserID
		LEFT JOIN	Permissions AS ist	ON ugs.UserID = ist.UserID AND soll.OwnerGroupId  = ist.OwnerGroupId AND soll.PermissionArea = ist.PermissionArea
	WHERE  ist.PermissionId IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)
	GROUP BY soll.OwnerGroupId, ugs.UserID, soll.PermissionArea

	--Berechtigungen entfernen
	DELETE FROM Permissions 
	WHERE IsInherited = 1 
		AND (Permissions.UserId = @currentUserId OR @forAllUsers = 1)
		AND  PermissionId NOT IN 
				(
					SELECT  ist.PermissionId
					FROM			@usersInGroups AS ugs 
						INNER JOIN	Permissions AS soll		ON ugs.GroupId = soll.UserID
						INNER JOIN	Permissions as ist	ON ugs.UserID = ist.UserID AND soll.OwnerGroupId  = ist.OwnerGroupId AND soll.PermissionArea = ist.PermissionArea
				)
		AND (Permissions.UserID NOT IN (SELECT * FROM @usersAuthorizedByGroup))
	
	UPDATE Permissions SET Permissions.HasWritePermission = SollSchreiben, Permissions.OptionsFlag=SollOp
	FROM 
	(SELECT ugs.UserId, g.OwnerGroupId, PermissionArea, MAX(CAST(g.HasWritePermission 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 Permissions AS G ON ugs.GroupId = G.UserID
		GROUP BY ugs.UserId , g.OwnerGroupId, PermissionArea) AS soll 
	INNER JOIN Permissions  ON 
			soll.UserId = Permissions.UserID AND 
			soll.OwnerGroupId = Permissions.OwnerGroupId AND 
			soll.PermissionArea = Permissions.PermissionArea
	WHERE
		(SollSchreiben <> Permissions.HasWritePermission OR SollOp <> Permissions.OptionsFlag)
		AND Permissions.IsInherited = 1
		AND (Permissions.UserId = @currentUserId OR @forAllUsers = 1)
		AND (Permissions.UserID NOT IN (SELECT * FROM @usersAuthorizedByGroup))	
	
	--Jeden User in Gruppe Kontaktdaten Jeder
	INSERT INTO Permissions(OwnerGroupId ,UserID, HasWritePermission, LM, UM, LC, UC, PermissionArea, OptionsFlag)
	SELECT -1, Users.UserID, 0, GETDATE(), 0 ,GETDATE(), 0, 0, 512
	FROM Users LEFT JOIN (SELECT * FROM Permissions WHERE PermissionArea = 0 AND OwnerGroupId = -1) AS UG on Users.UserID=UG.UserID WHERE UG.PermissionId IS NULL

	DELETE FROM Permissions WHERE PermissionArea <> 0 AND OwnerGroupId = -1
	
	INSERT INTO SeasonPermissions (SeasonId,UserID,IsInherited,LM,UM,LC,UC)
	SELECT DISTINCT soll.SeasonId, ugs.UserID, 1, GETDATE(), -1, GETDATE(), -1
	FROM	@usersInGroups AS ugs 
		INNER JOIN	SeasonPermissions AS soll	ON ugs.Groupid = soll.UserID
		LEFT JOIN	SeasonPermissions AS ist	ON ugs.UserID = ist.UserID AND soll.SeasonId=ist.SeasonId
	WHERE  ist.SeasonPermissionId IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)

	DELETE FROM SeasonPermissions 
	WHERE IsInherited = 1 AND  SeasonPermissionId NOT IN (
		SELECT      ist.SeasonPermissionId
		FROM        @usersInGroups          AS ugs
		INNER JOIN	SeasonPermissions soll      ON ugs.GroupId = soll.UserID
		INNER JOIN	SeasonPermissions ist       ON ugs.UserId = ist.UserID  AND soll.SeasonId=ist.SeasonId
	) 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

--#endregion InheritPermissions

--#region InsertWithIdentity

--Procedure zum wirderherstellen von gelöschen Daten (undo). Muss aufgrund von Berechtigunge auf 'IDENTITY_INSERT' in der InsertWithIdentityInternal als dbo ausgefühert werden
ALTER PROCEDURE dbo.InsertWithIdentity
	@Tablename NVARCHAR(254),
	@Fields NVARCHAR(MAX),
	@Values NVARCHAR(MAX)
AS
	BEGIN
		IF EXISTS(SELECT * FROM fn_my_permissions(@Tablename, N'OBJECT')   WHERE subentity_name  = N''  AND Permission_Name = N'INSERT') 
		BEGIN
			SET NOCOUNT ON
			DECLARE @userId INT
			SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
			EXECUTE InsertWithIdentityInternal @Tablename, @Fields, @Values, @userId
		END
	END
GO

--#endregion InsertWithIdentity

--#region InsertWithIdentityInternal

ALTER PROCEDURE dbo.InsertWithIdentityInternal 
	@Tablename NVARCHAR(254),
	@Fields NVARCHAR(MAX),
	@Values NVARCHAR(MAX),
	@UserId INT
	WITH EXECUTE AS 'dbo'
AS
	BEGIN
		SET NOCOUNT ON
		DECLARE @date NVARCHAR(MAX)
		SELECT  @date = '''' + CONVERT(NVARCHAR(50), GetDate()) + ''''
		EXEC (N'SET IDENTITY_INSERT ['+ @Tablename + N'] ON')
		EXEC (N'INSERT INTO [' + @Tablename + N'] (' + @Fields + N', LC, UC, LM, UM) VALUES  (' + @Values + N', '+  @date + N', ' + @UserId + N', '+  @date + N', ' + @UserId + N')')
		EXEC (N'SET IDENTITY_INSERT ['+ @Tablename + N'] OFF')
	END
GO

--#endregion InsertWithIdentityInternal

--#region LogLastLoginDate

ALTER PROCEDURE [dbo].[LogLastLoginDate] AS
BEGIN
	UPDATE Users SET LastLoginDate = GetDate() WHERE UserName = CURRENT_USER
END	
GO

--#endregion LogLastLoginDate

--#region LogLogin

ALTER PROCEDURE dbo.LogLogin 
		@ComputerName VARCHAR(64),
		@OSVersion VARCHAR(24),
		@TheasoftVersion VARCHAR(24),
		@IsAutoUpdateEnabled BIT,
		@AutoUpdatePath VARCHAR(255),
		@FrameworkInfo VARCHAR(MAX),
		@OSInfo VARCHAR(100) = NULL,
		@FrameworkVersion VARCHAR(24) = NULL
	AS
BEGIN
	DECLARE  @ComputerId INT
	DECLARE  @UserId INT
	SET @UserId = 0
	SET @ComputerId = 0
	SELECT @ComputerId = ComputerId FROM Computer WHERE Name = @ComputerName
	SELECT @UserId = UserID FROM Users WHERE  UserName = CURRENT_USER

	IF @UserId = 0 
	BEGIN
		EXEC AddCurrentUser
		SELECT @UserId = UserID FROM Users WHERE  UserName = CURRENT_USER
	END

	IF @ComputerId > 0
		BEGIN
			UPDATE Computer SET theasoftVersion = @TheasoftVersion, OSVersion = @OSVersion, AutoUpdatePath = @AutoUpdatePath, FrameworkInfo = @FrameworkInfo,
				            LM = GetDate(), UM = @UserId, OSInfo = @OSInfo, FrameworkVersion = @FrameworkVersion
			WHERE  ComputerId = @ComputerId
		END
	ELSE
		BEGIN
			INSERT INTO Computer (Name, theasoftVersion, OSVersion,AutoUpdatePath, FrameworkInfo, LC, UC, LM, UM, OSInfo, FrameworkVersion) 
				VALUES (@ComputerName, @TheasoftVersion, @OSVersion, @AutoUpdatePath, @FrameworkInfo, GetDate(), @UserId, GetDate(), @UserId, @OSInfo, @FrameworkVersion) 

			SELECT @ComputerId = ISNULL(scope_identity(),0)
		END	

		UPDATE Users SET LastLoginDate = GetDate(), LastLoginComputerId = @ComputerId WHERE UserID  = @UserId
END
GO

--#endregion LogLogin

--#region MergeDoubletten

ALTER PROCEDURE [dbo].[MergeDoubletten]
	@PersonId int, 
	@DoubletteId int
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	--UPDATE ABgruppe_Person SET PersNr=@PersonId where PersNr=@DoubletteId
	UPDATE Auditions			SET PersonId = @PersonId WHERE PersonId = @DoubletteId 
	UPDATE BankAccounts			SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE BasicCast			SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE Cast					SET PersonId = @PersonId WHERE PersonId = @DoubletteId

	UPDATE CastRepertoire		SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE BodyMeasurements		SET PersonId = @PersonId, MeasuredAt=DATEADD(minute,1,MeasuredAt)  WHERE PersonId = @DoubletteId
	UPDATE CashCommands			SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE CashCommands			SET AgencyId = @PersonId WHERE AgencyId = @DoubletteId
	UPDATE CheckListItem		SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE CheckListItemTemplate SET PersonId= @PersonId WHERE PersonId = @DoubletteId
	UPDATE DepartmentCollectives SET PersonId= @PersonId WHERE PersonId = @DoubletteId
	UPDATE Departments			SET HeadOfDepartmentId = @PersonId 
														 WHERE HeadOfDepartmentId = @DoubletteId
	UPDATE MailingListEntries	SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE Orders				SET SupplierId=@PersonId WHERE SupplierId = @DoubletteId
	UPDATE OrderTravelers		SET TravelerId=@PersonId WHERE TravelerId = @DoubletteId
	UPDATE PersonRelations		SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE PersonRelations		SET ChildPersonId = @PersonId WHERE ChildPersonId = @DoubletteId
	UPDATE PersonFieldData		SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	IF NOT EXISTS (SELECT * FROM PersonEmployee WHERE PersonId=@PersonId)
	BEGIN
		UPDATE PersonEmployee SET PersonId=@PersonId WHERE PersonId= @DoubletteId
	END
	ELSE
	BEGIN
		DELETE FROM PersonEmployee WHERE PersonId = @DoubletteId
	END
	UPDATE PersonMemo			SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE PersonAdditionalData	SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE Qualification_Person SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE ResourceObjectBorrows SET PersonId= @PersonId WHERE PersonId = @DoubletteId
	UPDATE ResourceObjectInsurances SET InsuredPersonId = @PersonId 
														 WHERE InsuredPersonId = @DoubletteId
	UPDATE ResourceObjects		SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE PersonStatus			SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE Travels				SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE Contracts			SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE WorkCreators			SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE WorkVersionRoles_Repertoire  SET PersonId=@PersonId WHERE PersonId = @DoubletteId
	UPDATE WorkVersions			SET PublisherId=@PersonId WHERE PublisherId = @DoubletteId
	UPDATE Locations			SET PersonId = @PersonId WHERE PersonId = @DoubletteId
	UPDATE BasicCastHistory		SET PersonNewId = @PersonId	WHERE PersonNewId = @DoubletteId
	
	DELETE FROM CastRepertoire WHERE PersonId = @DoubletteId AND RoleId IN (SELECT RoleId FROM CastRepertoire WHERE PersonId = @PersonId)
	DELETE FROM Qualification_Person WHERE PersonId = @DoubletteId AND Qualification_Person.QualificationId IN (SELECT QualificationId FROM Qualification_Person WHERE PersonId = @PersonId)
	DELETE FROM PersonPermissions	WHERE PersonId = @DoubletteId
	DELETE FROM PersonContactData	WHERE PersonId = @DoubletteId
	DELETE FROM PersonAddress		WHERE PersonId = @DoubletteId
	DELETE FROM PersonDetails		WHERE PersonId = @DoubletteId
	DELETE FROM PersonFeeNotes		WHERE PersonId = @DoubletteId
	DELETE FROM Persons				WHERE PersonId = @DoubletteId
END
GO

--#endregion MergeDoubletten

--#region NullifyBasicCastReferencesToWorkVersionRoles

ALTER PROCEDURE [dbo].NullifyBasicCastReferencesToWorkVersionRoles 
	@productionId INT
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @UserGroup int

	IF NOT EXISTS(SELECT * FROM Productions s WHERE s.ProductionId = @productionId)	
		BEGIN
			SELECT 2 AS ErrorCode
		END
	ELSE
		BEGIN
			SELECT @UserGroup = s.OwnerGroupId FROM Productions s WHERE s.ProductionId=@productionId
			--Berechtigungsprüfung
			IF (dbo.GetCurrentPermission(@UserGroup, 3) < 2 ) 
			BEGIN
				SELECT 1 AS ErrorCode
			END
			ELSE
			BEGIN
				UPDATE Roles SET WorkVersionRoleId = NULL WHERE ProductionId = @productionId
				SELECT 0 AS ErrorCode
			END
		END
END
GO

--#endregion NullifyBasicCastReferencesToWorkVersionRoles

--#region NullifyCastReferencesToContract

ALTER PROCEDURE [dbo].NullifyCastReferencesToContract 
	@contractId INT
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @UserGroup int

	IF NOT EXISTS(SELECT * FROM AbVertrag_Update v WHERE v.ContractId = @contractId)	
		BEGIN
			SELECT 2 AS ErrorCode
		END
	ELSE
		BEGIN
			SELECT @UserGroup = v.OwnerGroupId FROM AbVertrag_Update v WHERE v.ContractId = @contractId
			--Berechtigungsprüfung
			IF (dbo.GetCurrentPermission(@UserGroup, 1) < 2 ) 
			BEGIN
				SELECT 1 AS ErrorCode
			END
			ELSE
			BEGIN
				UPDATE Cast SET ContractId = NULL WHERE ContractId = @contractId
				SELECT 0 AS ErrorCode
			END
		END
END
GO

--#endregion NullifyCastReferencesToContract

--#region SetActivityHistory
ALTER PROCEDURE dbo.SetActivityHistory
	@ActivetyHistoryId INT,
	@note VARCHAR(MAX),
	@relevant BIT
AS
	UPDATE ActivityHistory 
	SET		XHBem = @note,
			XHRelevant = @relevant
	WHERE XHID	= @ActivetyHistoryId
GO

--#endregion SetActivityHistory

--#region SetCastHistory

ALTER PROCEDURE dbo.SetCastHistory
	@CastHistoryId INT,
	@note VARCHAR(MAX),
	@relevant BIT
AS
	UPDATE CastHistory
	SET		XHBem = @note,
			XHRelevant = @relevant
	WHERE XHID	= @CastHistoryId
GO

--#endregion SetCastHistory

--#region SetModulGroupVDatum
ALTER PROCEDURE [dbo].[SetModulGroupVDatum]
	@OwnerGroupId INT,
	@Date DATETIME 
AS
BEGIN   
	UPDATE dbo.OwnerGroups
	SET ActivityLockingDate = @Date
	WHERE OwnerGroupId = @OwnerGroupId
		AND EXISTS (SELECT u.UserID FROM Users AS u
			INNER JOIN Permissions AS ug ON ug.UserID = u.UserID
			WHERE u.UserName = CURRENT_USER AND ug.OwnerGroupId = @OwnerGroupId AND ug.PermissionArea = 2 AND ug.HasWritePermission = 1 AND ug.OptionsFlag & 1 = 1
		)

	SELECT @@ROWCOUNT
END
GO

--#endregion SetModulGroupVDatum

--#region SetModulGroupWebLockDate

ALTER PROCEDURE [dbo].[SetModulGroupWebLockDate]
	@OwnerGroupId int,
	@Date Datetime 
AS
BEGIN   
	UPDATE dbo.OwnerGroups
		SET WebPublishLockingDate = @Date
		WHERE OwnerGroupId = @OwnerGroupId
			AND EXISTS (SELECT u.UserID FROM Users AS u
							INNER JOIN Permissions AS ug ON ug.UserID = u.UserID
						WHERE u.UserName = CURRENT_USER AND ug.OwnerGroupId = @OwnerGroupId AND ug.PermissionArea = 2 AND ug.HasWritePermission = 1
			)

	SELECT @@ROWCOUNT
END
GO

--#endregion SetModulGroupWebLockDate

--#region ShiftCountingByWorkingTime

ALTER PROCEDURE dbo.ShiftCountingByWorkingTime
	@departmentId INT,
	@contractIds varchar(MAX),
	@startDate DATE,
	@endDate DATE
AS
	BEGIN
	
		SELECT cast([DepartmentWorkingTimeSettings] as xml) as workingTimes Into #xml FROM [Departments] where DepartmentId = @departmentId

		SELECT DATEADD(MINUTE, cast(cast(c.query('data(Start)') as VARCHAR(4)) as int), '00:00') AS zeit 
		INTO #times
		FROM #xml CROSS APPLY workingTimes.nodes('DepartmentWorkingTimeSettings/DayTimePartitions/DayTimePartition') x(c)

		declare @latestTime datetime select top 1 @latestTime = zeit from #times order by zeit desc;
		declare @earliestTime datetime select top 1 @earliestTime = zeit from #times order by zeit asc;

		select * into #times2 from (
		select t1.zeit as aktuell, t2.zeit as [next] from #times as t1
		INNER JOIN #times as t2 ON 
		t1.zeit <> t2.zeit 
		AND (t2.zeit = (select top 1 zeit from #times where zeit > t1.zeit) )
		OR t1.zeit = (@latestTime) AND t2.zeit = (@earliestTime)) a
		order by aktuell
		
		select * from (
		select t.aktuell as aktuell, d.ContractId, COUNT(1) as Count from #times2 as t
		CROSS JOIN DutyRoster as d
		where  d.DutyRosterTypeId = 0 AND d.ContractId IN (SELECT * FROM SplitIds(@contractIds))
		AND d.Date BETWEEN @startDate AND  @endDate
		AND (d.StartTime1 >= t.aktuell AND d.StartTime1 < t.[next]
			OR d.StartTime2 >= t.aktuell AND d.StartTime2 < t.[next]
			OR d.StartTime3 >= t.aktuell AND d.StartTime3 < t.[next]
			OR t.[next] = @earliestTime AND (t.aktuell <= d.StartTime1 OR t.aktuell <= d.StartTime2 OR t.aktuell <= d.StartTime3 OR t.[next] > d.StartTime1 OR t.[next] > d.StartTime2 OR t.[next] > d.StartTime3))
		GROUP BY t.aktuell, d.ContractId) as data
	END
GO

--#endregion ShiftCountingByWorkingTime

--#region sp_SubscriptionActivityCount

ALTER PROCEDURE [dbo].sp_SubscriptionActivityCount
	@subscriptionId int,
	@date  Datetime, 
	@seasonStart  Datetime
AS
	SELECT COUNT(*)
	FROM ActivitySubscriptions as AR
		INNER JOIN Activities AS A ON AR.ActivityId = A.ActivityId 
	WHERE SubscriptionId = @subscriptionId AND Date <= @date AND Date >= @seasonStart AND VariantId = 0
GO

--#endregion sp_SubscriptionActivityCount

--#region GetActivityPerformanceNumbers
ALTER FUNCTION [dbo].[GetActivityPerformanceNumbers](
		@start DATE,
		@end DATE)
RETURNS TABLE
AS
	RETURN (SELECT Row_Number() OVER (PARTITION BY a.ProductionId ORDER BY Date, StartTime) AS RowNum, ActivityId, Date 
			FROM Activities AS A
				INNER JOIN ActivityTypes AS AT ON AT.ActivityTypeId = A.ActivityTypeId
			WHERE Category >= 2000 
				AND Date BETWEEN @start AND @end 
				AND [Status] >= 3
				AND VariantId = 0)
GO

--#endregion GetActivityPerformanceNumbers

--#region GetActivityPerformanceNumbersAllSeasons

ALTER FUNCTION [dbo].[GetActivityPerformanceNumbersAllSeasons](
		@start DATE,
		@end DATE)
RETURNS TABLE
AS
	RETURN (SELECT * FROM (SELECT Row_Number() OVER (PARTITION BY a.ProductionId ORDER BY Date, StartTime)  + ISNULL(pd.NumberOfPerformancesBefore, 0)  AS RowNum, ActivityId, Date
			FROM Activities AS A
				INNER JOIN ActivityTypes AS AT ON AT.ActivityTypeId = A.ActivityTypeId
				LEFT JOIN ProductionDetails AS PD ON Pd.ProductionId = A.ProductionId
			WHERE Category >= 2000
				AND Date <= @end
				AND [Status] >= 3
				AND VariantId = 0
			) AS subA WHERE Date BETWEEN @start AND @end)
GO

--#endregion GetActivityPerformanceNumbersAllSeasons

--#region GetActivityTypeRehearsalNumbers

ALTER FUNCTION [dbo].[GetActivityTypeRehearsalNumbers](
		@start DATE,
		@end DATE)
RETURNS TABLE
AS
	RETURN (SELECT Row_Number() OVER (PARTITION BY a.ActivityTypeId, ProductionId ORDER BY Date, StartTime) AS RowNum, ActivityId, Date 
			FROM Activities AS A
				INNER JOIN ActivityTypes AS AT ON AT.ActivityTypeId = A.ActivityTypeId 
		WHERE AT.LfdNr = 1 AND Date BETWEEN @start AND @end AND [Status] >= 3 AND VariantId = 0)
GO

--#endregion GetActivityTypeRehearsalNumbers

--#region AccessDatum

ALTER FUNCTION [dbo].[AccessDatum] ()
RETURNS datetime AS
BEGIN
	DECLARE @TmpDat DATE

	SET @TmpDat = '30000101'
    SELECT TOP 1  @TmpDat = EndDate
		FROM  Seasons AS spz  
	    INNER JOIN SeasonPermissions AS us ON spz.SeasonId = us.SeasonId
	    INNER JOIN Users AS pw ON us.userid=pw.userid
    WHERE  CURRENT_USER = UserName 
    ORDER BY EndDate DESC

	RETURN @TmpDat
END
GO

--#endregion AccessDatum

--#region GetCurrentPermission

ALTER FUNCTION dbo.GetCurrentPermission(@Group INT, @PermissionFor INT) RETURNS INT
-- Rückgabewerte:
-- Keine Rechte		= 0 
-- Keine Lesen		= 1
-- Keine Schreiben  = 2 
AS
BEGIN
	DECLARE @Right INT 
	SET @Right = 0
	IF (CURRENT_USER = 'dbo') RETURN 2

	SELECT @Right = Permissions.HasWritePermission + 1
	FROM Permissions INNER JOIN Users ON Permissions.UserID = Users.UserID
	WHERE	Users.UserName			= CURRENT_USER  AND 
			PermissionArea	= @PermissionFor AND
			OwnerGroupId			= @Group 
	RETURN @Right
END
GO

--#endregion GetCurrentPermission

--#region IsActivityWritable

ALTER FUNCTION [dbo].IsActivityWritable(@Date DATETIME, @ProductionId INT, @ActivityTypeId INT, @ActivityStatus INT, @ActivityCreatorId INT)
 RETURNS BIT
 AS
 BEGIN
 	DECLARE @Permissions BIT	
	SET @Permissions  = 1
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER

	--Berechtigung für Spielzeit prüfen
	IF @Permissions = 1 AND NOT EXISTS (SELECT * FROM Seasons AS s
											INNER JOIN SeasonPermissions AS us	ON s.SeasonId = us.SeasonId
										WHERE us.UserId = @userId AND s.StartDate <= @Date AND s.EndDate >= @Date) 
	BEGIN
		SET @Permissions = 0
	END
	
	--Bei Berechtigung auf Anfragen brauchen keine weiteren Prüfungen stattfinden
	IF (@ActivityCreatorId <> @userId OR NOT @ActivityStatus IN (2,-1) OR  IS_MEMBER('EditActivityRequests') = 0) 
	BEGIN
		--Berechtigung auf Produktion	
		IF @Permissions = 1 AND NOT EXISTS (SELECT * FROM Productions AS s
												INNER JOIN Permissions AS ug	ON s.OwnerGroupId = ug.OwnerGroupId
										WHERE ug.PermissionArea = 2 AND ug.HasWritePermission = 1)
		BEGIN
			SET @Permissions = 0
		END

		--Berechtigung auf Aktivitätstyp, sind zu einem Typ keine Besitzergruppen wird dies wie "alle" gewertet	
		IF @Permissions = 1 AND EXISTS (SELECT * FROM ActivityTypeGroups AS atg WHERE ActivityTypeId = @ActivityTypeId) AND
							NOT EXISTS (SELECT * FROM ActivityTypeGroups AS atg INNER JOIN Permissions AS ug ON atg.OwnerGroupId = ug.OwnerGroupId 
										WHERE ug.PermissionArea = 2 AND ug.HasWritePermission = 1 AND ActivityTypeId = @ActivityTypeId) 
		BEGIN
			SET @Permissions = 0
		END
	END

	RETURN  @Permissions
END
GO

--#endregion IsActivityWritable

--#region TR_Insert_CostUnitNo

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.TR_Insert_costunitno')) DROP TRIGGER [dbo].TR_Insert_costunitno
GO
CREATE TRIGGER TR_Insert_CostUnitNo ON dbo.Costunits AFTER INSERT, UPDATE 
AS 
BEGIN
	DECLARE @UniqueInfo SMALLINT
	SELECT @UniqueInfo = CONVERT(SMALLINT, DataValue) FROM Settings WHERE Section = 'CostUnitSettings' AND KeyName = 'KeepCostUnitNoUnique'
	IF @UniqueInfo = 0 RETURN --Allow multiple Costunit with identical CostunitNo
	IF @UniqueInfo = 1 -- Do not allow multiple Costunit with identical CostunitNo and same Start
	BEGIN
		IF EXISTS (SELECT Count(c.costunitno) FROM Costunits c INNER JOIN inserted i ON c.costunitno = i.costunitno
					GROUP BY c.costunitno,c.BookableFrom HAVING COUNT(c.costunitno)>1)
		ROLLBACK TRANSACTION
	END	
	IF @UniqueInfo = 2 -- Do not allow multiple Costunit with identical CostunitNo
	BEGIN
		IF EXISTS (SELECT Count(c.costunitno) FROM Costunits c INNER JOIN inserted i ON c.costunitno = i.costunitno
					GROUP BY c.costunitno HAVING COUNT(c.costunitno)>1)
		ROLLBACK TRANSACTION
	END		
END
GO

--#endregion TR_Insert_CostUnitNo


--#region UpdateCastAsDbo

ALTER PROCEDURE [dbo].[UpdateCastAsDbo] 
	@castId INT,
	@contractId INT
AS
BEGIN
	UPDATE Cast SET ContractId = @contractId 
	WHERE  CastId = @castId 
END
GO

--#endregion UpdateCastAsDbo

--#region UpdateCastWithContractPermission

ALTER PROCEDURE [dbo].[UpdateCastWithContractPermission] 
	@castId INT,
	@contractId INT
AS
BEGIN
	UPDATE c SET c.ContractId = @contractId FROM Cast AS c
	INNER JOIN Roles	AS r ON c.RoleId = r.RoleId
	INNER JOIN Permissions AS Ug ON r.OwnerGroupId = ug.OwnerGroupId   
	INNER JOIN Users ON Ug.UserId  = Users.UserId 
	WHERE @castId = c.CastId 
	AND ug.PermissionArea = 1 /*Es soll der Berechtigungsbereich 1 (Vertragsdaten) verwendet werden*/
	AND ug.HasWritePermission = 1 
	AND Users.Username = CURRENT_USER
END
GO

--#endregion UpdateCastWithContractPermission

--#endregion Pocedures

--#region Defaults umbenennen
Print '####################### Rename Defaults 2.0 #######################'
IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_Productions_DefaultPerformaceDuration') ALTER TABLE Productions DROP CONSTRAINT DF_Productions_DefaultPerformaceDuration
IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_Productions_DefaultPerformaceStartTime') ALTER TABLE Productions DROP CONSTRAINT DF_Productions_DefaultPerformaceStartTime

GO
DECLARE @oldName VARCHAR(128) 
DECLARE @newName VARCHAR(128)
DECLARE cview_cursor CURSOR FOR 
SELECT so.name AS old_name, 'DF_' + object_name(so.parent_obj) + '_' + c.name AS new_name
FROM sysobjects so 
	INNER JOIN sysconstraints sc ON so.id = sc.constid 
	INNER JOIN syscolumns c ON sc.colid = c.colid AND c.id = sc.id
WHERE 	so.xtype = 'D' AND so.name <> 'DF_' + object_name(so.parent_obj) + '_' + c.name
	
OPEN cview_cursor 
FETCH NEXT FROM cview_cursor 
INTO @oldName, @newName
WHILE @@FETCH_STATUS = 0
	BEGIN
		
		Print 'Rename ' + @oldName + ' -> ' + @newName
		EXEC sp_rename  @oldName, @newName
		
		FETCH NEXT FROM cview_cursor 
		INTO @oldName, @newName
	END 

CLOSE cview_cursor 
DEALLOCATE cview_cursor 

ALTER TABLE [dbo].[Productions] ADD CONSTRAINT [DF_Productions_DefaultPerformaceDuration]  DEFAULT ('00:00') FOR [DefaultPerformaceDuration]
ALTER TABLE [dbo].[Productions] ADD CONSTRAINT [DF_Productions_DefaultPerformaceStartTime]  DEFAULT ('00:00') FOR [DefaultPerformaceStartTime]
GO
--#endregion

--#region FKs umbenennen
GO
Print '####################### FKs Defaults 2.0 #######################'
GO
DECLARE @oldName VARCHAR(128) 
DECLARE @newName VARCHAR(128)
DECLARE @tabName VARCHAR(128)
DECLARE cview_cursor CURSOR FOR 

SELECT  obj.name AS old_name,
'FK_'+tab1.name + '_' +  tab2.name + CASE WHEN col1.name <> col2.name THEN '_'+col1.name ELSE '' END AS new_name,
    tab1.name AS [table]--,    --col1.name AS [column],    --tab2.name AS [referenced_table],    --col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
	INNER JOIN sys.objects obj ON obj.object_id = fkc.constraint_object_id
	INNER JOIN sys.tables tab1 ON tab1.object_id = fkc.parent_object_id
	INNER JOIN sys.columns col1 ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
	INNER JOIN sys.tables tab2 ON tab2.object_id = fkc.referenced_object_id
	INNER JOIN sys.columns col2 ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id
WHERE 'FK_'+tab1.name + '_' +  tab2.name + CASE WHEN col1.name <> col2.name THEN '_'+col1.name ELSE '' END  <> obj.name
	
OPEN cview_cursor 
FETCH NEXT FROM cview_cursor 
INTO @oldName, @newName, @tabName
WHILE @@FETCH_STATUS = 0
	BEGIN
		IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(@newName) AND type = 'F') 
		BEGIN
			PRINT 'Delete ' + @tabName + '.' + @newName
			EXEC ('ALTER TABLE ' + @tabName + ' DROP CONSTRAINT ' + @newName)
		END
		ELSE
		BEGIN
			PRINT 'Rename ' + @oldName + ' -> ' + @newName
			EXEC sp_rename  @oldName, @newName
		END
		FETCH NEXT FROM cview_cursor 
		INTO @oldName, @newName, @tabName
	END 

CLOSE cview_cursor 
DEALLOCATE cview_cursor 
GO

--#endregion

--#region PKs umbenennen
GO
Print '####################### PKs Defaults 2.0 #######################'
GO
DECLARE @oldName VARCHAR(128) 
DECLARE @newName VARCHAR(128)
DECLARE cview_cursor CURSOR FOR 
SELECT so.name AS old_name, 'PK_' + object_name(so.parent_obj) AS new_name
FROM sysobjects so 
	INNER JOIN sysconstraints sc ON so.id = sc.constid 
WHERE 	so.xtype = 'PK' AND so.name <> 'PK_' + object_name(so.parent_obj) 
	
OPEN cview_cursor 
FETCH NEXT FROM cview_cursor 
INTO @oldName, @newName
WHILE @@FETCH_STATUS = 0
	BEGIN
		
		Print 'Rename ' + @oldName + ' -> ' + @newName
		EXEC sp_rename  @oldName, @newName
		
		FETCH NEXT FROM cview_cursor 
		INTO @oldName, @newName
	END 

CLOSE cview_cursor 
DEALLOCATE cview_cursor 

Print '####################### Ende 2.0 #######################'
GO
--#endregion

--#endregion ====================================================== DB 2.0 =====================================================

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

--Änderungen aus CreateDb_2018.sql

UPDATE ProductionFieldTypes SET IsVisibleIn = 2, DataType = 4 WHERE ProductionFieldTypeId IN (25,26) AND (IsVisibleIn <> 2 OR DataType<> 4)
--#region 20181108
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('OwnerGroups') AND [name] = 'MainOwnerGroupId')
BEGIN
	PRINT('Adding column OwnerGroups.MainOwnerGroupId ...')
	ALTER TABLE dbo.OwnerGroups ADD MainOwnerGroupId INT NULL
	--Einige bekannte Fälle einstellen
	EXEC('UPDATE OwnerGroups SET MainOwnerGroupId = 1 WHERE Name = ''Regie u Konzert'' AND Modul = 1')
	EXEC('UPDATE OwnerGroups SET MainOwnerGroupId = 1 WHERE Name = ''Regie'' AND Modul = 1')
END
GO
--#endregion

--#region 2018-11-21

--TextValue von varchar auf nvarchar lm korrigiert
IF EXISTS (SELECT * FROM sys.columns c INNER JOIN sys.types s ON c.system_type_id = s.system_type_id WHERE c.object_id = OBJECT_ID('ActivityProductionFieldData') AND c.[name] = 'TextValue' AND s.name = 'varchar')
BEGIN
	Print 'ProductionFieldData'
	ALTER TABLE ProductionFieldData ALTER COLUMN TextValue NVARCHAR(MAX)
	UPDATE ProductionFieldData SET TextValue = L10, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 1 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = L20, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 2 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = L30, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 3 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = L40, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 4 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = L50, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 5 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = L60, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 6 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = LRechts, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 7 AND p.lm = s.lc

	UPDATE ProductionFieldData SET TextValue = K10, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 8 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = K20, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 9 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = K30, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 10 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = K40, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 11 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = kRechts, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 12 AND p.lm = s.lc

	UPDATE ProductionFieldData SET TextValue = T10, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 13 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = T20, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 14 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = T30, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 15 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = T40, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 16 AND p.lm = s.lc

	UPDATE ProductionFieldData SET TextValue = F10, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 17 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = F20, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 18 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = F30, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 19 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = F40, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 20 AND p.lm = s.lc

	UPDATE ProductionFieldData SET TextValue = Creator, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 22 AND p.lm = s.lc

	UPDATE ProductionFieldData SET TextValue = Memo, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 28 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = Memo_EN, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN ProductionDetails s ON p.ProductionId = s.ProductionId AND ProductionFieldTypeId = 29 AND p.lm = s.lc
END 
GO
IF EXISTS (SELECT * FROM sys.columns c INNER JOIN sys.types s ON c.system_type_id = s.system_type_id WHERE c.object_id = OBJECT_ID('ActivityProductionFieldData') AND c.[name] = 'TextValue' AND s.name = 'varchar')
BEGIN
	Print 'ActivityProductionFieldData'
	ALTER TABLE ActivityProductionFieldData ALTER COLUMN TextValue NVARCHAR(MAX)
	UPDATE ActivityProductionFieldData SET TextValue = L10, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 1 AND p.lm = s.lc
	UPDATE ActivityProductionFieldData SET TextValue = L20, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 2 AND p.lm = s.lc
	UPDATE ActivityProductionFieldData SET TextValue = L30, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 3 AND p.lm = s.lc
	UPDATE ActivityProductionFieldData SET TextValue = L40, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 4 AND p.lm = s.lc
	UPDATE ActivityProductionFieldData SET TextValue = L50, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 5 AND p.lm = s.lc
	UPDATE ActivityProductionFieldData SET TextValue = L60, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 6 AND p.lm = s.lc
	UPDATE ActivityProductionFieldData SET TextValue = LRechts, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 7 AND p.lm = s.lc

	UPDATE ActivityProductionFieldData SET TextValue = K10, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 8 AND p.lm = s.lc
	UPDATE ActivityProductionFieldData SET TextValue = K20, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 9 AND p.lm = s.lc
	UPDATE ActivityProductionFieldData SET TextValue = K30, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 10 AND p.lm = s.lc
	UPDATE ActivityProductionFieldData SET TextValue = K40, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 11 AND p.lm = s.lc
	UPDATE ActivityProductionFieldData SET TextValue = kRechts, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 12 AND p.lm = s.lc

	UPDATE ActivityProductionFieldData SET TextValue = s.PKomponist, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 22 AND p.lm = s.lc
	UPDATE ActivityProductionFieldData SET TextValue = s.POriginaltitel, lm = ISNULL(s.lm,'19000101') FROM ActivityProductionFieldData p INNER JOIN PresseText s ON p.ActivityId = s.ActivityId AND ProductionFieldTypeId = 23 AND p.lm = s.lc
END
--#endregion

--#region 2018-11-29 sh bugfix flexexport

UPDATE VerteilerFeld SET ObjectName = 'Activities.LocationId' WHERE ObjectName = 'Locations.LocationId' AND ControlContainerName = 'ts_DataAuff'
GO

--#endregion


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Qualification_Role_Roles') AND type = 'F') 
BEGIN
	Print 'Add FK_QualificationRole_Role'
	DELETE FROM Qualification_Role WHERE NOT EXISTS (SELECT * FROM Roles WHERE Qualification_Role.RoleId = Roles.RoleId)

	ALTER TABLE dbo.Qualification_Role  WITH CHECK ADD  CONSTRAINT FK_Qualification_Role_Roles FOREIGN KEY(RoleId)
		REFERENCES dbo.Roles (RoleId) ON DELETE CASCADE
	ALTER TABLE dbo.Qualification_Role CHECK CONSTRAINT FK_Qualification_Role_Roles
	--Instrumente sind kein Kollektiv Orchester
	Print 'Add Update RoleTypes'
	UPDATE RoleTypes SET RoleTypeCategory = 0 WHERE Module =2 AND RoleTypeCategory = 100 AND Name <> 'Orchester'

	--Farben für Aufgabenbereiche
	UPDATE RoleTypes SET Settings = NULL
	FROM RoleTypes WHERE RoleTypeCategory = 0 AND Module = 1 AND RoleTypeId > 0
		AND (Settings IS NULL OR convert(VARCHAR(MAX),Settings) = '<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackColor><A>0</A><R>0</R><G>0</G><B>0</B></BackColor><ShowEmtyInBudget>true</ShowEmtyInBudget></Settings>')

	UPDATE RoleTypes SET Settings = NULL
	FROM RoleTypes WHERE RoleTypeCategory = 100 AND Module = 1 AND RoleTypeId > 0
		AND (Settings IS NULL OR convert(VARCHAR(MAX),Settings) = '<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackColor><A>0</A><R>0</R><G>0</G><B>0</B></BackColor><ShowEmtyInBudget>true</ShowEmtyInBudget></Settings>')
		
	UPDATE RoleTypes SET Settings = NULL
	FROM RoleTypes WHERE RoleTypeCategory = 110 AND Module = 1 AND RoleTypeId > 0
		AND (Settings IS NULL OR convert(VARCHAR(MAX),Settings) = '<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackColor><A>0</A><R>0</R><G>0</G><B>0</B></BackColor><ShowEmtyInBudget>true</ShowEmtyInBudget></Settings>')

	UPDATE RoleTypes SET Settings = NULL
	FROM RoleTypes WHERE RoleTypeCategory = 120 AND Module = 1 AND RoleTypeId > 0
		AND (Settings IS NULL OR convert(VARCHAR(MAX),Settings) = '<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackColor><A>0</A><R>0</R><G>0</G><B>0</B></BackColor><ShowEmtyInBudget>true</ShowEmtyInBudget></Settings>')
	
	UPDATE RoleTypes SET Settings = NULL
	FROM RoleTypes WHERE RoleTypeCategory = 130 AND Module = 1 AND RoleTypeId > 0
		AND (Settings IS NULL OR convert(VARCHAR(MAX),Settings) = '<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackColor><A>0</A><R>0</R><G>0</G><B>0</B></BackColor><ShowEmtyInBudget>true</ShowEmtyInBudget></Settings>')

END
GO

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

--#region ----------- 4.191.x ---------------------------------

--#region Role_Season für SeasonId 0 entfernen
DELETE FROM Role_Season WHERE SeasonId = 0
GO
--#endregion


--#region bm 20181121 IsVerified für dpe
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('DutyRoster') AND [name] = 'IsVerified')
BEGIN
	PRINT('Adding column DutyRoster.IsVerified ...')
	ALTER TABLE dbo.DutyRoster ADD IsVerified BIT NOT NULL CONSTRAINT DF_DutyRoster_IsVerified DEFAULT 0
END
GO
--#endregion

--#region bm 20181203 Back- and ForeColor für Varianten
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Variants') AND [name] = 'FontFormatXML')
BEGIN
	PRINT('Adding column Variants.FontFormatXML ...')
	ALTER TABLE dbo.Variants ADD FontFormatXML XML NULL
END
GO
--#endregion
--#region 
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.CountDownRoles') AND o.Name = 'IX_CountDownRoles_ResourceObjects_CountDownId_RoleId')
BEGIN
	Print('Create IX_CountDownRoles_ResourceObjects_CountDownId_RoleId')
	DELETE FROM CountDownRoles WHERE CountDownRoleId NOT IN (SELECT MIN(CountDownRoleId) FROM CountDownRoles GROUP BY CountDownId, RoleId)
	CREATE UNIQUE NONCLUSTERED INDEX IX_CountDownRoles_ResourceObjects_CountDownId_RoleId ON CountDownRoles (CountDownId, RoleId) ON [PRIMARY]
END
GO
dropcolumn 'Productions', 'ChorID'
GO
dropcolumn 'Productions', 'OrchID'
--#endregion



--#region 20181022
IF EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'Date' and o.id = OBJECT_ID(N'ActivityHistory') AND c.xtype = 61)
BEGIN
	Print 'ActivityHistory '
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.ActivityHistory') AND o.Name = 'IX_Date') DROP INDEX ActivityHistory.IX_Date
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.ActivityHistory') AND o.Name = 'IX_ActivityHistory_Date') DROP INDEX ActivityHistory.IX_ActivityHistory_Date
	DELETE FROM ActivityHistory WHERE Date IS NULL
	ALTER TABLE ActivityHistory ALTER COLUMN Date DATE NOT NULL
	CREATE NONCLUSTERED INDEX IX_ActivityHistory_Date ON ActivityHistory (Date) ON [PRIMARY]

	UPDATE ActivityHistory SET StartTime = '00:00' WHERE StartTime IS NULL
	UPDATE ActivityHistory SET EndTime = '00:00' WHERE EndTime IS NULL
	UPDATE ActivityHistory SET StartTime = '1900 ' + CONVERT(varchar(5), StartTime, 108) WHERE StartTime <'19000101'
	UPDATE ActivityHistory SET EndTime = '1900 ' + CONVERT(varchar(5), EndTime, 108) WHERE EndTime <'19000101'
	ALTER TABLE ActivityHistory ALTER COLUMN StartTime SMALLDATETIME NOT NULL
	ALTER TABLE ActivityHistory ALTER COLUMN EndTime SMALLDATETIME NOT NULL

	UPDATE ActivityHistory SET ProductionId = 0 WHERE ProductionId IS NULL
	ALTER TABLE ActivityHistory ALTER COLUMN ProductionId INT NOT NULL

	UPDATE ActivityHistory SET LocationId = 0 WHERE LocationId IS NULL
	ALTER TABLE ActivityHistory ALTER COLUMN LocationId INT NOT NULL

	DELETE FROM ActivityHistory  WHERE  ActivityTypeId IS NULL
	ALTER TABLE ActivityHistory ALTER COLUMN ActivityTypeId INT NOT NULL

	ALTER TABLE ActivityHistory ALTER COLUMN ArtisticNote VARCHAR(256) SPARSE NULL

	UPDATE ActivityHistory SET Status = 10 WHERE Status IS NULL
	ALTER TABLE ActivityHistory ALTER COLUMN Status SMALLINT NOT NULL

	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
		WHERE c.name = 'PriceCategoryId' and o.id = OBJECT_ID(N'dbo.ActivityHistory')) ALTER TABLE ActivityHistory DROP COLUMN PriceCategoryId

	DELETE FROM ActivityHistory  WHERE ActivityId IS NULL
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.ActivityHistory') AND o.Name = 'IX_ActivityId') DROP INDEX ActivityHistory.IX_ActivityId
	ALTER TABLE ActivityHistory ALTER COLUMN ActivityId INT NOT NULL
	CREATE NONCLUSTERED INDEX IX_ActivityHistory_ActivityId ON ActivityHistory (ActivityId) ON [PRIMARY]

	UPDATE ActivityHistory SET XHWinUser = '?' WHERE XHWinUser IS NULL
	ALTER TABLE ActivityHistory ALTER COLUMN XHWinUser VARCHAR(128)
		
	UPDATE ActivityHistory SET XHMode = 2  WHERE XHWinUser IS NULL
	ALTER TABLE ActivityHistory ALTER COLUMN XHMode TINYINT NOT NULL

	ALTER TABLE ActivityHistory ALTER COLUMN XHBem VARCHAR(MAX) SPARSE NULL

	UPDATE ActivityHistory SET XHRelevant = 0  WHERE XHRelevant IS NULL
	ALTER TABLE ActivityHistory ALTER COLUMN XHRelevant BIT NOT NULL
	ALTER TABLE ActivityHistory ADD CONSTRAINT DF_ActivityHistory_XHRelevant DEFAULT 0 FOR XHRelevant

	ALTER TABLE ActivityHistory ALTER COLUMN XHInfo VARCHAR(MAX)

	UPDATE ActivityHistory SET IsSecret = a.IsSecret FROM ActivityHistory AS H INNER JOIN Activities AS a on h.ActivityId=a.ActivityId
	UPDATE ActivityHistory SET IsSecret = 0  WHERE IsSecret IS NULL
	ALTER TABLE ActivityHistory ALTER COLUMN IsSecret BIT NOT NULL
	ALTER TABLE ActivityHistory ADD CONSTRAINT DF_ActivityHistory_IsSecret DEFAULT 0 FOR IsSecret
	
	UPDATE ActivityHistory SET VariantId = 0  WHERE VariantId IS NULL
	ALTER TABLE ActivityHistory ALTER COLUMN VariantId INT NOT NULL 
	ALTER TABLE ActivityHistory ADD CONSTRAINT DF_ActivityHistory_VariantId DEFAULT 0 FOR VariantId

	Exec ('UPDATE ActivityHistory SET LC = XHTime  WHERE LC IS NULL AND  NOT XHTime IS NULL')
	UPDATE ActivityHistory SET LC = '19000101'  WHERE LC IS NULL
	UPDATE ActivityHistory SET LM = LC  WHERE LM IS NULL

	ALTER TABLE ActivityHistory ALTER COLUMN LC DATETIME NOT NULL
	ALTER TABLE ActivityHistory ALTER COLUMN LM DATETIME NOT NULL

	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'XHDbUser' and o.id = OBJECT_ID(N'dbo.ActivityHistory')) ALTER TABLE ActivityHistory DROP COLUMN XHDbUser
	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'XHTime' and o.id = OBJECT_ID(N'dbo.ActivityHistory')) ALTER TABLE ActivityHistory DROP COLUMN XHTime

	ALTER TABLE ActivityHistory ADD ProductionOwnerGroupId INT NULL
	Exec ('UPDATE ActivityHistory SET ProductionOwnerGroupId = s.OwnerGroupId FROM ActivityHistory AS H INNER JOIN Activities AS a on h.ActivityId=a.ActivityId INNER JOIN Productions AS s on a.ProductionId = s.ProductionId')
	Exec ('UPDATE ActivityHistory SET ProductionOwnerGroupId = s.OwnerGroupId FROM ActivityHistory AS H INNER JOIN Productions AS s on h.ProductionId = s.ProductionId WHERE ProductionOwnerGroupId IS NULL')
	Exec ('UPDATE ActivityHistory SET ProductionOwnerGroupId = 1 WHERE ProductionOwnerGroupId IS NULL')
	ALTER TABLE ActivityHistory ALTER COLUMN ProductionOwnerGroupId INT NOT NULL 
END
GO
IF NOT EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'IsActivitySecret' and o.id = OBJECT_ID(N'CastHistory'))
BEGIN
	Print 'CastHistory '

	DELETE FROM CastHistory WHERE Date IS NULL
	ALTER TABLE CastHistory ALTER COLUMN Date DATE NOT NULL

	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'DiffVon' and o.id = OBJECT_ID(N'dbo.CastHistory')) ALTER TABLE CastHistory DROP COLUMN DiffVon
	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'DiffBis' and o.id = OBJECT_ID(N'dbo.CastHistory')) ALTER TABLE CastHistory DROP COLUMN DiffBis
	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'NoCount' and o.id = OBJECT_ID(N'dbo.CastHistory')) ALTER TABLE CastHistory DROP COLUMN NoCount
	UPDATE CastHistory SET ProductionId = 0 WHERE ProductionId IS NULL
	ALTER TABLE CastHistory ALTER COLUMN ProductionId INT NOT NULL

	UPDATE CastHistory SET RoleId = 0 WHERE RoleId IS NULL
	ALTER TABLE CastHistory ALTER COLUMN RoleId INT NOT NULL

	UPDATE CastHistory SET ActivityId = 0 WHERE ActivityId IS NULL
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.CastHistory') AND o.Name = 'IX_ActivityId') DROP INDEX CastHistory.IX_ActivityId
	ALTER TABLE CastHistory ALTER COLUMN ActivityId INT NOT NULL
	IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.CastHistory') AND o.Name = 'IX_CastHistory_ActivityId') CREATE NONCLUSTERED INDEX IX_CastHistory_ActivityId ON CastHistory (ActivityId) ON [PRIMARY]
	
	UPDATE CastHistory SET PersonId = 0 WHERE PersonId IS NULL
	ALTER TABLE CastHistory ALTER COLUMN PersonId INT NOT NULL

	UPDATE CastHistory SET CastId = 0 WHERE CastId IS NULL
	ALTER TABLE CastHistory ALTER COLUMN CastId INT NOT NULL

	UPDATE CastHistory SET LocationId = 0 WHERE LocationId IS NULL
	ALTER TABLE CastHistory ALTER COLUMN LocationId INT NOT NULL

	ALTER TABLE CastHistory ALTER COLUMN Note VARCHAR(256) SPARSE NULL
	
	UPDATE CastHistory SET XHWinUser = '?' WHERE XHWinUser IS NULL
	ALTER TABLE CastHistory ALTER COLUMN XHWinUser VARCHAR(128)
		
	UPDATE CastHistory SET XHMode = 2  WHERE XHWinUser IS NULL
	ALTER TABLE CastHistory ALTER COLUMN XHMode TINYINT NOT NULL

	ALTER TABLE CastHistory ALTER COLUMN XHBem VARCHAR(MAX) SPARSE NULL

	UPDATE CastHistory SET XHRelevant = 0  WHERE XHRelevant IS NULL
	ALTER TABLE CastHistory ALTER COLUMN XHRelevant BIT NOT NULL
	ALTER TABLE CastHistory ADD CONSTRAINT DF_CastHistory_XHRelevant DEFAULT 0 FOR XHRelevant

	UPDATE CastHistory SET IsSecret = c.IsSecret FROM CastHistory AS H INNER JOIN Cast AS c on h.CastId = c.CastId
	UPDATE CastHistory SET IsSecret = 0  WHERE IsSecret IS NULL
	ALTER TABLE CastHistory ALTER COLUMN IsSecret BIT NOT NULL
	
	Exec('UPDATE CastHistory SET LC = XHTime  WHERE LC IS NULL AND  NOT XHTime IS NULL')
	UPDATE CastHistory SET LC = '19000101'  WHERE LC IS NULL
	UPDATE CastHistory SET LM = LC  WHERE LM IS NULL

	ALTER TABLE CastHistory ALTER COLUMN LC DATETIME NOT NULL
	ALTER TABLE CastHistory ALTER COLUMN LM DATETIME NOT NULL

	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'XHDbUser' and o.id = OBJECT_ID(N'dbo.CastHistory')) ALTER TABLE CastHistory DROP COLUMN XHDbUser
	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'XHTime' and o.id = OBJECT_ID(N'dbo.CastHistory')) ALTER TABLE CastHistory DROP COLUMN XHTime

	ALTER TABLE CastHistory ADD ActivityCategoryId INT NULL
	Exec('UPDATE CastHistory SET ActivityCategoryId = a.ActivityTypeId FROM CastHistory AS H INNER JOIN Activities AS a on h.ActivityId=a.ActivityId ')
	Exec('UPDATE CastHistory SET ActivityCategoryId = a.ActivityTypeId FROM CastHistory AS H INNER JOIN ActivityHistory AS a on h.ActivityId=a.ActivityId  WHERE ActivityCategoryId IS NULL')
	Exec('UPDATE CastHistory SET ActivityCategoryId = 0 WHERE ActivityCategoryId IS NULL')
	ALTER TABLE CastHistory ALTER COLUMN ActivityCategoryId INT NOT NULL 
	
	ALTER TABLE CastHistory ADD ProductionOwnerGroupId INT NULL
	Exec('UPDATE CastHistory SET ProductionOwnerGroupId = s.OwnerGroupId FROM CastHistory AS H INNER JOIN Productions AS s on h.ProductionId=s.ProductionId ')
	Exec('UPDATE CastHistory SET ProductionOwnerGroupId = 1 WHERE ProductionOwnerGroupId IS NULL')
	ALTER TABLE CastHistory ALTER COLUMN ProductionOwnerGroupId INT NOT NULL 

	ALTER TABLE CastHistory ADD RoleOwnerGroupId INT NULL
	Exec('UPDATE CastHistory SET RoleOwnerGroupId = r.OwnerGroupId FROM CastHistory AS H INNER JOIN Roles AS r on h.RoleId=r.RoleId ')
	Exec('UPDATE CastHistory SET RoleOwnerGroupId = s.OwnerGroupId FROM CastHistory AS H INNER JOIN Productions AS s on h.ProductionId = s.ProductionId WHERE h.RoleOwnerGroupId IS NULL')
	Exec('UPDATE CastHistory SET RoleOwnerGroupId = 1 WHERE RoleOwnerGroupId IS NULL')
	ALTER TABLE CastHistory ALTER COLUMN RoleOwnerGroupId INT NOT NULL 

	ALTER TABLE CastHistory ADD IsActivitySecret BIT NULL
	Exec('UPDATE CastHistory SET IsActivitySecret = a.IsSecret FROM CastHistory AS H INNER JOIN Activities AS a on h.ActivityId=a.ActivityId ')
	Exec('UPDATE CastHistory SET IsActivitySecret = a.IsSecret FROM CastHistory AS H INNER JOIN ActivityHistory AS a on h.ActivityId=a.ActivityId  WHERE h.IsActivitySecret IS NULL')
	Exec('UPDATE CastHistory SET IsActivitySecret = 0 WHERE IsActivitySecret IS NULL')
	ALTER TABLE CastHistory ALTER COLUMN IsActivitySecret BIT NOT NULL 

	CREATE NONCLUSTERED INDEX IX_CastHistory_Date ON CastHistory (Date) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IX_CastHistory_CastId ON CastHistory (CastId) ON [PRIMARY]
END

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'DbUser' and o.id = OBJECT_ID(N'dbo.HistoryConfirmations'))
BEGIN
	ALTER TABLE HistoryConfirmations DROP COLUMN DbUser
	ALTER TABLE HistoryConfirmations DROP COLUMN WinUser
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.HistoryConfirmations') AND o.Name = 'IX_UC_Tabl') DROP INDEX HistoryConfirmations.IX_UC_Tabl
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.HistoryConfirmations') AND o.Name = 'IX_XHID') DROP INDEX HistoryConfirmations.IX_XHID
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.HistoryConfirmations') AND o.Name = 'PK_HistoryConfirmations') 	ALTER TABLE dbo.HistoryConfirmations	DROP CONSTRAINT PK_HistoryConfirmations 

	Exec('UPDATE HistoryConfirmations SET LC = ViewTime  WHERE LC IS NULL AND  NOT ViewTime IS NULL')
	UPDATE HistoryConfirmations SET LC = '19000101'  WHERE LC IS NULL
	UPDATE HistoryConfirmations SET LM = LC  WHERE LM IS NULL
	ALTER TABLE HistoryConfirmations ALTER COLUMN LC DATETIME NOT NULL
	ALTER TABLE HistoryConfirmations ALTER COLUMN LM DATETIME NOT NULL
	ALTER TABLE HistoryConfirmations DROP COLUMN ViewTime
	ALTER TABLE HistoryConfirmations ALTER COLUMN TableName VARCHAR(32) NOT NULL
	DELETE FROM HistoryConfirmations WHERE UC IS NULL
	ALTER TABLE HistoryConfirmations ALTER COLUMN UC INT NOT NULL
	
	DELETE FROM HistoryConfirmations WHERE HistoryConfirmationId NOT IN (SELECT MIN(HistoryConfirmationId) FROM HistoryConfirmations GROUP BY TableName, UC, XHID)
	CREATE UNIQUE CLUSTERED INDEX IX_HistoryConfirmations_Teble_UserId_XHID ON HistoryConfirmations (TableName, UC, XHID) ON [PRIMARY]

	ALTER TABLE HistoryConfirmations ADD CONSTRAINT PK_HistoryConfirmations PRIMARY KEY (HistoryConfirmationId) ON [PRIMARY]
END


IF EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'StartDate' and o.id = OBJECT_ID(N'Seasons') AND c.xtype = 61)
BEGIN
	Print 'Seasons '
	ALTER TABLE Seasons ALTER COLUMN StartDate DATE NOT NULL
	ALTER TABLE Seasons ALTER COLUMN EndDate DATE NOT NULL
END
go
IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_Seasons_Ausgelagert') ALTER TABLE Seasons DROP CONSTRAINT DF_Seasons_Ausgelagert
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'Ausgelagert' and o.id = OBJECT_ID(N'dbo.Seasons')) ALTER TABLE Seasons DROP COLUMN Ausgelagert

IF EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'StartDate' and o.id = OBJECT_ID(N'Variants') AND c.xtype = 61)
BEGIN
	Print 'Variants '
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.Variants') AND o.Name = 'IX_Variants_Code_StartDate_Enddate') DROP INDEX Variants.IX_Variants_Code_StartDate_Enddate
	ALTER TABLE Variants ALTER COLUMN StartDate DATE NULL
	ALTER TABLE Variants ALTER COLUMN EndDate DATE NULL
	ALTER TABLE Variants ADD FontFormatString XML NULL
	CREATE UNIQUE NONCLUSTERED INDEX IX_Variants_Code_StartDate_EndDate ON Variants (Code, StartDate, EndDate) ON [PRIMARY]
END
GO

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[GetActivityHistoryInternal]'))	DROP PROCEDURE dbo.[GetActivityHistoryInternal] 
GO
CREATE PROCEDURE [dbo].[GetActivityHistoryInternal]
	@start DATE, @end DATE,
	@condition VARCHAR(MAX),
	@joins INT,
	@ShowOld BIT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN	
	SET NOCOUNT ON
	DECLARE @SQLQuery AS NVARCHAR(MAX)
	DECLARE @permissionPeriodStart DATE
	DECLARE @permissionPeriodEnd DATE
	DECLARE @UserIsString AS NVARCHAR(20)
	SET @UserIsString = CONVERT(VARCHAR(20), @Userid)

	-- *** Spielzeitberechtigungen prüfen ***
	SELECT @permissionPeriodStart = MIN(s.StartDate), @permissionPeriodEnd = MAX(s.EndDate)
		FROM Seasons AS s
			INNER JOIN SeasonPermissions AS us	ON s.SeasonId = us.SeasonId
		WHERE us.UserId = @userId 

	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
		
	SET @SQLQuery = 'SELECT a.*
						FROM ActivityHistory AS a
							INNER JOIN Permissions AS ug ON a.ProductionOwnerGroupId = ug.OwnerGroupId 
											AND ug.UserId = '+ @UserIsString+'
											AND ug.PermissionArea = 2 '

	IF (@ShowOld = 0)
		SET @SQLQuery = @SQLQuery + ' LEFT JOIN (SELECT xhid FROM HistoryConfirmations WHERE TableName = ''Activities'' AND UC = '+ @UserIsString +') AS d ON a.xhID = d.xhid '

	IF (@joins&1 = 1)
		SET @SQLQuery = @SQLQuery + ' INNER JOIN Productions AS p ON p.ProductionId = a.ProductionId '

	SET @SQLQuery = @SQLQuery + ' WHERE a.Date BETWEEN ''' + CAST(@start AS VARCHAR(MAX)) + '''  AND ''' + CAST(@end AS VARCHAR(MAX)) + '''
										AND (a.IsSecret = 0 OR ug.OptionsFlag IS NULL OR ug.OptionsFlag & 1 = 1)'

	IF (@ShowOld = 0)
		SET @SQLQuery = @SQLQuery + ' AND d.xhId IS NULL'

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

	SET @SQLQuery = @SQLQuery + ' ORDER BY a.LC'
	
	EXECUTE sp_Executesql  @SQLQuery
END
GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetActivityHistory'))	DROP PROCEDURE dbo.GetActivityHistory 
GO

CREATE PROCEDURE dbo.GetActivityHistory
	@start DATE,
	@end DATE,
	@condition VARCHAR(MAX),
	@joins INT,
	@ShowOld BIT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
	EXECUTE GetActivityHistoryInternal @start, @end, @condition,@joins, @ShowOld, @userId
END
GO
GRANT EXECUTE ON dbo.GetActivityHistory TO PUBLIC
GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetCastHistoryInternal'))	DROP PROCEDURE dbo.GetCastHistoryInternal
GO
CREATE PROCEDURE dbo.GetCastHistoryInternal
	@start DATE, @end DATE,
	@condition VARCHAR(MAX),
	@joins INT,
	@ShowOld BIT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN	
	SET NOCOUNT ON
	DECLARE @SQLQuery AS NVARCHAR(MAX)
	DECLARE @permissionPeriodStart DATE
	DECLARE @permissionPeriodEnd DATE
	DECLARE @UserIsString AS NVARCHAR(20)
	SET @UserIsString = CONVERT(VARCHAR(20), @Userid)
	-- *** Spielzeitberechtigungen prüfen ***
	SELECT @permissionPeriodStart = MIN(s.StartDate), @permissionPeriodEnd = MAX(s.EndDate)
		FROM Seasons AS s
			INNER JOIN SeasonPermissions AS us	ON s.SeasonId = us.SeasonId
		WHERE us.UserId = @userId

	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
		
	SET @SQLQuery = 'SELECT c.*
						FROM CastHistory AS c
							INNER JOIN (SELECT * FROM Permissions WHERE UserId = ' + @UserIsString +' AND PermissionArea = 2) AS ugActi ON c.ProductionOwnerGroupId = ugActi.OwnerGroupId
							INNER JOIN (SELECT * FROM Permissions WHERE UserId = ' + @UserIsString +' AND PermissionArea = 4) AS ugCast ON c.RoleOwnerGroupId = ugCast.OwnerGroupId '

	IF (@ShowOld = 0)
		SET @SQLQuery = @SQLQuery + ' LEFT JOIN (SELECT xhid FROM HistoryConfirmations WHERE TableName = ''Cast'' AND UC =  '+  @UserIsString +') AS d ON c.xhID = d.xhid' 

	IF (@joins&1 = 1)
		SET @SQLQuery = @SQLQuery + ' INNER JOIN Roles AS r ON c.RoleId = r.Id '

	IF (@joins&2 = 2)
		SET @SQLQuery = @SQLQuery + ' INNER JOIN Productions AS p ON c.ProductionId = p.ProductionId '

	SET @SQLQuery = @SQLQuery + ' WHERE c.Date BETWEEN ''' + CAST(@start AS VARCHAR(MAX)) + '''  AND ''' + CAST(@end AS VARCHAR(MAX)) + '''
									AND (c.IsActivitySecret = 0 OR ugActi.OptionsFlag IS NULL OR ugActi.OptionsFlag & 1 = 1)
									AND (c.IsSecret = 0			 OR ugCast.OptionsFlag IS NULL OR ugCast.OptionsFlag & 1 = 1)'
	IF (@ShowOld = 0) 
		SET @SQLQuery = @SQLQuery + 'AND d.xhId IS NULL'

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

	SET @SQLQuery = @SQLQuery + ' ORDER BY c.LC'
	
	EXECUTE sp_Executesql  @SQLQuery
END
GO

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetCastHistory'))	DROP PROCEDURE dbo.GetCastHistory 
GO
CREATE PROCEDURE dbo.GetCastHistory
	@start DATE,	@end DATE,
	@condition VARCHAR(MAX),
	@joins INT,
	@ShowOld BIT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
	EXECUTE GetCastHistoryInternal @start, @end, @condition ,@joins, @ShowOld, @userId
END
GO
GRANT EXECUTE ON dbo.GetCastHistory TO PUBLIC
GO

IF OBJECT_ID ('TR_Update_Activity', 'TR') IS NOT NULL DROP TRIGGER TR_Update_Activity
GO
CREATE TRIGGER dbo.TR_Update_Activity ON dbo.Activities AFTER UPDATE
		AS 
	SET NOCOUNT ON
	IF UPDATE(IsSecret)
	BEGIN
		UPDATE ActivityHistory SET ActivityHistory.IsSecret = ins.IsSecret FROM ActivityHistory AS xh JOIN  INSERTED AS ins ON xh.ActivityId = ins.ActivityId
		UPDATE CastHistory SET CastHistory.IsActivitySecret= ins.IsSecret FROM ActivityHistory AS X JOIN INSERTED AS ins ON x.ActivityId = ins.ActivityId
	END
GO
IF OBJECT_ID ('TR_Update_Cast', 'TR') IS NOT NULL DROP TRIGGER TR_Update_Cast
GO
CREATE TRIGGER dbo.TR_Update_Cast ON dbo.Cast AFTER UPDATE
		AS
	SET NOCOUNT ON
	IF UPDATE(IsSecret)
	BEGIN
		UPDATE CastHistory SET CastHistory.IsSecret = ins.IsSecret FROM CastHistory AS X JOIN INSERTED AS ins ON x.CastId = ins.CastId
	END

GO
DropRoleWithDropRoleMember'KostümDatenlesen'
GO
DropRoleWithDropRoleMember 'KostümDatenSchreiben'
GO
DropRoleWithDropRoleMember 'ContractTrackingRead'
GO
DropRoleWithDropRoleMember 'ContractTrackingWrite'
GO
DropRoleWithDropRoleMember 'Kontaktdaten ändern'
GO
DropRoleWithDropRoleMember 'Kontaktdaten lesen'
GO
DropRoleWithDropRoleMember 'PersoContractWrite'
GO
DropRoleWithDropRoleMember 'PersoWorkContractWrite'
GO
DropRoleWithDropRoleMember 'Presse ändern'
GO
DropRoleWithDropRoleMember 'Soli-Daten ändern'
GO
DropRoleWithDropRoleMember 'Soli-Daten lesen'
GO
DropRoleWithDropRoleMember 'Soli Urlaub L'
GO
DropRoleWithDropRoleMember 'TheaOrchesterlesen'
GO
DropRoleWithDropRoleMember 'UrlaubSchreiben'
GO
DropRoleWithDropRoleMember 'Honorar-Daten ändern'
GO
DropRoleWithDropRoleMember 'Honorar-Daten lesen'
GO
DropRoleWithDropRoleMember 'PersoPublic'
GO
DropRoleWithDropRoleMember 'PersoCloseWrite'
GO
DropRoleWithDropRoleMember 'SpielplanTeileÄndern'
GO
DropRoleWithDropRoleMember 'Standardbes ändern'
GO
DropRoleWithDropRoleMember 'Spielplan ändern'
GO
DropRoleWithDropRoleMember 'Spielplan alles lesen'
GO
DropRoleWithDropRoleMember 'RepertoireLesen'
GO
DropRoleWithDropRoleMember 'RepertoireSchreiben'

--#endregion
--#region 2018-11-15

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonMemo_Persons') AND type = 'F') 
	ALTER TABLE dbo.PersonMemo	DROP CONSTRAINT FK_PersonMemo_Persons

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonMemo_Persons') AND type = 'F') 
BEGIN
	DELETE FROM PersonMemo  WHERE PersonId NOT IN (SELECT PersonId FROM Persons)
		Print ('create FK_PersonMemo_Persons')
	ALTER TABLE dbo.PersonMemo WITH CHECK ADD CONSTRAINT FK_PersonMemo_Persons FOREIGN KEY(PersonId)
		REFERENCES dbo.Persons (PersonId) ON DELETE CASCADE
	ALTER TABLE dbo.PersonMemo CHECK CONSTRAINT FK_PersonMemo_Persons
END

IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersonMemo') AND o.Name = 'IX_PersonalNotes_PersonId')
	 DROP INDEX PersonMemo.IX_PersonalNotes_PersonId

--#endregion
--#region 2018-11-20
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.PersonAdditionalDataTypes'))
BEGIN
PRINT 'PersonAdditionalDataTypes IsInactive'
	ALTER TABLE PersonAdditionalDataTypes ADD IsInactive INT  NOT NULL CONSTRAINT DF_PersonAdditionalDataTypes_IsInactive DEFAULT 0
	UPDATE PersonAdditionalDataTypes SET OwnerGroupId = 1 WHERE OwnerGroupId NOT IN (SELECT OwnerGroupId FROM OwnerGroups)
	UPDATE PersonAdditionalDataTypes SET OwnerGroupId = 1 WHERE OwnerGroupId IS NULL
	ALTER TABLE PersonAdditionalDataTypes ALTER COLUMN OwnerGroupId INT NOT NULL

	ALTER TABLE dbo.PersonAdditionalDataTypes WITH CHECK ADD CONSTRAINT FK_PersonAdditionalDataTypes_OwnerGroups FOREIGN KEY(OwnerGroupId)
		REFERENCES dbo.OwnerGroups (OwnerGroupId) 
	ALTER TABLE dbo.PersonAdditionalDataTypes CHECK CONSTRAINT FK_PersonAdditionalDataTypes_OwnerGroups
END
GO
IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.DailyScheduleSections') AND o.Name = 'PK_BezKurz')
	DROP INDEX DailyScheduleSections.PK_BezKurz
GO
DropColumn 'DailyScheduleSections', 'BezKurz'
GO
IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersonCategories') AND o.Name = 'zaehler')
	DROP INDEX PersonCategories.zaehler
GO

IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.DutyRoster') AND o.Name = 'IX_DutyRoster_DateArtContract')
	DROP INDEX DutyRoster.IX_DutyRoster_DateArtContract

GO
IF EXISTS (SELECT * FROM  sysColumns o WHERE  o.id = OBJECT_ID(N'dbo.DutyRoster') AND o.Name = 'Date' AND Isnullable = 1)
BEGIN
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.DutyRoster') AND o.Name = 'IX_DutyRoster_Date')
		 DROP INDEX DutyRoster.IX_DutyRoster_Date
	DELETE FROM DutyRoster WHERE Date IS NULL
	ALTER TABLE DutyRoster ALTER COLUMN Date DATE NOT NULL
END
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.DutyRoster') AND o.Name = 'IX_DutyRoster_ArtContractDate')
	CREATE UNIQUE CLUSTERED INDEX IX_DutyRoster_ArtContractDate ON dbo.DutyRoster (DutyRosterTypeId, ContractId, Date)

IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.DutyRoster') AND o.Name = 'IX_DutyRoster_Date')
	CREATE INDEX IX_DutyRoster_Date ON dbo.DutyRoster (Date)
GO
IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.DutyRoster') AND o.Name = 'iVertragsNr')
	DROP INDEX DutyRoster.iVertragsNr
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.DutyRoster') AND o.Name = 'IX_DutyRoster_Contract')
	CREATE INDEX IX_DutyRoster_Contract ON dbo.DutyRoster (ContractId)
GO
--#endregion
--#region
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'OvernightCostsPerformance' and o.id = OBJECT_ID(N'SeasonOwnerGroupSettings'))
BEGIN
	Print 'SeasonOwnerGroupSettings TravelCostsPerformance OvernightCostsFlat OvernightCostsPerformance'
	ALTER TABLE SeasonOwnerGroupSettings Add TravelCostsPerformance MONEY NOT NULL CONSTRAINT DF_SeasonOwnerGroupSettings_TravelCostsPerformance DEFAULT 0
	ALTER TABLE SeasonOwnerGroupSettings Add OvernightCostsFlat MONEY NOT NULL CONSTRAINT DF_SeasonOwnerGroupSettings_OvernightCostsFlat DEFAULT 0
	ALTER TABLE SeasonOwnerGroupSettings Add OvernightCostsPerformance MONEY NOT NULL CONSTRAINT DF_SeasonOwnerGroupSettings_OvernightCostsPerformance DEFAULT 0
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'RehearsalFeeFlat' and o.id = OBJECT_ID(N'Role_Season'))
BEGIN
	Print 'Role_Season RehearsalFeeFlat'
	ALTER TABLE Role_Season Add RehearsalFeeFlat MONEY NULL
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CalculationDate' and o.id = OBJECT_ID(N'ProductionCosts'))
BEGIN
	Print 'ProductionCosts CalculationDate'
	ALTER TABLE ProductionCosts ADD CalculationDate DATE NULL
	EXEC ('INSERT INTO ProductionCosts (ProductionCostTypeId,ProductionId,ProjectedCosts,LM,UM,LC,UC,ContractEngagementId,CalculationValue,Note,CalculationDate)
	SELECT ProductionCostTypeId,c.ProductionId,ProjectedCosts,c.LM,c.UM,c.LC,c.UC,ContractEngagementId,CalculationValue,Note,s.StartDate 
	FROM ProductionCosts c 
		INNER JOIN ProductionInSeasons p ON c.ProductionId = p.ProductionId 
		INNER JOIN Seasons s ON p.SeasonId = s.SeasonId 
	WHERE p.OnlyRehersals = 0')
	EXEC ('DELETE FROM ProductionCosts WHERE CalculationDate IS NULL')
	ALTER TABLE ProductionCosts ALTER COLUMN CalculationDate DATE NOT NULL

	DELETE FROM ProductionCosts WHERE ProductionCostTypeId IS NULL
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.ProductionCosts') AND o.Name = 'IX_KostenID')
		DROP INDEX ProductionCosts.IX_KostenID
	ALTER TABLE ProductionCosts ALTER COLUMN ProductionCostTypeId INT NOT NULL

	DELETE FROM ProductionCosts WHERE ProductionId NOT IN (SELECT ProductionId FROM Productions)

	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.ProductionCosts') AND o.Name = 'IX_Snr')
		DROP INDEX ProductionCosts.IX_Snr
	ALTER TABLE ProductionCosts ALTER COLUMN ProductionId INT NOT NULL

	IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.ProductionCosts') AND o.Name = 'IX_ProductionCosts_ProductionCalculationDate')
		EXEC ('CREATE INDEX IX_ProductionCosts_ProductionCalculationDate ON dbo.ProductionCosts (ProductionId, CalculationDate)')

	ALTER TABLE dbo.ProductionCosts  WITH CHECK ADD  CONSTRAINT FK_ProductionCosts_Productions FOREIGN KEY(ProductionId)
		REFERENCES dbo.Productions (ProductionId) ON DELETE CASCADE
	ALTER TABLE dbo.ProductionCosts CHECK CONSTRAINT FK_ProductionCosts_Productions
END
GO
DropDefaultConstraint 'ProductionCostTypes' , 'IsProPerformance'
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CostTypeId' and o.id = OBJECT_ID(N'ProductionCostTypes'))
BEGIN
	ALTER TABLE ProductionCostTypes Add CostTypeId INT NULL
	ALTER TABLE dbo.ProductionCostTypes  WITH CHECK ADD  CONSTRAINT FK_ProductionCostTypes_CostTypes FOREIGN KEY(CostTypeId)
		REFERENCES dbo. CostTypes (CostTypeId) ON DELETE CASCADE
	ALTER TABLE dbo.ProductionCostTypes CHECK CONSTRAINT FK_ProductionCostTypes_CostTypes
	
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.ProductionCostTypes') AND o.Name = 'UQ_Kosten_KostenBez')
		DROP INDEX ProductionCostTypes.UQ_Kosten_KostenBez

	UPDATE ProductionCostTypes SET Name = '--' WHERE Name IS NULL
	ALTER TABLE ProductionCostTypes ALTER COLUMN Name VARCHAR(50) NOT NULL
	EXECUTE PrepareUniqueColumnIndex N'ProductionCostTypes',N'Name',N'ProductionCostTypeId',N'VARCHAR(50)'
	CREATE UNIQUE NONCLUSTERED INDEX UQ_CostType_Name ON ProductionCostTypes (Name) ON [PRIMARY]

	UPDATE ProductionCostTypes SET IsIncome = 1 WHERE IsIncome IS NULL
	ALTER TABLE ProductionCostTypes ALTER COLUMN IsIncome SMALLINT NOT NULL
	ALTER TABLE ProductionCostTypes ADD CONSTRAINT DF_ProductionCostTypes_IsIncome DEFAULT 1 FOR IsIncome

	ALTER TABLE ProductionCostTypes ALTER COLUMN IsProPerformance TINYINT NOT NULL
	ALTER TABLE ProductionCostTypes ADD CONSTRAINT DF_ProductionCostTypes_IsProPerformance DEFAULT 1 FOR IsProPerformance
END
GO
dropcolumn 'ProductionCostTypes_Stück', 'BetragIst'
GO
dropcolumn 'ProductionCostTypes', 'KontoNr'
GO
--#endregion
--#region 20181212
IF  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ZeichenVor' and o.id = OBJECT_ID(N'PlanLayoutContent'))
BEGIN
	Print 'PlanLayoutContent Statusfilter'
	UPDATE PlanLayoutContent SET ContentSettings = Convert(XML, Replace(Convert(VARCHAR(max),  ContentSettings),' &lt;Status /&gt;','    &lt;Status&gt;
		  &lt;eStatusStatus&gt;approved&lt;/eStatusStatus&gt;
		  &lt;eStatusStatus&gt;inquiry&lt;/eStatusStatus&gt;
		  &lt;eStatusStatus&gt;request&lt;/eStatusStatus&gt;
		  &lt;eStatusStatus&gt;absent&lt;/eStatusStatus&gt;
		&lt;/Status&gt;')) 
	FROM PlanLayoutContent ps
		INNER JOIN PlanColumns sp ON ps.SpalteID = sp.SpalteID
		INNER JOIN [plan] p ON sp.PlanLayoutId = p.PlanLayoutId
	WHERE PlanLayoutType  IN (30, 120, 130, 160) 
	AND NOT ContentSettings IS NULL
	AND CONVERT(VARCHAR(max), ContentSettings) LIKE '%PersStatusListConverterFieldSettings%'
	AND CONVERT(VARCHAR(max), ContentSettings) LIKE '%&lt;Status /&gt;%'

	DELETE  Role_Season WHERE (Note IS NULL AND RoleNotNeeded = 0 AND Fee IS NULL AND OvernightFeeFlat IS NULL AND TravelFeeFlat IS NULL AND OvernightFeePerformance IS NULL 
							AND TravelFeePerformance IS NULL AND (EnsembleCount = 0 OR EnsembleCount IS NULL ) AND FeeNote IS NULL AND RehearsalFeeFlat IS NULL) OR SeasonId = 0

	ALTER TABLE PlanLayoutContent DROP COLUMN ZeichenVor
END

GO
--#endregion
--#region
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.AdressSort') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)		DROP TABLE AdressSort
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.AdressSpalte') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE AdressSpalte
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.AdressPlan') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)		DROP TABLE AdressPlan
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.AdressAusgabe') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE AdressAusgabe
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.AdressAuswahlPersKat') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)DROP TABLE AdressAuswahlPersKat
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.AblagePfade') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE AblagePfade
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.PlanText') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)		DROP TABLE PlanText
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.BlockedCostTypes') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)DROP TABLE BlockedCostTypes

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.RoleConnection') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE RoleConnection
exec dropcolumn 'PersoParameter', 'TBZFt'
exec dropcolumn 'PersoParameter', 'TBZUrlKrk'
exec dropcolumn 'Roles', 'StdPro'
GO
DropColumn 'Roles', 'Cover'

IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbAgenturAP'))			DROP VIEW dbo.AbAgenturAP
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbAgentur'))				DROP VIEW dbo.AbAgentur
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbPersAdressKom'))				DROP VIEW dbo.AbPersAdressKom
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbVstNrproZr'))			DROP PROCEDURE dbo.AbVstNrproZr
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbVstNr'))				DROP PROCEDURE dbo.AbVstNr
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbBesetzung'))			DROP PROCEDURE dbo.AbBesetzung
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.update_AblagePfade_1'))	DROP PROCEDURE dbo.update_AblagePfade_1
--#endregion

--#region SH 2018-12-20 Spalte IsExportable in Tabelle ProductionFieldTypes
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ProductionFieldTypes') AND [name] = 'IsExportable')
BEGIN
	PRINT('Adding column ProductionFieldTypes.IsExportable ...')
	ALTER TABLE dbo.ProductionFieldTypes ADD IsExportable BIT NOT NULL CONSTRAINT DF_ProductionFieldTypes_IsExportable DEFAULT 0

	--daten die beim konvertieren erstellt wurde, auf exportierbar stellen
	EXEC ('UPDATE ProductionFieldTypes SET IsExportable = 1 WHERE UM = -1')
END
GO
--#endregion



--#endregion (4.191.x)

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

--#region 2019-01-25 sh Alte Select Berechtigungen auf TimeAccountMonthValues entfernen
REVOKE SELECT ON [dbo].[TimeAccountMonthValues] TO [PersoAdmin] AS [dbo]
GO

REVOKE SELECT ON [dbo].[TimeAccountMonthValues] TO [public] AS [dbo]
GO
--#endregion

--#region 2019-01-25 sh Spalte KnownUserType in Tabelle Users
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Users') AND [name] = 'KnownUserType')
BEGIN
	PRINT('Adding column Users.KnownUserType ...')
	ALTER TABLE dbo.Users ADD KnownUserType TINYINT NULL
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysindexes o WHERE o.id = OBJECT_ID(N'[dbo].[Users]') AND o.Name = N'UX_KnownUserType')
BEGIN
	PRINT('Adding unique index for Users.KnownUserType ...')
	EXEC('CREATE UNIQUE NONCLUSTERED INDEX UX_KnownUserType ON dbo.Users(KnownUserType) WHERE KnownUserType IS NOT NULL ON [PRIMARY]')
END
GO
--#endregion

--#region Aufbabenbereichsfarbe
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 191 OR (Minor=191 AND Build < 102)))))
BEGIN
	PRINT('Setting task area colors...')
	--Farben für Aufgabenbereiche
	UPDATE RoleTypes SET Settings = '<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackColor><A>255</A><R>125</R><G>168</G><B>217</B></BackColor><ShowEmtyInBudget>true</ShowEmtyInBudget></Settings>'
	FROM RoleTypes WHERE RoleTypeCategory = 0 AND Module = 1 AND RoleTypeId > 0 AND Settings IS NULL

	UPDATE RoleTypes SET Settings = '<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackColor><A>255</A><R>0</R><G>0</G><B>255</B></BackColor><ShowEmtyInBudget>true</ShowEmtyInBudget></Settings>'
	FROM RoleTypes WHERE RoleTypeCategory = 100 AND Module = 1 AND RoleTypeId > 0 AND Settings IS NULL
		
	UPDATE RoleTypes SET Settings = '<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackColor><A>255</A><R>255</R><G>242</G><B>0</B></BackColor><ShowEmtyInBudget>true</ShowEmtyInBudget></Settings>'
	FROM RoleTypes WHERE RoleTypeCategory = 110 AND Module = 1 AND RoleTypeId > 0 AND Settings IS NULL

	UPDATE RoleTypes SET Settings = '<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackColor><A>255</A><R>0</R><G>166</G><B>81</B></BackColor><ShowEmtyInBudget>true</ShowEmtyInBudget></Settings>'
	FROM RoleTypes WHERE RoleTypeCategory = 120 AND Module = 1 AND RoleTypeId > 0 AND Settings IS NULL
		
	UPDATE RoleTypes SET Settings = '<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackColor><A>255</A><R>212</R><G>0</G><B>0</B></BackColor><ShowEmtyInBudget>true</ShowEmtyInBudget></Settings>'
	FROM RoleTypes WHERE RoleTypeCategory = 130 AND Module = 1 AND RoleTypeId > 0 AND Settings IS NULL
END
GO
--#endregion

--#region 20190305 AbTechnicalPersonalDemands aktualisieren und FK_TechnicalJobs_WorkAreaGroups anlegen
Print ('Update AbTechnicalPersonalDemands')
GO
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbTechnicalPersonalDemands'))  DROP VIEW dbo.AbTechnicalPersonalDemands
GO
CREATE VIEW dbo.AbTechnicalPersonalDemands
AS 
	SELECT Act.ActivityId AS ActivityId, Act.Date, Job.WorkAreaGroupId, Job.StartOffset, Job.EndOffset, Job.PersonCount AS SollZahl, Count(cuwt.ActivityJobId) AS IstZahl, Job.Name AS Info
		FROM TechnicalJobs AS Job
			INNER JOIN Activities		AS Act ON  Act.ActivityId = Job.ActivityId
			LEFT JOIN CostUnitWorkingTimes	AS cuwt ON cuwt.ActivityJobId = Job.TechnicalJobId AND cuwt.ActivityID = Act.ActivityId
	WHERE Act.[Status] >= 0 AND Act.VariantId = 0 
	GROUP BY Act.ActivityId, Act.Date, Job.TechnicalJobId, Job.PersonCount, Job.WorkAreaGroupId, Job.Name, Job.StartOffset, Job.EndOffset
GO
GRANT SELECT ON AbTechnicalPersonalDemands TO [public]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_TechnicalJobs_WorkAreaGroups') AND type = 'F') 
BEGIN
	Print ('create FK_TechnicalJobs_WorkAreaGroups')
	DELETE FROM  CostUnitWorkingTimes  WHERE CostUnitWorkingTimes.ActivityJobId in (SELECT TechnicalJobId from TechnicalJobs WHERE not WorkAreaGroupId IN (SELECT WorkAreaGroupId from WorkAreaGroups))
	DELETE FROM TechnicalJobs WHERE not WorkAreaGroupId IN (SELECT WorkAreaGroupId from WorkAreaGroups)
	UPDATE TechnicalJobs SET PersonCount = 0 WHERE PersonCount IS NULL
	ALTER TABLE TechnicalJobs ALTER COLUMN PersonCount INT NOT NULL
	ALTER TABLE TechnicalJobs ADD CONSTRAINT DF_TechnicalJobs_PersonCount DEFAULT 0 FOR PersonCount 

	
	ALTER TABLE dbo.TechnicalJobs  WITH CHECK ADD  CONSTRAINT FK_TechnicalJobs_WorkAreaGroups FOREIGN KEY(WorkAreaGroupId)
		REFERENCES dbo.WorkAreaGroups (WorkAreaGroupId)
	ALTER TABLE dbo.TechnicalJobs CHECK CONSTRAINT FK_TechnicalJobs_WorkAreaGroups
END
GO
--#endregion 

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

--#region ----------- 4.192.x ---------------------------------

--#region TK 20190204 RuleSettings bei RoleBonus und ProductionBonus
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'RuleSettings' AND o.id = OBJECT_ID(N'RoleBonus'))
BEGIN
	Print 'Adding RoleBonus.RuleSettings...'
	ALTER TABLE RoleBonus ADD RuleSettings XML NULL
	EXEC ('UPDATE RoleBonus SET RuleSettings = ''<RoleBonusFeeRule><ActivityTypeNames>pubPerformance</ActivityTypeNames></RoleBonusFeeRule>''')

	Print 'Adding ProductionBonus.RuleSettings...'
	ALTER TABLE ProductionBonus ADD RuleSettings XML NULL
	EXEC ('UPDATE ProductionBonus SET RuleSettings = ''<ProductionBonusFeeRule><ActivityTypeNames>pubPerformance</ActivityTypeNames></ProductionBonusFeeRule>''')
END
GO
--#endregion

--#region TK Settings von DynamicCastCountingFormula umschreiben
UPDATE FormulaConfigurations 
	SET SerializedParameter = Replace(CAST(SerializedParameter AS VARCHAR(MAX)), 'CastFormulaParameter','DynamicCastCountingFormulaParameter') 
	WHERE FormulaId = 'DynamicCastCountingFormula' AND NOT SerializedParameter IS NULL
GO
--#endregion

--#region 20190204 18
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ChargedValue' AND o.id = OBJECT_ID(N'Activities_ResourceObjects'))
BEGIN
	PRINT('Add Activities_ResourceObjects ChargedValue...')
	ALTER TABLE Activities_ResourceObjects ADD ChargedValue MONEY NULL

	PRINT('Update FormulaConfigurations...')
	UPDATE FormulaConfigurations 
	SET SerializedParameter = Replace(CAST(SerializedParameter AS VARCHAR(MAX)), 'CastFormulaParameter','DynamicCastCountingFormulaParameter')
	WHERE FormulaId = 'DynamicCastCountingFormula' AND NOT SerializedParameter IS NULL
END
GO
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.GetActivities2'))	DROP PROCEDURE dbo.GetActivities2
GO

--#endregion

--#region 20190225
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Note' AND o.id = OBJECT_ID(N'PersonFields'))
BEGIN
	PRINT('Add PersonFields ChargedValue...')
	ALTER TABLE PersonFields ADD GroupName VARCHAR(100) NULL
	ALTER TABLE PersonFields ADD DataType SMALLINT NOT NULL CONSTRAINT DF_PersonFields_DataType DEFAULT 0
	ALTER TABLE PersonFields ADD Settings XML NULL
	ALTER TABLE PersonFields ADD Note VARCHAR(1024) NULL
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'StartDate' AND o.id = OBJECT_ID(N'PersonRelations'))
	BEGIN
		ALTER TABLE PersonRelations ADD StartDate DATE NULL
		ALTER TABLE PersonRelations ADD EndDate DATE NULL
	END

GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Code' AND o.id = OBJECT_ID(N'Subscriptions'))
BEGIN
	PRINT('Add PersonFields ChargedValue...')
	ALTER TABLE Subscriptions ADD Code VARCHAR(4) NULL
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BankPersonId' AND o.id = OBJECT_ID(N'BankAccounts'))
BEGIN
	PRINT('Add PersonFields BankId...')
	ALTER TABLE BankAccounts ADD BankPersonId INT NULL

		ALTER TABLE dbo.BankAccounts  WITH CHECK ADD  CONSTRAINT FK_BankAccounts_Persons_BankPersonId FOREIGN KEY(BankPersonId)
		REFERENCES dbo.Persons (PersonId) 
	ALTER TABLE dbo.BankAccounts CHECK CONSTRAINT FK_BankAccounts_Persons_BankPersonId
END

GO
dropcolumn 'Subscriptions', 'PreisBez'
GO
dropcolumn 'BankAccount', 'PostalCode'
GO
dropcolumn 'PersonRelations', 'Start'
GO
dropcolumn 'PersonRelations', 'End'
GO
dropcolumn 'SubscriptionTypes', 'WtR'
GO
dropcolumn 'SubscriptionTypes', 'RingbezTS'
GO
--#endregion

--#region ------------DH20190221---------------------------------
IF NOT EXISTS (SELECT * FROM Permissions WHERE PermissionArea=5 AND OptionsFlag&512>0)
BEGIN
	UPDATE Permissions
	SET OptionsFlag=OptionsFlag+512
	WHERE PermissionArea=5 AND OptionsFlag&2>0
END

--#endregion ---------DH20190221---------------------------------


--#region SH 2019-03-04 Holidays für Berlin und Thüringen ergänzen

--Berlin -> Weltfrauentag, am 08.03.
IF EXISTS (SELECT * FROM Settings s WHERE s.Section = 'Adresse' AND s.KeyName = 'Bundesland' AND s.DataValue = '<Land>Berlin</Land>')
BEGIN
	PRINT 'Adding Weltfrauentag to holidays...'
	INSERT INTO Holidays (Date, Name, LM, UM, LC, UC, HolidayCategory)
	SELECT CAST(CONVERT(VARCHAR(4), DATEPART(YEAR, st.EndDate))+ '0308' AS DATETIME), 'Weltfrauentag', GETDATE(), 0, GETDATE(), 0, 3 
	FROM Seasons st
	WHERE DATEPART(YEAR,st.EndDate)>= 2019
	AND NOT EXISTS (SELECT f.HolidayId FROM Holidays f WHERE Date = CAST(CONVERT(VARCHAR(4), DATEPART(YEAR, st.EndDate))+ '0308' AS DATETIME))
END
GO

--Thüringen -> Weltkindertag, am 20.09.
IF EXISTS (SELECT * FROM Settings s WHERE s.Section = 'Adresse' AND s.KeyName = 'Bundesland' AND s.DataValue = '<Land>Thüringen</Land>')
BEGIN
	PRINT 'Adding Weltkindertag to holidays...'
	INSERT INTO Holidays (Date, Name, LM, UM, LC, UC, HolidayCategory)
	SELECT CAST(CONVERT(VARCHAR(4), DATEPART(YEAR, st.EndDate))+ '0920' AS DATETIME), 'Weltkindertag', GETDATE(), 0, GETDATE(), 0, 3 
	FROM Seasons st
	WHERE DATEPART(YEAR,st.EndDate)>= 2019
	AND NOT EXISTS (SELECT f.HolidayId FROM Holidays f WHERE Date = CAST(CONVERT(VARCHAR(4), DATEPART(YEAR, st.EndDate))+ '0920' AS DATETIME))
END
GO
--#endregion

--#endregion -------- (4.192.x) -------------------------------

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



--#region SH 2019-04-02 Berechtigung auf DistributionList und VerteilerFeld für VorlagenSchreiben, für einheitliche Berechtigungen beim Spielplanexport
GRANT INSERT, UPDATE, DELETE ON [dbo].[MailingList] TO [VorlagenSchreiben]
GO

GRANT INSERT, UPDATE, DELETE ON [dbo].[MailingList] TO [VorlagenSchreiben]
GO
--#endregion

--#region 20190402 Leere Historyeintreäge entfernen
	DELETE FROM ActivityHistory WHERE xhmode = 2 AND XHDetails IS NULL AND XHBem IS NULL
	GO
--#endregion

--#region 20190404
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name  = 'TextValue'  AND c.xtype = 231 AND o.xtype = 'U' AND o.name = 'PersonFieldData')
BEGIN
	PRINT ('PersonFieldData...TextValue')
	ALTER TABLE PersonFieldData ALTER COLUMN TextValue NVARCHAR(512) NOT NULL
END
GO
--#endregion

--#region SH 2019-04-25 Speichernamen von Attachments von absolut in relativ umwandeln
IF EXISTS (SELECT * FROM Attachments a WHERE CHARINDEX('\', a.StoredFileName) > 0)
BEGIN
	PRINT('Updating Attachments StoredFileName...')
	UPDATE Attachments SET StoredFileName = RIGHT(StoredFileName, CHARINDEX('\', REVERSE(StoredFileName)) -1) WHERE CHARINDEX('\', StoredFileName) > 0	
END
GO
--#endregion

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

--#region ----------- 4.193.x ---------------------------------

--#region ------------DH20190304-------------------------------
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('SchoolHolidays') AND [name] = 'RegionCode')
BEGIN
	PRINT('Adding column SchoolHolidays.RegionCode ...')
	ALTER TABLE SchoolHolidays ADD RegionCode NVARCHAR(6) NULL
END
GO
--#endregion ---------DH20190304-------------------------------

--#region SH 2019-03-19 Berechtigungen aufräumen für CountDown und TechnicalJobs 
REVOKE DELETE, INSERT, SELECT, UPDATE ON CountDowns FROM DispoAdmin, PersoAdmin
GO

REVOKE DELETE, INSERT, SELECT, UPDATE ON TechnicalJobs FROM PersoAdmin
GO
--#endregion

--#region TK 20190315 letzte Timestampspalten entfernen
DECLARE @table VARCHAR(100) 
DECLARE @field VARCHAR(100) 
DECLARE cview_cursor CURSOR FOR 
	SELECT o.name AS tab , c.name AS field FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE  c.xtype = 189 AND o.xtype = 'U'

OPEN cview_cursor 
	FETCH NEXT FROM cview_cursor 
	INTO  @table, @field
	WHILE @@FETCH_STATUS = 0
	BEGIN
		Print 'Delete ' + @table +'.' + @field
		DECLARE @ccmd varchar(100)
	
		SELECT @ccmd='ALTER TABLE [' + @table + '] DROP COLUMN [' + @field + ']'
		EXEC (@ccmd)

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

--#region TK 20190315 lc, lm -> Datetime2
IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.Orders') AND o.Name = 'IX_Orders_CashfundID') AND
	EXISTS (SELECT o.name AS tab , c.name AS field FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name  IN ('lm', 'lc')  AND   c.xtype = 61 AND o.xtype = 'U' AND  o.name = 'Orders')
BEGIN
	DROP INDEX [Orders].IX_Orders_CashfundID
	CREATE NONCLUSTERED INDEX IX_Orders_CashfundId ON dbo.Orders (CashFundId)
END
GO

DECLARE @table VARCHAR(256) 
DECLARE @field VARCHAR(256) 
DECLARE cview_cursor CURSOR FOR 
	SELECT o.name AS tab , c.name AS field FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name  IN ('lm', 'lc') AND o.name <> 'updateLog'  AND   c.xtype <> 58 AND o.xtype = 'U' 

OPEN cview_cursor 
	FETCH NEXT FROM cview_cursor 
	INTO  @table, @field
	WHILE @@FETCH_STATUS = 0
	BEGIN
		Print 'Update ' + @table +'.' + @field
		DECLARE @ccmd VARCHAR(MAX)
	
		SELECT @ccmd='UPDATE [' + @table + '] SET ' + @field + ' = ''19000101'' WHERE ' + @field + ' IS NULL'
		EXEC (@ccmd)

		SELECT @ccmd='UPDATE [' + @table + '] SET ' + @field + ' = ''19000101'' WHERE ' + @field + ' < ''19000101'' OR ' + @field + ' > ''20790606'''
		EXEC (@ccmd)

		SELECT @ccmd='ALTER TABLE [' + @table + '] ALTER COLUMN [' + @field + '] SMALLDATETIME NOT NULL'
		EXEC (@ccmd)

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

--#region TK 20190315 alte spalten entfernen
Dropcolumn 'Departments', 'ArchivDatum'
GO
Dropcolumn 'Departments', 'EndOfNight'
GO
Dropcolumn 'Departments', 'Morgens'
GO
Dropcolumn 'Departments', 'Mittag'
GO
Dropcolumn 'Departments', '"EndOfEvening'
GO
Dropcolumn 'Departments', 'SchriftMorgens'
GO
Dropcolumn 'Departments', 'SchriftMittag'
GO
Dropcolumn 'Departments', 'SchriftAbends'
GO
Dropcolumn 'Departments', 'NightShiftForegroundColor'
GO
Dropcolumn 'Departments', 'HintergrundMorgens'
GO
Dropcolumn 'Departments', 'HintergrundMittag'
GO
Dropcolumn 'Departments', 'HintergrundAbends'
GO
Dropcolumn 'Departments', 'NightShiftBackgroundColor'
GO
Dropcolumn 'Calendar', 'Kw'
GO
Dropcolumn 'Calendar', 'TextWoPla'
GO
--#endregion

--#region TK 20190315
if EXISTS (SELECT o.name AS tab , c.name AS field FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name  = 'Day'  AND   c.xtype = 61 AND o.xtype = 'U' AND  o.name = 'DayNotes')
BEGIN
	Print 'DayNotes'
	ALTER TABLE DayNotes ALTER COLUMN [Day] DATE NOT NULL
	ALTER TABLE dbo.DayNotes DROP CONSTRAINT PK_DayNotes WITH ( ONLINE = OFF )
		
	DELETE a FROM  DayNotes AS a INNER JOIN (SELECT  DayNoteCategoryId, [Day] from DayNotes GROUP BY DayNoteCategoryId, [Day] HAVING COUNT(*) >1) AS b ON a.Day = b.day AND a.DayNoteCategoryId = b.DayNoteCategoryId
		WHERE DayNoteId NOT IN (SELECT MIN(DayNoteId) from DayNotes GROUP BY DayNoteCategoryId, [Day] HAVING COUNT(*) >1)

	CREATE UNIQUE CLUSTERED INDEX IX_DayNotes_DayDayNoteCategoryId ON dbo.DayNotes ([Day], DayNoteCategoryId)
	ALTER TABLE dbo.DayNotes ADD  CONSTRAINT PK_DayNotes PRIMARY KEY NONCLUSTERED (DayNoteId)
END
IF EXISTS (SELECT o.name AS tab , c.name AS field FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name  = 'StartDate'  AND   c.xtype = 61 AND o.xtype = 'U' AND  o.name = 'ContractEngagements')
BEGIN
	Print 'contract period'
	ALTER TABLE ContractEngagements ALTER COLUMN StartDate DATE NULL
	ALTER TABLE ContractEngagements ALTER COLUMN EndDate DATE NULL
	UPDATE ContractEngagements SET StartDate = NULL WHERE StartDate = '19000101'
	UPDATE Contracts SET StartDate = NULL WHERE StartDate = '19000101'
	UPDATE ContractDepartments SET StartDate = NULL WHERE  StartDate  = '19000101'

	UPDATE ContractEngagements SET EndDate = NULL WHERE EndDate = '30000101'
	UPDATE Contracts SET EndDate = NULL WHERE EndDate = '30000101'
	UPDATE ContractDepartments SET EndDate = NULL WHERE  EndDate  = '30000101'
END
IF EXISTS (SELECT o.name AS tab , c.name AS field FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name  = 'Start'  AND   c.xtype = 61 AND o.xtype = 'U' AND  o.name = 'Tours')
BEGIN
	Print 'Tours period'
	ALTER TABLE Tours ALTER COLUMN [Start]  DATE NOT NULL
	ALTER TABLE Tours ALTER COLUMN [End] DATE NOT NULL

	ALTER TABLE Tours ALTER COLUMN [StartTime] SMALLDATETIME NULL
	ALTER TABLE Tours ALTER COLUMN [EndTime] SMALLDATETIME NULL
END
IF EXISTS (SELECT o.name AS tab , c.name AS field FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name  = 'ValidFrom'  AND   c.xtype = 61 AND o.xtype = 'U' AND  o.name = 'BonusDefaultAmounts')
BEGIN
	Print 'BonusDefaultAmounts period'
	ALTER TABLE BonusDefaultAmounts ALTER COLUMN ValidFrom  DATE NULL
	ALTER TABLE BonusDefaultAmounts ALTER COLUMN ValidTo DATE NULL
END
IF EXISTS (SELECT o.name AS tab , c.name AS field FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name  = 'ServiceDate'  AND   c.xtype = 61 AND o.xtype = 'U' AND  o.name = 'CashCommandPos')
BEGIN
	Print 'CashCommandPos period'
	ALTER TABLE CashCommandPos ALTER COLUMN ServiceDate DATE NULL
END
IF EXISTS (SELECT o.name AS tab , c.name AS field FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name  = 'BillingPeriodEnd'  AND   c.xtype = 61 AND o.xtype = 'U' AND  o.name = 'CashCommand')
BEGIN
	Print 'CashCommand period'
	DROP INDEX IX_CashCommand_CashDate ON dbo.CashCommand
	ALTER TABLE CashCommand ALTER COLUMN CashDate DATE NOT NULL
	ALTER TABLE CashCommand ALTER COLUMN BillingPeriodStart DATE NULL
	ALTER TABLE CashCommand ALTER COLUMN BillingPeriodEnd DATE NULL
	CREATE NONCLUSTERED INDEX IX_CashCommand_CashDate ON dbo.CashCommand(CashDate)
END
IF EXISTS (SELECT o.name AS tab , c.name AS field FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name  = 'DayOfDeath'  AND   c.xtype = 61 AND o.xtype = 'U' AND  o.name = 'PersonDetails')
BEGIN
	Print 'PersonDetails period'
	ALTER TABLE PersonDetails ALTER COLUMN DateOfBirth DATE NULL
	ALTER TABLE PersonDetails ALTER COLUMN PassDateOfIssue DATE NULL
	ALTER TABLE PersonDetails ALTER COLUMN PassDateOfExpiry DATE NULL
	ALTER TABLE PersonDetails ALTER COLUMN IdentityCardDateOfIssue DATE NULL
	ALTER TABLE PersonDetails ALTER COLUMN IdentityCardDateOfExpiry DATE NULL
	ALTER TABLE PersonDetails ALTER COLUMN DayOfDeath DATE NULL
END
GO

IF EXISTS (SELECT o.name AS tab , c.name AS field FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name  = 'Date'  AND   c.xtype = 61 AND o.xtype = 'U' AND  o.name = 'Calendar')
BEGIN
	Print 'Calendar Date'
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.Date') AND xtype = 'pk') ALTER TABLE dbo.Calendar DROP CONSTRAINT Date
	
	ALTER TABLE dbo.Calendar	DROP CONSTRAINT PK_Calendar
	ALTER TABLE Calendar ALTER COLUMN Date DATE NOT NULL
	CREATE UNIQUE CLUSTERED  INDEX IX_Calender_Date ON dbo.Calendar(Date)
	ALTER TABLE dbo.Calendar ADD CONSTRAINT	PK_Calendar PRIMARY KEY NONCLUSTERED (CalenderId) 
END
--#endregion

--#region TK 2019-03-19 / 04-01
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'MarkVacantCastDaysBefore' AND o.id = OBJECT_ID(N'CastRules'))
BEGIN
	PRINT('CastRules CheckBasicCastOverlappings')
	ALTER TABLE CastRules ADD CheckBasicCastOverlapping BIT NOT NULL CONSTRAINT DF_CastRules_CheckBasicCastOverlapping DEFAULT 0
	ALTER TABLE CastRules ADD MarkVacantCastDaysBefore SMALLINT NULL
	EXEC ('UPDATE CastRules SET CheckBasicCastOverlapping = 1 FROM  CastRules AS ra INNER JOIN ActivityTypes AS a on ra.ActivityTypeId = a.ActivityTypeId WHERE  a.Category >= 2000')
	EXEC ('UPDATE CastRules SET MarkVacantCastDaysBefore = 30 FROM  CastRules AS ra INNER JOIN ActivityTypes AS a on ra.ActivityTypeId = a.ActivityTypeId INNER JOIN RoleTypes AS Rl ON ra.RoleTypeId = Rl.RoleTypeId WHERE a.Category >= 2000 AND rl.RoleTypeCategory = 0 AND ra.IsMandatory = 1')
	EXEC ('UPDATE CastRules SET MarkVacantCastDaysBefore = 32767 FROM  CastRules AS ra INNER JOIN ActivityTypes AS a on ra.ActivityTypeId = a.ActivityTypeId INNER JOIN RoleTypes AS Rl ON ra.RoleTypeId = Rl.RoleTypeId WHERE rl.RoleTypeCategory >= 100 AND ra.IsMandatory = 1')
END
GO
ALTER TABLE ActivityHistory ALTER COLUMN StartTime TIME(0) NOT NULL
ALTER TABLE ActivityHistory ALTER COLUMN EndTime TIME(0) NOT NULL
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsFontBold' AND o.id = OBJECT_ID(N'Roles'))
	BEGIN
	PRINT('Roles IsFontBold')
	EXEC sp_rename  'Roles.FontFormat', 'IsFontBold', 'COLUMN'
	EXEC('UPDATE Roles SET IsFontBold = 0 WHERE IsFontBold IS NULL')
	EXEC('UPDATE Roles SET IsFontBold = 0 WHERE IsFontBold = 2')
	EXEC('UPDATE Roles SET IsFontBold = 1 WHERE IsFontBold = 3')
	ALTER TABLE Roles ALTER COLUMN  IsFontBold BIT NOT NULL
	ALTER TABLE Roles ADD CONSTRAINT DF_Roles_IsFontBold DEFAULT 0 FOR IsFontBold
END
GO
--#endregion TK 2019-03-19

--#region 2019-01-14 SH Repetitorrolle bei Bedarf wieder hinzufügen
IF NOT EXISTS(SELECT * FROM Roles bs WHERE bs.RoleId = -1)
BEGIN
	PRINT 'Adding Repetitor role...'
	SET IDENTITY_INSERT Roles ON
	INSERT INTO Roles (RoleId, ProductionId, Name, RoleTypeId, IsFontBold, PrintMode, OwnerGroupId, LM, UM, LC, UC, PersonCount)
	VALUES (-1, -1, 'Repetitor', -1, 0, 1, 1, GETDATE(),-1, GETDATE(), -1, 1)
	SET IDENTITY_INSERT Roles OFF
END
GO
--#endregion

--#region Roles und RoleTypes umbau
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsProductionTeam' AND o.id = OBJECT_ID(N'Roles'))
BEGIN
PRINT('Adding column Roles.IsProductionTeam...')
	ALTER TABLE Roles ADD IsProductionTeam BIT NOT NULL CONSTRAINT DF_Roles_IsProductionTeam DEFAULT 0
	Exec('UPDATE Roles SET IsProductionTeam = 1 WHERE StdVs = 0')
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsProductionTeam' AND o.id = OBJECT_ID(N'RoleTypes'))
BEGIN
PRINT('Adding column RoleTypes.IsProductionTeam...')
	ALTER TABLE RoleTypes ADD IsProductionTeam BIT NOT NULL CONSTRAINT DF_RoleTypes_IsProductionTeam DEFAULT 0
	Exec('UPDATE RoleTypes SET IsProductionTeam = 1 WHERE StdVs = 0')
END
GO
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.FK_Role_Group') AND type = 'F')			 ALTER TABLE dbo.Roles	DROP CONSTRAINT FK_Role_Group
IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Roles') AND o.Name = 'IX_Besitzer') DROP INDEX Roles.IX_Besitzer
IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Roles') AND o.Name = 'IX_Roles_RoleId_OwnerId') DROP INDEX Roles.IX_Roles_RoleId_OwnerId
GO
DropDefaultConstraint 'Roles', 'PersonCount'
GO
DropDefaultConstraint 'Roles', 'Leporello'
GO
DropDefaultConstraint 'Roles', 'PresseSort'
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Roles') AND o.Name = 'IX_Roles_OwnerGroups')
BEGIN
	ALTER TABLE Roles ALTER COLUMN PersonCount SMALLINT NOT NULL
	UPDATE Roles SET Leporello = 0 WHERE Leporello IS NULL
	UPDATE Roles SET PresseSort = 0 WHERE PresseSort IS NULL
	ALTER TABLE Roles ALTER COLUMN Leporello SMALLINT NOT NULL
	ALTER TABLE Roles ALTER COLUMN PresseSort SMALLINT NOT NULL

	UPDATE Roles SET OwnerGroupId = 1 WHERE OwnerGroupId IS NULL
	ALTER TABLE Roles ALTER COLUMN OwnerGroupId INT NOT NULL

	CREATE INDEX IX_Roles_OwnerGroups ON Roles (OwnerGroupId) INCLUDE (RoleId, ProductionId, RoleTypeId, IsProductionTeam)

END

GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Role_Group') AND type = 'F')
BEGIN
	ALTER TABLE dbo.Roles  WITH CHECK ADD  CONSTRAINT FK_Roles_Groups FOREIGN KEY(OwnerGroupId)
		REFERENCES dbo.OwnerGroups (OwnerGroupId) 
	ALTER TABLE dbo.Roles CHECK CONSTRAINT FK_Roles_Groups
END
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Roles') AND o.Name = 'IX_Roles_RoleId_OwnerId') CREATE INDEX IX_Roles_RoleId_OwnerId ON dbo.Roles (RoleId, OwnerGroupId)
IF NOT EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_Roles_Leporello') ALTER TABLE Roles ADD CONSTRAINT DF_Roles_Leporello DEFAULT 0 FOR Leporello
IF NOT EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_Roles_PresseSort') ALTER TABLE Roles ADD CONSTRAINT DF_Roles_PresseSort DEFAULT 0 FOR PresseSort
GO


IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'PK_RoleTypes' AND type_desc = 'NONCLUSTERED')
BEGIN
	PRINT('RoleTypes ...')
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.RoleTypes') AND o.Name = 'RollenID') DROP INDEX RoleTypes.RollenID
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.RoleTypes') AND o.Name = 'PK_Name') DROP INDEX RoleTypes.PK_Name
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_WorkVersionRoles_RoleTypes') AND type = 'F') ALTER TABLE dbo.WorkVersionRoles DROP CONSTRAINT FK_WorkVersionRoles_RoleTypes
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Roles_RoleTypes') AND type = 'F') ALTER TABLE dbo.Roles DROP CONSTRAINT FK_Roles_RoleTypes
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Roles_RoleCategories') AND type = 'F') ALTER TABLE dbo.Roles DROP CONSTRAINT FK_Roles_RoleCategories
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_CastRules_RoleTypes') AND type = 'F') ALTER TABLE dbo.CastRules DROP CONSTRAINT FK_CastRules_RoleTypes
	ALTER TABLE dbo.RoleTypes DROP CONSTRAINT PK_RoleTypes
	ALTER TABLE dbo.RoleTypes ADD CONSTRAINT PK_RoleTypes PRIMARY KEY CLUSTERED (RoleTypeId) 

	ALTER TABLE WorkVersionRoles WITH CHECK ADD CONSTRAINT FK_WorkVersionRoles_RoleTypes FOREIGN KEY(RoleTypeId) REFERENCES RoleTypes (RoleTypeId)
	ALTER TABLE Roles WITH CHECK ADD CONSTRAINT FK_Roles_RoleTypes FOREIGN KEY(RoleTypeId) REFERENCES RoleTypes (RoleTypeId)
	ALTER TABLE CastRules WITH CHECK ADD CONSTRAINT FK_CastRules_RoleTypes FOREIGN KEY(RoleTypeId) REFERENCES RoleTypes (RoleTypeId)
	PRINT('Delete empty Basicast ...')
	DELETE FROM BesetzungStdSoliTabelle WHERE PersNr1 IS NULL AND PersNr2 IS NULL AND   PersNr3 IS NULL AND PersNr4 IS NULL AND Note IS NULL AND IsSecret = 0
END

GO
dropcolumn 'RoleTypes', 'TagesplanSort'
GO
dropcolumn 'RoleTypes', 'StdVs'
GO
dropcolumn 'Roles', 'StdVs'
GO
dropcolumn 'Roles', 'Exklusiv'
GO
dropcolumn 'CashCommand', 'PayDate'
GO
--#endregion

--#region CopyRole aktualisiert
PRINT('Updating Procedure CopyRole...')
GO

GO
ALTER PROCEDURE [dbo].[CopyRole]
	@productionId int,
	@roleId  int
As
BEGIN
	DECLARE @userId INT

	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
INSERT INTO Roles (
	[Name],[Pos],[Leporello],[PresseSort],[IsProductionTeam],[RoleTypeId],JourneyGroupId,IsFontBold
      ,[PrintMode],[OwnerGroupId],[WorkAreaGroupId],PersonCount,[ShortName]
      ,[CountDownId],[PublishedName],[IsStarRole],[IsInactive],[RoleCode],[Note],[RoleCategoryId],[WorkVersionRoleId]
	  ,[AutoCast],[StartMasktime],[EndMasktime]
	  ,[ProductionId] 
      ,[LM]
      ,[UM]
      ,[LC]
      ,[UC]) 
SELECT 
	[Name],[Pos],[Leporello],[PresseSort],[IsProductionTeam],[RoleTypeId],JourneyGroupId,IsFontBold
      ,[PrintMode],[OwnerGroupId],[WorkAreaGroupId] ,PersonCount,[ShortName]
      ,[CountDownId],[PublishedName],[IsStarRole],[IsInactive],[RoleCode],[Note],[RoleCategoryId],[WorkVersionRoleId]
	  ,[AutoCast],[StartMasktime],[EndMasktime]
	  ,@productionId, 
	  GETDATE(),
	  @userId,
	  GETDATE(),
	  @userId
FROM Roles AS RoleSource WHERE RoleSource.RoleId = @roleId
SELECT CAST(@@IDENTITY as INT)
END
GO
--#endregion

--#region Neu Spalte für Spaltenfilter in DispoLayoutColumns, inklusive umschreiben der alten Einstellungen

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('DispoLayoutColumns') AND [name] = 'ColumnFilterSettings')
BEGIN
	PRINT('Adding Dispo UserPwColumnFilterSettingsKnownUserType ...')
	ALTER TABLE dbo.DispoLayoutColumns ADD ColumnFilterSettings XML NULL
END
GO
IF NOT EXISTS (SELECT * FROM DispoLayoutColumns WHERE NOT ColumnFilterSettings IS NULL)
BEGIN
	UPDATE DispoLayoutColumns SET ColumnFilterSettings= '<DispoLayoutColumnFilter><StageNodes>' +
		ISNULL(STUFF((SELECT '<string>stage'+ CAST(ar.LocationId  AS VARCHAR(10)) + '</string>'
			FROM HDMzr ar 
			WHERE ar.DispoLayoutColumnId = r.DispoLayoutColumnId AND ar.LocationId <> 0
		FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 0, '') ,'')+ '</StageNodes>'+
		(CASE WHEN (SELECT COUNT(*) FROM HDMzr ar WHERE ar.DispoLayoutColumnId = r.DispoLayoutColumnId AND ar.LocationId = 0) = 1 THEN '<IsRestColumn>true</IsRestColumn>' ELSE '' END )+
		'<DefaultStageId>' + CAST(ISNULL((SELECT MIN(LocationId) FROM HDMzr ar WHERE ar.DispoLayoutColumnId = r.DispoLayoutColumnId AND ar.Std = 1),0) AS VARCHAR(10))  +  '</DefaultStageId>' 
		+'</DispoLayoutColumnFilter>'
 FROM DispoLayoutColumns r
END
GO
--#endregion

--#region nicht mehr verwendete Spalten von DispoLayoutColumns entfernen
dropcolumn 'DispoLayoutColumns', 'wVon'
GO
dropcolumn 'DispoLayoutColumns', 'wBis'
GO
dropcolumn 'DispoLayoutColumns', 'wTitel'
GO
dropcolumn 'DispoLayoutColumns', 'wArt'
GO
dropcolumn 'DispoLayoutColumns', 'wBem'
GO
dropcolumn 'DispoLayoutColumns', 'wAbo'
GO
dropcolumn 'DispoLayoutColumns', 'wChor'
GO
dropcolumn 'DispoLayoutColumns', 'wOrch'
GO
dropcolumn 'DispoLayoutColumns', 'wZr'
GO
dropcolumn 'DispoLayoutColumns', 'ContractTypesCategory'
GO
dropcolumn 'DispoLayoutColumns', 'wStatus'
GO
dropcolumn 'DispoLayoutColumns', 'StartDate'
GO
dropcolumn 'DispoLayoutColumns', 'EndDate'
GO
dropcolumn 'DispoLayoutColumns', 'vTitel'
GO
dropcolumn 'DispoLayoutColumns', 'vBem'
GO
dropcolumn 'DispoLayoutColumns', 'vAbo'
GO
dropcolumn 'DispoLayoutColumns', 'vChor'
GO
dropcolumn 'DispoLayoutColumns', 'vOrch'
GO
dropcolumn 'DispoLayoutColumns', 'vStatus'
GO
dropcolumn 'DispoLayoutColumns', 'wBallett'
GO
dropcolumn 'DispoLayoutColumns', 'wPreis'
GO
dropcolumn 'DispoLayoutColumns', 'vBallett'
GO
dropcolumn 'DispoLayoutColumns', 'vPreis'
GO
dropcolumn 'DispoLayoutColumns', 'vInfo'
GO
dropcolumn 'DispoLayoutColumns', 'wInfo'
GO
dropcolumn 'DispoLayoutColumns', 'vBem2'
GO
dropcolumn 'DispoLayoutColumns', 'wBem2'
GO
dropcolumn 'DispoLayoutColumns', 'vBemlang'
GO
dropcolumn 'DispoLayoutColumns', 'wBemlang'
GO
dropcolumn 'DispoLayoutColumns', 'vBesetzung'
GO
dropcolumn 'DispoLayoutColumns', 'wBesetzung'
GO
dropcolumn 'DispoLayoutColumns', 'vFahrplan'
GO
dropcolumn 'DispoLayoutColumns', 'wFahrplan'
GO
dropcolumn 'DispoLayoutColumns', 'wWebStart'
GO
dropcolumn 'DispoLayoutColumns', 'vWebStart'
GO
dropcolumn 'DispoLayoutColumns', 'wPR'
GO
dropcolumn 'DispoLayoutColumns', 'wExid'
GO
dropcolumn 'DispoLayoutColumns', 'wVKStart'
GO
dropcolumn 'DispoLayoutColumns', 'wVKStatus'
GO
dropcolumn 'DispoLayoutColumns', 'wPreisBem'
GO
dropcolumn 'DispoLayoutColumns', 'vPR'
GO
dropcolumn 'DispoLayoutColumns', 'vExid'
GO
dropcolumn 'DispoLayoutColumns', 'vVKStart'
GO
dropcolumn 'DispoLayoutColumns', 'vVKStatus'
GO
dropcolumn 'DispoLayoutColumns', 'vPreisBem'
GO
dropcolumn 'DispoLayoutColumns', 'wVKStatus'
GO
dropcolumn 'DispoLayoutColumns', 'wPreisBem'
GO
dropcolumn 'DispoLayoutColumns', 'vPR'
GO
dropcolumn 'DispoLayoutColumns', 'vExid'
GO
dropcolumn 'DispoLayoutColumns', 'vVKStart'
GO
dropcolumn 'DispoLayoutColumns', 'vVKStatus'
GO
dropcolumn 'DispoLayoutColumns', 'vPreisBem'
GO
dropcolumn 'DispoLayouts', 'sFahrplan'
GO
dropcolumn 'DispoLayouts', 'vTagMemo'
GO
dropcolumn 'DispoLayouts', 'Orch'
GO
dropcolumn 'DispoLayouts', 'Chor'
GO
dropcolumn 'DispoLayouts', 'Ballett'
GO
dropcolumn 'DispoLayouts', 'wUrlaub'
GO
dropcolumn 'DispoLayouts', 'vUrlaub'
GO
dropcolumn 'DispoLayouts', 'BesSelektion'
GO
dropcolumn 'DispoLayouts', 'wTagMemo'
GO
dropcolumn 'DispoLayouts', 'sArt'
GO
dropcolumn 'DispoLayouts', 'sBem'
GO
dropcolumn 'DispoLayouts', 'sZr'
GO
dropcolumn 'DispoLayouts', 'sAbo'
GO
dropcolumn 'DispoLayouts', 'sChor'
GO
dropcolumn 'DispoLayouts', 'sOrch'
GO
dropcolumn 'DispoLayouts', 'sBallett'
GO
dropcolumn 'DispoLayouts', 'sStatus'
GO
dropcolumn 'DispoLayouts', 'sPreis'
GO
dropcolumn 'DispoLayouts', 'sInfo'
GO
dropcolumn 'DispoLayouts', 'sBem2'
GO
dropcolumn 'DispoLayouts', 'sBemLang'
GO
dropcolumn 'DispoLayouts', 'sFahrpla'
GO
dropcolumn 'DispoLayouts', 'sBesetzung'
GO
dropcolumn 'DispoLayouts', 'sVon'
GO
dropcolumn 'DispoLayouts', 'sBis'
GO
dropcolumn 'DispoLayouts', 'sTitel'
GO
--#endregion

--#region PersonRelations.Function verlängern
ALTER TABLE PersonRelations ALTER COLUMN FunctionName VARCHAR(512)
GO
--#endregion

--#region DH 2019-04-12 Neue Spalte für BudgetPeriods

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('BudgetPeriods') AND [name] = 'IsClosed')
BEGIN
	PRINT('Adding column BudgetPeriods.IsClosed ...')
	ALTER TABLE dbo.BudgetPeriods ADD IsClosed BIT NOT NULL CONSTRAINT DF_BudgetPeriods_IsClosed DEFAULT 0
END
GO
--#endregion DH 2019-04-12

--#region DH 2019-04-26 Vorsingenverwaltung
--#region tabellen
IF NOT EXISTS (SELECT * FROM sys.tables WHERE [name]='AuditionTypes')
BEGIN
       PRINT 'Create AuditionTypes'
       CREATE TABLE [AuditionTypes](
             [AuditionTypeId] INT IDENTITY(1,1) NOT NULL,
             [OwnerGroupId] INT NOT NULL,
             [Name] VARCHAR(50) NOT NULL,
             [IsInactive] BIT NOT NULL CONSTRAINT DF_AuditionTypes_IsInactive DEFAULT 0,
             LM SMALLDATETIME NOT NULL,
             UM INT NULL,
             LC SMALLDATETIME NOT NULL,
             UC INT NULL,
             CONSTRAINT PK_AuditionTypes PRIMARY KEY CLUSTERED (AuditionTypeId) ON [PRIMARY],
             CONSTRAINT FK_AuditionTypes_OwnerGroups FOREIGN KEY(OwnerGroupId) REFERENCES OwnerGroups (OwnerGroupId)
       ) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.tables WHERE [name]='Auditions')
BEGIN
       PRINT 'Create Auditions'
       CREATE TABLE [Auditions](
             AuditionId INT IDENTITY(1,1) NOT NULL,
             AuditionTypeId INT NOT NULL,
             PersonId INT NOT NULL,
             ActivityId INT NULL,
             [Start] SMALLDATETIME NOT NULL,
             LM SMALLDATETIME NOT NULL,
             UM INT NOT NULL,
             LC SMALLDATETIME NOT NULL,
             UC INT NOT NULL,
             CONSTRAINT PK_Auditions PRIMARY KEY NONCLUSTERED (AuditionId) ON [PRIMARY],
             CONSTRAINT FK_Auditions_AuditionTypes FOREIGN KEY(AuditionTypeId) REFERENCES AuditionTypes (AuditionTypeId),
             CONSTRAINT FK_Auditions_Persons FOREIGN KEY(PersonId) REFERENCES Persons(PersonId),
             CONSTRAINT FK_Auditions_Activities FOREIGN KEY(ActivityId) REFERENCES [dbo].[Activities] ([ActivityId])
       ) ON [PRIMARY]
       CREATE CLUSTERED INDEX IX_Auditions_PersonId ON [Auditions](PersonId)
END
GO

IF NOT EXISTS (SELECT * FROM sys.tables WHERE [name]='AuditionFieldTypes')
BEGIN
       PRINT 'Create AuditionFieldTypes'
       CREATE TABLE [AuditionFieldTypes](
             [AuditionFieldTypeId] INT IDENTITY(1,1) NOT NULL,
             [ModulFlag] SMALLINT NOT NULL CONSTRAINT DF_AuditionFieldTypes_ModulFlag DEFAULT 0,
             [Name] VARCHAR(100) NOT NULL,
             [Code] VARCHAR(20) NOT NULL,
             [GroupName] VARCHAR(100) NULL,
             [DataType] SMALLINT NOT NULL,
             [Settings] XML NULL,
             [Note] VARCHAR(1024) NULL,
             [IsInactive] BIT NOT NULL CONSTRAINT DF_AuditionFieldTypes_IsInactive DEFAULT 0,
             LM SMALLDATETIME NOT NULL,
             UM INT NULL,
             LC SMALLDATETIME NOT NULL,
             UC INT NULL,
             CONSTRAINT PK_AuditionFieldTypes PRIMARY KEY CLUSTERED (AuditionFieldTypeId) ON [PRIMARY]
       ) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.tables WHERE [name]='AuditionTypes_AuditionFieldTypes')
BEGIN
       PRINT 'Create AuditionTypes_AuditionFieldTypes'
       CREATE TABLE [AuditionTypes_AuditionFieldTypes](
             [AuditionType_AuditionFieldTypeId] INT IDENTITY(1,1) NOT NULL,
             [AuditionFieldTypeId] INT NOT NULL,
             [AuditionTypeId] INT NOT NULL,
             [Sort] INT NOT NULL CONSTRAINT DF_AuditionTypes_AuditionFieldTypes_Sort DEFAULT 0,
             LM SMALLDATETIME NOT NULL,
             UM INT NULL,
             LC SMALLDATETIME NOT NULL,
             UC INT NULL,
             CONSTRAINT PK_AuditionTypes_AuditionFieldTypes PRIMARY KEY NONCLUSTERED (AuditionType_AuditionFieldTypeId) ON [PRIMARY],
             CONSTRAINT FK_AuditionTypes_AuditionFieldTypes_AuditionTypes FOREIGN KEY(AuditionTypeId) REFERENCES AuditionTypes (AuditionTypeId),
             CONSTRAINT FK_AuditionTypes_AuditionFieldTypes_AuditionFieldTypes FOREIGN KEY(AuditionFieldTypeId) REFERENCES AuditionFieldTypes (AuditionFieldTypeId)
       ) ON [PRIMARY]

       CREATE INDEX IX_AuditionTypes_AuditionFieldTypes_AuditionFieldTypeId ON [AuditionTypes_AuditionFieldTypes](AuditionFieldTypeId)
       CREATE INDEX IX_AuditionTypes_AuditionFieldTypes_AuditionTypeId ON [AuditionTypes_AuditionFieldTypes](AuditionTypeId)
       CREATE UNIQUE INDEX IX_AuditionTypes_AuditionFieldTypes_AuditionFieldTypeId_AuditionTypeId ON AuditionTypes_AuditionFieldTypes([AuditionFieldTypeId],[AuditionTypeId])
END
GO

IF NOT EXISTS (SELECT * FROM sys.tables WHERE [name]='AuditionFieldData')
BEGIN
       PRINT 'Create AuditionFieldData'
       CREATE TABLE [dbo].[AuditionFieldData](
             [AuditionFieldDataId] INT IDENTITY(1,1) NOT NULL,
             [AuditionId] INT NOT NULL,
             [AuditionFieldTypeId] INT NOT NULL,
             [TextValue] NVARCHAR(MAX) NOT NULL,
             [LM] SMALLDATETIME NOT NULL,
             [UM] INT NULL,
             [LC] SMALLDATETIME NOT NULL,
             [UC] INT NULL,
             CONSTRAINT [PK_AuditionFieldData] PRIMARY KEY NONCLUSTERED (AuditionFieldDataId) ON [PRIMARY],
             CONSTRAINT FK_AuditionFieldData_Auditions FOREIGN KEY([AuditionId]) REFERENCES [Auditions] (AuditionId),
             CONSTRAINT FK_AuditionFieldData_AuditionFieldTypes FOREIGN KEY([AuditionFieldTypeId]) REFERENCES [AuditionFieldTypes] ([AuditionFieldTypeId])
       ) ON [PRIMARY]
       CREATE CLUSTERED INDEX IX_AuditionFieldData_AuditionId ON [AuditionFieldData]([AuditionId])
       CREATE UNIQUE INDEX IX_AuditionFieldData_AuditionId_AuditionFieldTypeId ON [AuditionFieldData]([AuditionId],AuditionFieldTypeId)
END
GO

IF NOT EXISTS (SELECT * FROM sys.tables WHERE [name]='Auditions_WorkRoles')
BEGIN
       PRINT 'Create Audition_WorkRoles'
       CREATE TABLE [dbo].Auditions_WorkRoles(
             Audition_WorkRoleId INT IDENTITY(1,1) NOT NULL,
             [AuditionId] INT NOT NULL,
             [WorkRoleId] INT NOT NULL,
			 Rating TINYINT NULL,
             Note NVARCHAR(256) NULL,
             [LM] SMALLDATETIME NOT NULL,
             [UM] INT NULL,
             [LC] SMALLDATETIME NOT NULL,
             [UC] INT NULL,
             CONSTRAINT PK_Auditions_WorkRoles PRIMARY KEY CLUSTERED (Audition_WorkRoleId) ON [PRIMARY],
             CONSTRAINT FK_Auditions_WorkRoles_Auditions FOREIGN KEY([AuditionId]) REFERENCES [Auditions] (AuditionId) ON DELETE CASCADE,
			 CONSTRAINT FK_Auditions_WorkRoles_WorkVersionRoles_WorkRoleId FOREIGN KEY([WorkRoleId]) REFERENCES WorkVersionRoles (WorkVersionRoleId),
       ) ON [PRIMARY]
       CREATE INDEX IX_Audition_WorkRoleId_AuditionId ON Auditions_WorkRoles(AuditionId)
       CREATE UNIQUE INDEX IX_Audition_WorkRoleId_AuditionId_WorkRoleId ON Auditions_WorkRoles([AuditionId],WorkRoleId)
END
GO
--#endregion

--#region Permissions
GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.Auditions_WorkRoles to Public --Todo

GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.AuditionFieldTypes to DispoAdmin,ChorAdmin
GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.AuditionTypes to DispoAdmin,ChorAdmin
GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.AuditionTypes_AuditionFieldTypes to DispoAdmin,ChorAdmin

GRANT Select ON dbo.AuditionFieldTypes to Public
GRANT Select ON dbo.AuditionTypes to Public
GRANT Select ON dbo.AuditionTypes_AuditionFieldTypes to Public
GO
--#endregion Permissions

--#region Audition
IF EXISTS (SELECT * FROM sys.views WHERE [name]='ABAuditions')
BEGIN
	DROP VIEW dbo.ABAuditions
END
GO
	CREATE VIEW dbo.ABAuditions
AS 
	SELECT A.* 
		FROM Auditions AS A
			INNER JOIN AuditionTypes AS AT ON A.AuditionTypeID=AT.AuditionTypeID
			INNER JOIN Permissions AS ug ON AT.OwnerGroupId = ug.OwnerGroupId AND UG.PermissionArea=18
			INNER JOIN Users AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER		

GO
GRANT SELECT ON ABAuditions to Public
GO

IF EXISTS (SELECT * FROM sys.views WHERE [name]='ABAuditions_Update')
BEGIN
	DROP VIEW dbo.ABAuditions_Update
END
GO
	CREATE VIEW dbo.ABAuditions_Update
AS 
	 SELECT A2.* 
		FROM Auditions AS A2 where a2.AuditionId in (SELECT A.AuditionId 
		FROM Auditions AS A
			INNER JOIN AuditionTypes AS AT ON A.AuditionTypeID=AT.AuditionTypeID
			INNER JOIN Permissions AS ug ON AT.OwnerGroupId = ug.OwnerGroupId AND UG.PermissionArea=18 AND UG.HasWritePermission=1
			INNER JOIN Users AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER		)

GO
GRANT SELECT, INSERT, UPDATE, DELETE ON ABAuditions_Update to Public
GO
--#endregion Audition


--#region AuditionFieldData
IF EXISTS (SELECT * FROM sys.views WHERE [name]='ABAuditionFieldData')
BEGIN
	DROP VIEW dbo.ABAuditionFieldData
END
GO
	CREATE VIEW dbo.ABAuditionFieldData
AS 
	SELECT AFD.* 
		FROM AuditionFieldData AS AFD
			INNER JOIN Auditions AS A on AFD.AuditionId=A.AuditionID
			INNER JOIN AuditionTypes AS AT ON A.AuditionTypeID=AT.AuditionTypeID
			INNER JOIN Permissions AS ug ON AT.OwnerGroupId = ug.OwnerGroupId AND UG.PermissionArea=18
			INNER JOIN Users AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER		

GO
GRANT SELECT ON ABAuditionFieldData to Public
GO
IF EXISTS (SELECT * FROM sys.views WHERE [name]='ABAuditionFieldData_Update')
BEGIN
	DROP VIEW dbo.ABAuditionFieldData_Update
END
GO
	CREATE VIEW dbo.ABAuditionFieldData_Update
AS 
	SELECT AFD.* 
		FROM AuditionFieldData AS AFD where afd.AuditionFieldDataId in (select AuditionFieldDataId from AuditionFieldData AD
			INNER JOIN Auditions AS A on AD.AuditionId=A.AuditionID
			INNER JOIN AuditionTypes AS AT ON A.AuditionTypeID=AT.AuditionTypeID
			INNER JOIN Permissions AS ug ON AT.OwnerGroupId = ug.OwnerGroupId AND UG.PermissionArea=18 AND UG.HasWritePermission=1
			INNER JOIN Users AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER)		

GO
GRANT SELECT, INSERT, UPDATE, DELETE ON ABAuditionFieldData_Update to Public
GO
--#endregion AuditionFieldData

--#region MergeDoubletten
--obsolete da in bereich db 2.0
--#endregion MergeDoubletten

--#endregion DH 2019-04-26 Vorsingenverwaltung

--#region 2019-06-07 
ALTER TABLE PersonAddress ALTER COLUMN Name VARCHAR(30) NULL
GO
--#endregion

--#endregion -------- (4.193.x) -------------------------------

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

--#region 2019-05-24 sh Default für Roles.Anzahl wieder anlegen
IF NOT EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_Roles_PersonCount')
ALTER TABLE Roles ADD CONSTRAINT DF_Roles_PersonCount DEFAULT 1 FOR PersonCount
GO
--#endregion

--#region 2019-05-28 sh AbProbenNr aktualisieren, ausgefallene Aktivitäten ignorieren
ALTER PROCEDURE [dbo].[AbProbenNr]
	@lSnr INT,
	@DDatum DATE,
	@dVon  SMALLDATETIME,
	@dspzStart DATE,
	@lArt As INT
AS
	SELECT Count(*) AS Anz
	FROM Activities
	WHERE ProductionId = @lSnr
		AND [Status] >= 0
		AND VariantId = 0
		AND ActivityTypeId = @lArt 
		AND Date >= @dspzStart
		AND (Date < @DDatum OR  (Date = @DDatum AND StartTime <= @dvon))

GO
--#endregion

--#region 20190613 CastCount
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.GetCastCountByContractAndProduction')) DROP PROCEDURE dbo.GetCastCountByContractAndProduction

GO
CREATE PROCEDURE dbo.GetCastCountByContractAndProduction
		 @contractId INT, @productionId INT, @untilDate DATE, @activityTypeIds IdFilterTable READONLY 
AS
BEGIN
	SELECT Count(DISTINCT a.ActivityId)
	FROM Cast			AS c
		INNER JOIN Activities	AS A   ON A.ActivityId = c.ActivityId
		INNER JOIN @activityTypeIds		AS atFilter ON A.ActivityTypeId = atFilter.Id
	WHERE   a.Date <= @untilDate
		AND a.ProductionId = @productionId
		AND c.IsCanceled = 0
		AND a.VariantId = 0
		AND c.ContractId = @ContractId
		AND (c.Creditable > 0 OR (c.Creditable IS NULL AND a.[Status] >= 0))
END
GO
GRANT EXECUTE ON GetCastCountByContractAndProduction TO [public]
--#endregion

--#region 20190613
  UPDATE [ShiftTypes] SET DepartmentGroupId = NULL WHERE DepartmentGroupId = 0
  UPDATE Departments SET DepartmentGroupId = NULL WHERE DepartmentGroupId = 0
  DELETE FROM DepartmentGroups WHERE DepartmentGroupId = 0
GO
--#endregion

--#region 2019-06-21 sh ClearOldDutyRosterData korrigiert
--obsolete da in bereich DB 2.0
--#endregion

--#region 2019-06-12 sh ClearOldCashCommands korrigiert
--obsolete da in bereich DB 2.0
--#endregion

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

--#region ----------- 4.194.x ---------------------------------

--#region -------- DH20190621 Warnungen
GRANT UPDATE,SELECT,INSERT,DELETE ON dbo.WarningLog TO DataCleaningAdmin
GO
--#region -------- CastInvalidOffsetWarning
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].[CastInvalidOffsetWarning]'))
BEGIN
	DROP PROCEDURE dbo.[CastInvalidOffsetWarning]
END
GO
CREATE PROCEDURE [dbo].[CastInvalidOffsetWarning]
		@infoOnly bit
		WITH EXECUTE AS 'dbo'
		AS
		BEGIN
			
		
		IF(@infoOnly=0)
		BEGIN
			UPDATE  Cast SET EndOffset = 0  FROM 
						Cast AS C 
							INNER JOIN Activities AS A ON c.ActivityId = a.ActivityId
					WHERE C.EndOffset <> 0 
						AND  (EndOffset + DATEDIFF(MINUTE, a.StartTime, a.EndTime)) < 0;
			UPDATE  Cast SET StartOffset = 0  FROM 
					Cast AS C 
						INNER JOIN Activities AS A ON c.ActivityId = a.ActivityId
				WHERE C.StartOffset <> 0 
					AND StartOffset > DATEDIFF(MINUTE, a.StartTime, a.EndTime);
			END
		ELSE
		BEGIN
			SELECT Date, StartTime, ISNULL(Title,''), ISNULL(KeyName, '') FROM 
						(SELECT KeyName, Title, Date, DATEDIFF(MINUTE, a.StartTime, a.EndTime) AS Duration,A.StartTime, A.EndTime, C.StartOffset, C.EndOffset
						FROM Cast AS C 
							INNER JOIN Activities AS A ON c.ActivityId = a.ActivityId
							INNER JOIN Productions AS PR on a.ProductionId = pr.ProductionId
							INNER JOIN Persons AS P on c.PersonId = p.PersonId
						WHERE C.StartOffset <> 0 or C.EndOffset <> 0) AS aa
						WHERE EndOffset + Duration < 0 OR StartOffset > Duration
		END
	END
GO
GRANT EXEC on [CastInvalidOffsetWarning] to DataCleaningAdmin
GO
--#endregion -------- [CastInvalidOffsetWarning]
--#region [DutyEntryContractPeriodWarning]
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].[DutyEntryContractPeriodWarning]'))
BEGIN
	DROP PROCEDURE dbo.[DutyEntryContractPeriodWarning]
END
GO
CREATE PROCEDURE [dbo].[DutyEntryContractPeriodWarning]
		@infoOnly bit
		WITH EXECUTE AS 'dbo'
		AS
		BEGIN
			
		
		IF(@infoOnly=0)
		BEGIN
			DELETE DutyRoster 
			FROM DutyRoster AS dp 
			INNER JOIN Contracts AS c ON dp.ContractId = c.ContractId 
									WHERE dp.Date < c.StartDate OR dp.Date > c.EndDate;
			END
		ELSE
		BEGIN
			SELECT DISTINCT c.ContractId 
			FROM DutyRoster AS dp 
			INNER JOIN Contracts AS c ON dp.ContractId = c.ContractId 
									WHERE dp.Date < c.StartDate OR dp.Date > c.EndDate;
						
		END
	END
GO
GRANT EXEC on [DutyEntryContractPeriodWarning] to DataCleaningAdmin
GO
--#endregion [DutyEntryContractPeriodWarning]

--#region [TravelWithoutTravelstepsWarning]
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].[TravelWithoutTravelstepsWarning]'))
BEGIN
	DROP PROCEDURE dbo.TravelWithoutTravelstepsWarning
END
GO
CREATE PROCEDURE [dbo].TravelWithoutTravelstepsWarning
		@infoOnly bit
		WITH EXECUTE AS 'dbo'
		AS
		BEGIN
			
		
		IF(@infoOnly=0)
		BEGIN
			DELETE Travels 
			FROM Travels LEFT JOIN TravelSteps ON Travels.TravelId = TravelSteps.TravelId 
			WHERE TravelSteps.TravelId IS NULL;
			END
		ELSE
		BEGIN
			SELECT Travels.Description  
			FROM Travels LEFT JOIN TravelSteps ON Travels.TravelId = TravelSteps.TravelId 
			WHERE TravelSteps.TravelId IS NULL;
						
		END
	END
GO
GRANT EXEC on TravelWithoutTravelstepsWarning to DataCleaningAdmin
GO
--#endregion [TravelWithoutTravelstepsWarning]

--#region [RoleCastInWrongActivityWarning]
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].[RoleCastInWrongActivityWarning]'))
BEGIN
	DROP PROCEDURE dbo.RoleCastInWrongActivityWarning
END
GO
CREATE PROCEDURE [dbo].RoleCastInWrongActivityWarning
		@infoOnly bit
		WITH EXECUTE AS 'dbo'
		AS
		BEGIN
		
		IF(@infoOnly=0)
		BEGIN
			DELETE FROM CastBonus 
			WHERE CastId IN (Select BID From (SELECT Cast.CastId as bid, Activities.ProductionId as asnr, Roles.ProductionId as bsnr, Activities.Date, Roles.Name
										FROM Activities 
											INNER JOIN Cast ON Activities.ActivityId = Cast.ActivityId
											INNER JOIN Roles ON Roles.RoleId = Cast.RoleId
										 WHERE (Roles.ProductionId <> Activities.ProductionId AND Roles.RoleId <> 0 AND Roles.ProductionId <> 0)) AS a 
										 LEFT JOIN ProductionChilds ON a.ASNr = ProductionChilds.ProductionId AND a.BSnr = ProductionChilds.ChildProductionId WHERE ChildProductionId IS NULL);

			DELETE FROM Cast WHERE CastId IN (Select BID From (SELECT Cast.CastId as bid, Activities.ProductionId as asnr, Roles.ProductionId as bsnr, Activities.Date, Roles.Name
										FROM Activities 
											INNER JOIN Cast ON Activities.ActivityId = Cast.ActivityId
											INNER JOIN Roles ON Roles.RoleId = Cast.RoleId
										 WHERE (Roles.ProductionId <> Activities.ProductionId AND Roles.RoleId <> 0 AND Roles.ProductionId <> 0)) AS a 
										 LEFT JOIN ProductionChilds ON a.ASNr = ProductionChilds.ProductionId AND a.BSnr = ProductionChilds.ChildProductionId WHERE ChildProductionId IS NULL);
			END
		ELSE
		BEGIN
			SELECT a.Date, a.Name
			FROM (SELECT Cast.CastId as bid, Activities.ProductionId as asnr, Roles.ProductionId as bsnr, Activities.Date, Roles.Name
										FROM Activities 
											INNER JOIN Cast ON Activities.ActivityId = Cast.ActivityId
											INNER JOIN Roles ON Roles.RoleId = Cast.RoleId
										 WHERE (Roles.ProductionId <> Activities.ProductionId AND Roles.RoleId <> 0 AND Roles.ProductionId <> 0)) AS a 
										 LEFT JOIN ProductionChilds ON a.ASNr = ProductionChilds.ProductionId AND a.BSnr = ProductionChilds.ChildProductionId WHERE ChildProductionId IS NULL;
						
		END
	END
GO
GRANT EXEC on RoleCastInWrongActivityWarning to DataCleaningAdmin
GO
--#endregion [RoleCastInWrongActivityWarning]

--#region [CastInProduction0Warning]
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].[CastInProduction0Warning]'))
BEGIN
	DROP PROCEDURE dbo.CastInProduction0Warning
END
GO
CREATE PROCEDURE [dbo].CastInProduction0Warning
		@infoOnly bit
		WITH EXECUTE AS 'dbo'
		AS
		BEGIN
		
		IF(@infoOnly=0)
		BEGIN
			DELETE FROM BasicCast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE RoleId <> 0 AND ProductionId = 0)
			DELETE FROM Cast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE RoleId <> 0 AND ProductionId = 0)
			DELETE FROM CastRepertoire WHERE RoleId IN (SELECT RoleId FROM Roles WHERE RoleId <> 0 AND ProductionId = 0)
			DELETE FROM TechnicalJobs WHERE RoleId IN (SELECT RoleId FROM Roles WHERE RoleId <> 0 AND ProductionId = 0)
			DELETE FROM Roles WHERE RoleId <> 0 AND ProductionId = 0
		END
		ELSE
		BEGIN
			SELECT ISNULL(Name,'NN') FROM Roles WHERE RoleId <> 0 AND ProductionId = 0				
		END
	END
GO
GRANT EXEC on CastInProduction0Warning to DataCleaningAdmin
GO
--#endregion [CastInProduction0Warning]
--#region [InvalidContactWarning]
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].[InvalidContactWarning]'))DROP PROCEDURE dbo.InvalidContactWarning
GO
CREATE PROCEDURE [dbo].InvalidContactWarning
		WITH EXECUTE AS 'dbo'
		AS
		BEGIN
			UPDATE Persons SET AcademicTitle  = NULL WHERE RTRIM(AcademicTitle) = '';
			UPDATE Persons SET FunctionName  = NULL WHERE RTRIM(FunctionName) = '';
			UPDATE Persons SET PersonnelNo = NULL WHERE RTRIM(PersonnelNo) = '';
		END
GO
GRANT EXEC on InvalidContactWarning to DataCleaningAdmin
GO
--#endregion [InvalidContactWarning]
--#region [CastInvalidContractWarning]
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].[CastInvalidContractWarning]'))
BEGIN
	DROP PROCEDURE dbo.CastInvalidContractWarning
END
GO
CREATE PROCEDURE [dbo].CastInvalidContractWarning
		@infoOnly bit
		WITH EXECUTE AS 'dbo'
		AS
		BEGIN
		
		IF(@infoOnly=0)
		BEGIN
			UPDATE Cast SET ContractId = NULL 
					WHERE CastId IN (SELECT Ca.CastId 
							FROM Cast Ca INNER JOIN Contracts AS Co ON Ca.ContractId = Co.ContractId 
										WHERE ca.PersonId <> Co.PersonId);
		END
		ELSE
		BEGIN
			SELECT DISTINCT Ca.ContractID 
					FROM Cast Ca INNER JOIN Contracts AS Co ON Ca.ContractId = Co.ContractId 
					WHERE ca.PersonId <> Co.PersonId;				
		END
	END
GO
GRANT EXEC on CastInvalidContractWarning to DataCleaningAdmin
GO
--#endregion [CastInvalidContractWarning]
--#endregion -------- DH20190621 Warnungen -------------------------------

--#region -------- DH20190626 Index auf ParentActivityID
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.Activities') AND o.Name = 'IX_Activities_ParentActivityId')
BEGIN
	Print('Create IX_Activities_ParentActivityId');
	CREATE NONCLUSTERED INDEX IX_Activities_ParentActivityId  
    ON dbo.Activities (LinkedActivityId)  
    WHERE LinkedActivityId IS NOT NULL ;  
END
GO
--#endregion -------- DH20190626 Index auf ParentActivityID

--#region Orders Datumsspalten auf NOT NULL
ALTER TABLE Orders ALTER COLUMN OrderDate DATE NOT NULL
ALTER TABLE Orders ALTER COLUMN DelivaryUntilDate DATE NULL
ALTER TABLE Orders ALTER COLUMN QuoteDate DATE NULL
GO
--#endregion

--#region PersonContactData Einträge ohne Value oder Bemerkung löschen
DELETE FROM PersonContactData WHERE ISNULL(DataValue,'') = '' AND ISNULL(Note,'') = ''
GO
--#endregion

--#region 20190517 TK

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ContractTypes_ContractFieldTypes') AND [name] = 'ShowOnPage')
BEGIN
	PRINT('Adding ContractTypes_ContractFieldTypes ShowOnPage ...')
	ALTER TABLE dbo.ContractTypes_ContractFieldTypes ADD ShowOnPage TINYINT NOT NULL CONSTRAINT DF_ContractTypes_ContractFieldTypes_ShowOnPage DEFAULT 0
	EXEC ('UPDATE ContractTypes_ContractFieldTypes SET ShowOnPage = 2')
END
GO

IF NOT EXISTS (SELECT * FROM ContractTypes_ContractFieldTypes 
	WHERE ShowOnPage = 0)
BEGIN

	DECLARE @country VARCHAR(20)
	SELECT @country = DataValue FROM Settings WHERE Section = 'Adresse' AND KeyName = 'Country'
	IF @country = 'FI'
		BEGIN--Finnisch
			SET IDENTITY_INSERT ContractFieldTypes  ON
			INSERT INTO ContractFieldTypes (ContractFieldTypeId,[Name],[Code],[Sort],[LM],[UM],[LC],[UC],[DataType],GroupName)
			VALUES 
				(1001, 'Contract text for travels','travel',2,'19000101',0,'19000101',0,1,'Travel/Accommodation'),
				(1002, 'Contract text for accommodation','accommodation',3,'19000101',0,'19000101',0,1,'Travel/Accommodation'),
				(1003, 'Huomautus harjoituksiin','rehearsal',0,'19000101',0,'19000101',0,1,NULL),
				(1004, 'Huomautus esityksiin','performance',1,'19000101',0,'19000101',0,1,NULL),
				(1005, 'Contract supplement','additional',0,'19000101',0,'19000101',0,1,NULL),
				(1006, 'Internal remark','internal',1,'19000101',0,'19000101',0,1,NULL),
				(1007, 'Foreigner tax','foreignersTax',4,'19000101',0,'19000101',0,4,'Muuta'),
				(1008, 'Priority','priority',5,'19000101',0,'19000101',0,4,'Muuta'),
				(1009, 'Osall. palkkaneuvotteluun','feeNegotiation',6,'19000101',0,'19000101',0,4,'Muuta'),
				(1010, 'Lahjoitukset','donations',7,'19000101',0,'19000101',0,4,'Muuta')
			SET IDENTITY_INSERT ContractFieldTypes OFF
		END
	ELSE IF @country = 'EN'
		BEGIN--Englisch
			SET IDENTITY_INSERT ContractFieldTypes  ON
			INSERT INTO ContractFieldTypes (ContractFieldTypeId,[Name],[Code],[Sort],[LM],[UM],[LC],[UC],[DataType],GroupName)
			VALUES 
				(1001, 'Contract text for travels','travel',2,'19000101',0,'19000101',0,1,'Travel/Accommodation'),
				(1002, 'Contract text for accommodation','accommodation',3,'19000101',0,'19000101',0,1,'Travel/Accommodation'),
				(1003, 'Note for rehearsals','rehearsal',0,'19000101',0,'19000101',0,1,NULL),
				(1004, 'Note for performances:','performance',1,'19000101',0,'19000101',0,1,NULL),
				(1005, 'Contract supplement','additional',0,'19000101',0,'19000101',0,1,NULL),
				(1006, 'Internal remark','internal',1,'19000101',0,'19000101',0,1,NULL),
				(1007, 'Foreigner tax','foreignersTax',4,'19000101',0,'19000101',0,4,'Miscellaneous'),
				(1008, 'Priority','priority',5,'19000101',0,'19000101',0,4,'Miscellaneous'),
				(1009, 'Takes part in increase of fees','feeNegotiation',6,'19000101',0,'19000101',0,4,'Miscellaneous'),
				(1010, 'Extra Payment','donations',7,'19000101',0,'19000101',0,4,'Miscellaneous')
			SET IDENTITY_INSERT ContractFieldTypes OFF
		END
	ELSE IF @country = 'F' OR @country = 'BE'
		BEGIN--Französisch
			SET IDENTITY_INSERT ContractFieldTypes  ON
			INSERT INTO ContractFieldTypes (ContractFieldTypeId,[Name],[Code],[Sort],[LM],[UM],[LC],[UC],[DataType],GroupName)
			VALUES 
				(1001, 'Texte contractuel des frais de voyage','travel',2,'19000101',0,'19000101',0,1,'Voyages/hébergement'),
				(1002, 'Vertragstext Unterkunft','accommodation',3,'19000101',0,'19000101',0,1,'Voyages/hébergement'),
				(1003, 'Remarque pour les répétitions :','rehearsal',0,'19000101',0,'19000101',0,1,NULL),
				(1004, 'Remarque pour les représentations','performance',1,'19000101',0,'19000101',0,1,NULL),
				(1005, 'Avenant au contrat','additional',0,'19000101',0,'19000101',0,1,NULL),
				(1006, 'Remarque interne','internal',1,'19000101',0,'19000101',0,1,NULL),
				(1007, 'Impôts pour les étrangers','foreignersTax',4,'19000101',0,'19000101',0,4,'Divers'),
				(1008, 'Priorité','priority',5,'19000101',0,'19000101',0,4,'Divers'),
				(1009, 'Part. aux négoc. cachet','feeNegotiation',6,'19000101',0,'19000101',0,4,'Divers'),
				(1010, 'Allocations','donations',7,'19000101',0,'19000101',0,4,'Divers')
			SET IDENTITY_INSERT ContractFieldTypes OFF
		END
	ELSE IF @country = 'NL'
		BEGIN--Belgien
			SET IDENTITY_INSERT ContractFieldTypes  ON
			INSERT INTO ContractFieldTypes (ContractFieldTypeId,[Name],[Code],[Sort],[LM],[UM],[LC],[UC],[DataType],GroupName)
			VALUES 
				(1001, 'Contracttekst reizen','travel',2,'19000101',0,'19000101',0,1,'Reizen/verblijf'),
				(1002, 'Contracttekst verblijf','accommodation',3,'19000101',0,'19000101',0,1,'Reizen/verblijf'),
				(1003, 'Opmerking voor repetities','rehearsal',0,'19000101',0,'19000101',0,1,NULL),
				(1004, 'Opmerking voor voorstellingen','performance',1,'19000101',0,'19000101',0,1,NULL),
				(1005, 'Toevoeging bij het contract','additional',0,'19000101',0,'19000101',0,1,NULL),
				(1006, 'Interne opmerking','internal',1,'19000101',0,'19000101',0,1,NULL),
				(1007, 'Tax voor buitenlander','foreignersTax',4,'19000101',0,'19000101',0,4,'Overige'),
				(1008, 'Prioriteit','priority',5,'19000101',0,'19000101',0,4,'Overige'),
				(1009, 'Deln. aan gageverh.','feeNegotiation',6,'19000101',0,'19000101',0,4,'Overige'),
				(1010, 'Donaties','donations',7,'19000101',0,'19000101',0,4,'Overige')
			SET IDENTITY_INSERT ContractFieldTypes OFF
		END
	ELSE IF @country = 'CZ'
		BEGIN--Belgien
			SET IDENTITY_INSERT ContractFieldTypes  ON
			INSERT INTO ContractFieldTypes (ContractFieldTypeId,[Name],[Code],[Sort],[LM],[UM],[LC],[UC],[DataType],GroupName)
			VALUES 
				(1001, 'Smluvní text cestovní náklady','travel',2,'19000101',0,'19000101',0,1,'Cesty/ubytování'),
				(1002, 'Smluvní text Ubytování','accommodation',3,'19000101',0,'19000101',0,1,'Cesty/ubytování'),
				(1003, 'Poznámka pro zkoušky','rehearsal',0,'19000101',0,'19000101',0,1,NULL),
				(1004, 'Poznámka pro představení','performance',1,'19000101',0,'19000101',0,1,NULL),
				(1005, 'Dodatek ke smlouvě','additional',0,'19000101',0,'19000101',0,1,NULL),
				(1006, 'Interní poznámka','internal',1,'19000101',0,'19000101',0,1,NULL),
				(1007, 'Srážková daň','foreignersTax',4,'19000101',0,'19000101',0,4,'Ostatní'),
				(1008, 'priorita','priority',5,'19000101',0,'19000101',0,4,'Ostatní'),
				(1009, 'Účastni vyjednávání o honoráři','feeNegotiation',6,'19000101',0,'19000101',0,4,'Ostatní'),
				(1010, 'Dotace','donations',7,'19000101',0,'19000101',0,4,'Ostatní')
			SET IDENTITY_INSERT ContractFieldTypes OFF
		END
	ELSE
		BEGIN
			SET IDENTITY_INSERT ContractFieldTypes  ON
			INSERT INTO ContractFieldTypes (ContractFieldTypeId,[Name],[Code],[Sort],[LM],[UM],[LC],[UC],[DataType],GroupName)
			VALUES 
				(1001, 'Vertragstext Reisen','travel',2,'19000101',0,'19000101',0,1,'Reise/Unterkunft'),
				(1002, 'Vertragstext Unterkunft','accommodation',3,'19000101',0,'19000101',0,1,'Reise/Unterkunft'),
				(1003, 'Bemerkung für Proben','rehearsal',0,'19000101',0,'19000101',0,1,NULL),
				(1004, 'Bemerkung für Vorstellungen','performance',1,'19000101',0,'19000101',0,1,NULL),
				(1005, 'Vertragszusatz','additional',0,'19000101',0,'19000101',0,1,NULL),
				(1006, 'Interne Anmerkung','internal',1,'19000101',0,'19000101',0,1,NULL),
				(1007, 'Ausländersteuer','foreignersTax',4,'19000101',0,'19000101',0,4,'Sonstiges'),
				(1008, 'Priorität','priority',5,'19000101',0,'19000101',0,4,'Sonstiges'),
				(1009, 'Teiln. an Gagenverh.','feeNegotiation',6,'19000101',0,'19000101',0,4,'Sonstiges'),
				(1010, 'Zuwendungen','donations',7,'19000101',0,'19000101',0,4,'Sonstiges')
			SET IDENTITY_INSERT ContractFieldTypes OFF
		END

	INSERT INTO ContractTypes_ContractFieldTypes (ContractFieldTypeId, ContractTypeId,ShowOnPage,LM,UM,LC,UC) SELECT 1005, ContractTypeId,0,'19000101',0,'19000101',0 FROM ContractTypes 
	INSERT INTO ContractTypes_ContractFieldTypes (ContractFieldTypeId, ContractTypeId,ShowOnPage,LM,UM,LC,UC) SELECT 1006, ContractTypeId,0,'19000101',0,'19000101',0 FROM ContractTypes 

	INSERT INTO ContractTypes_ContractFieldTypes (ContractFieldTypeId, ContractTypeId,ShowOnPage,LM,UM,LC,UC) SELECT 1001, ContractTypeId,0,'19000101',0,'19000101',0 FROM ContractTypes WHERE Module = 1 AND ContractTypesCategory <> 255 
	INSERT INTO ContractTypes_ContractFieldTypes (ContractFieldTypeId, ContractTypeId,ShowOnPage,LM,UM,LC,UC) SELECT 1002, ContractTypeId,0,'19000101',0,'19000101',0 FROM ContractTypes WHERE Module = 1 AND ContractTypesCategory <> 255 

	INSERT INTO ContractTypes_ContractFieldTypes (ContractFieldTypeId, ContractTypeId,ShowOnPage,LM,UM,LC,UC) SELECT 1003, ContractTypeId,1,'19000101',0,'19000101',0 FROM ContractTypes WHERE Module = 1 AND ContractTypesCategory <> 255 
	INSERT INTO ContractTypes_ContractFieldTypes (ContractFieldTypeId, ContractTypeId,ShowOnPage,LM,UM,LC,UC) SELECT 1004, ContractTypeId,1,'19000101',0,'19000101',0 FROM ContractTypes WHERE Module = 1 AND ContractTypesCategory <> 255 

	INSERT INTO ContractTypes_ContractFieldTypes (ContractFieldTypeId, ContractTypeId,ShowOnPage,LM,UM,LC,UC) SELECT 1009, ContractTypeId,0,'19000101',0,'19000101',0 FROM ContractTypes WHERE Module = 1 AND ContractTypesCategory = 255 
	INSERT INTO ContractTypes_ContractFieldTypes (ContractFieldTypeId, ContractTypeId,ShowOnPage,LM,UM,LC,UC) SELECT 1010, ContractTypeId,0,'19000101',0,'19000101',0 FROM ContractTypes WHERE Module = 1 AND ContractTypesCategory = 255 

	INSERT INTO ContractTypes_ContractFieldTypes (ContractFieldTypeId, ContractTypeId,ShowOnPage,LM,UM,LC,UC) SELECT 1007, ContractTypeId,0,'19000101',0,'19000101',0 FROM ContractTypes WHERE Module = 1 AND ContractTypesCategory <> 255 
	INSERT INTO ContractTypes_ContractFieldTypes (ContractFieldTypeId, ContractTypeId,ShowOnPage,LM,UM,LC,UC) SELECT 1008, ContractTypeId,0,'19000101',0,'19000101',0 FROM ContractTypes WHERE Module = 1 AND ContractTypesCategory <> 255 


	INSERT INTO  ContractFields (ContractFieldTypeId, ContractId, TextValue,LM,UM,LC,UC)
	SELECT 1001, ContractId, Memo1, ISNULL(lm,'19000101'),ISNULL(um,0), ISNULL(lc,'19000101'),ISNULL(uc,0) FROM ContractDetails WHERE NOT Memo1 IS NULL AND Memo1 <> ''

	INSERT INTO  ContractFields (ContractFieldTypeId,ContractId, TextValue,LM,UM,LC,UC)
	SELECT 1002, ContractId, Memo2, ISNULL(lm,'19000101'),ISNULL(um,0), ISNULL(lc,'19000101'),ISNULL(uc,0) FROM ContractDetails WHERE NOT Memo2 IS NULL AND Memo2 <> ''

	INSERT INTO  ContractFields (ContractFieldTypeId,ContractId, TextValue,LM,UM,LC,UC)
	SELECT 1003, ContractId, Memo3, ISNULL(lm,'19000101'),ISNULL(um,0), ISNULL(lc,'19000101'),ISNULL(uc,0) FROM ContractDetails WHERE NOT Memo3 IS NULL AND Memo3 <> ''

	INSERT INTO  ContractFields (ContractFieldTypeId,ContractId, TextValue,LM,UM,LC,UC)
	SELECT 1004, ContractId, Memo4, ISNULL(lm,'19000101'),ISNULL(um,0), ISNULL(lc,'19000101'),ISNULL(uc,0) FROM ContractDetails WHERE NOT Memo4 IS NULL AND Memo4 <> ''

	INSERT INTO  ContractFields (ContractFieldTypeId,ContractId, TextValue,LM,UM,LC,UC)
	SELECT 1005, ContractId, Memo5, ISNULL(lm,'19000101'),ISNULL(um,0), ISNULL(lc,'19000101'),ISNULL(uc,0) FROM ContractDetails WHERE NOT Memo5 IS NULL AND Memo5 <> ''

	INSERT INTO  ContractFields (ContractFieldTypeId,ContractId, TextValue,LM,UM,LC,UC)
	SELECT 1006, ContractId, Memo6, ISNULL(lm,'19000101'),ISNULL(um,0), ISNULL(lc,'19000101'),ISNULL(uc,0) FROM ContractDetails WHERE NOT Memo6 IS NULL AND Memo6 <> ''

	INSERT INTO  ContractFields (ContractFieldTypeId,ContractId, TextValue,LM,UM,LC,UC)
	SELECT 1007, ContractId, 'True', ISNULL(lm,'19000101'),ISNULL(um,0), ISNULL(lc,'19000101'),ISNULL(uc,0) FROM ContractDetails WHERE NOT ForeignerTax IS NULL AND ForeignerTax = 1

	INSERT INTO  ContractFields (ContractFieldTypeId,ContractId, TextValue,LM,UM,LC,UC)
	SELECT 1008, ContractId, 'True', ISNULL(lm,'19000101'),ISNULL(um,0), ISNULL(lc,'19000101'),ISNULL(uc,0) FROM ContractDetails WHERE NOT HasPriority IS NULL AND HasPriority = 1

	INSERT INTO  ContractFields (ContractFieldTypeId,ContractId, TextValue,LM,UM,LC,UC)
	SELECT 1009, ContractId, 'True', ISNULL(lm,'19000101'),ISNULL(um,0), ISNULL(lc,'19000101'),ISNULL(uc,0) FROM ContractDetails WHERE NOT Optionen IS NULL AND Optionen IN (1,3)

	INSERT INTO  ContractFields (ContractFieldTypeId,ContractId, TextValue,LM,UM,LC,UC)
	SELECT 1010, ContractId, 'True', ISNULL(lm,'19000101'),ISNULL(um,0), ISNULL(lc,'19000101'),ISNULL(uc,0) FROM ContractDetails  WHERE NOT Optionen IS NULL AND Optionen IN (2,3)
END
GO
--#endregion

--#region 20190604 Status

Declare @YearCloseID  int

select @yearcloseid= min([YearCloseTypeId]) from yearclosetypes 
UPDATE [PersonStatusTypes] SET StatusArt = 30 WHERE StatusArt NOT IN (10,11,15,17,20,30)
IF EXISTS(SELECT * FROM [PersonStatusTypes] WHERE StatusArt = 10 AND TimeAccountId IS NULL) AND NOT EXISTS (SELECT * FROM [PersonStatusTypes] WHERE StatusArt = 10 AND NOT TimeAccountId IS NULL) 
BEGIN
	IF EXISTS(SELECT * FROM TimeAccounts WHERE Formel = 3010 AND NOT Module&4=4)
		BEGIN
			UPDATE [PersonStatusTypes] SET TimeAccountId = (SELECT TOP 1 TimeAccountId FROM TimeAccounts WHERE Formel  = 3010 AND NOT Module&4=4) WHERE StatusArt = 10 AND TimeAccountId IS NULL
		END 
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT * FROM TimeAccounts WHERE Formel  = 3010)
		BEGIN
			INSERT INTO TimeAccounts (Name, Formel, Module, YearCloseTypeId, LC, LM) VALUES ('Urlaub' ,3010, 0, @yearcloseid, '19000101','19000101')
		END 
		UPDATE [PersonStatusTypes] SET TimeAccountId = (SELECT TOP 1 TimeAccountId FROM TimeAccounts WHERE Formel  = 3010 ) WHERE StatusArt = 10 AND  TimeAccountId IS NULL
	END
END

IF EXISTS(SELECT * FROM [PersonStatusTypes] WHERE StatusArt = 11 AND TimeAccountId IS NULL) AND NOT EXISTS (SELECT * FROM [PersonStatusTypes] WHERE StatusArt = 11 AND  NOT TimeAccountId IS NULL) 
BEGIN
	IF EXISTS(SELECT * FROM TimeAccounts WHERE Formel = 3011 AND NOT Module&4=4)
		BEGIN
			UPDATE [PersonStatusTypes] SET TimeAccountId = (SELECT TOP 1 TimeAccountId FROM TimeAccounts WHERE Formel = 3011 AND NOT Module&4=4) WHERE StatusArt = 11 AND TimeAccountId IS NULL
		END 
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT * FROM TimeAccounts WHERE Formel = 3011)
		BEGIN
			INSERT INTO TimeAccounts (Name, Formel, Module, YearCloseTypeId, LC, LM) VALUES ('Krank', 3011, 0, @yearcloseid, '19000101','19000101')
		END 
		UPDATE [PersonStatusTypes] SET TimeAccountId = (SELECT TOP 1 TimeAccountId FROM TimeAccounts WHERE Formel  = 3011) WHERE StatusArt = 11 AND NOT TimeAccountId IS NULL
	END
END

IF EXISTS(SELECT * FROM [PersonStatusTypes] WHERE StatusArt = 17 AND TimeAccountId IS NULL) 
BEGIN
	IF EXISTS(SELECT * FROM TimeAccounts WHERE Formel = 3050 AND NOT Module&4=4)
		BEGIN
			UPDATE [PersonStatusTypes] SET TimeAccountId = (SELECT TOP 1 TimeAccountId FROM TimeAccounts WHERE Formel = 3050 AND NOT Module&4=4) WHERE StatusArt = 17 AND TimeAccountId IS NULL
		END 
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT * FROM TimeAccounts WHERE Formel = 3050)
		BEGIN
			INSERT INTO TimeAccounts (Name, Formel, Module, YearCloseTypeId, LC, LM) VALUES ('Frei' ,3050, 0, @yearcloseid, '19000101','19000101')
		END 
		UPDATE [PersonStatusTypes] SET TimeAccountId = (SELECT TOP 1 TimeAccountId FROM TimeAccounts WHERE Formel  = 3050) WHERE StatusArt = 17 AND TimeAccountId IS NULL
	END
END

IF EXISTS(SELECT * FROM [PersonStatusTypes] WHERE StatusArt = 20 AND TimeAccountId IS NULL) 
BEGIN
	UPDATE TimeAccounts SET Formel = 1 WHERE TimeAccountId = 1 AND Formel = 0
	
	IF NOT EXISTS(SELECT * FROM TimeAccounts WHERE Formel = 1)
	BEGIN
		INSERT INTO TimeAccounts (Name, Formel, Module, YearCloseTypeId, LC, LM) VALUES ('Arbeitszeit' ,1 , 0, @yearcloseid, '19000101','19000101')
	END 
	UPDATE [PersonStatusTypes] SET TimeAccountId = (SELECT TOP 1 TimeAccountId FROM TimeAccounts WHERE Formel  = 1) WHERE StatusArt = 20 AND TimeAccountId IS NULL
END

IF EXISTS(SELECT * FROM [PersonStatusTypes] WHERE StatusArt = 30 AND TimeAccountId IS NULL) 
BEGIN
	IF NOT EXISTS(SELECT * FROM TimeAccounts WHERE Formel = 4050)
	BEGIN
		INSERT INTO TimeAccounts (Name, Formel, Module, YearCloseTypeId, LC, LM) VALUES ('Anwesend' , 4050 , 0, @yearcloseid, '19000101','19000101')
	END 
	UPDATE [PersonStatusTypes] SET TimeAccountId = (SELECT TOP 1 TimeAccountId FROM TimeAccounts WHERE Formel  = 4050) WHERE StatusArt = 30 AND TimeAccountId IS NULL
END

IF EXISTS(SELECT * FROM [PersonStatusTypes] WHERE TimeAccountId IS NULL AND CountingType = 0) 
BEGIN
	DECLARE @tid INT
	INSERT INTO TimeAccounts (Name, Formel, Unit, Module, YearCloseTypeId, LC, LM) VALUES ('Abwesend (Stunden)' , 3000 ,1 , 59, @yearcloseid, '19000101','19000101')
	SET @tid = SCOPE_IDENTITY() 
	UPDATE PersonStatusTypes SET TimeAccountId =  @tid WHERE TimeAccountId IS NULL
END

GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ShiftTypes') AND [name] = 'PrintCode')
BEGIN
	PRINT('Adding Dispo PrintCode ...')
	ALTER TABLE dbo.ShiftTypes ADD Code VARCHAR(2) NULL
	ALTER TABLE dbo.ShiftTypes ADD PrintCode VARCHAR(2) NULL
	EXEC('UPDATE ShiftTypes SET Code = LEFT(ShortName,2), PrintCode =  LEFT(ShortName,2) WHERE NOT ShortName IS NULL')
	UPDATE FormulaConfigurations SET SerializedParameter = REPLACE(REPLACE(REPLACE(CAST(SerializedParameter AS VARCHAR(MAX)),'<TypeOfAbsence>Urlaub</TypeOfAbsence>','<Formulas>KontoUrlaub</Formulas>'),'<TypeOfAbsence>Krank</TypeOfAbsence>','<Formulas>KontoKrank</Formulas>'),'<TypeOfAbsence>Free</TypeOfAbsence>','<Formulas>Frei</Formulas>') WHERE FormulaId IN ('CollectiveDutyReportAbsenceFormula','AbsenceCountingFormula')
	UPDATE Permissions SET OptionsFlag = 256 WHERE PermissionArea = 8
END
GO
IF EXISTS (SELECT * FROM sys.sysobjects dc WHERE dc.name = 'CK_PersonStatus_PeriodCheck') ALTER TABLE [dbo].[PersonStatus] DROP CONSTRAINT [CK_PersonStatus_PeriodCheck]
IF EXISTS (SELECT * FROM sys.sysobjects dc WHERE dc.name = 'aaaaaStatusZeitR_PK') ALTER TABLE [dbo].[PersonStatus] DROP CONSTRAINT aaaaaStatusZeitR_PK
IF EXISTS (SELECT * FROM sys.sysobjects dc WHERE dc.name = 'PK_PersonStatus') ALTER TABLE [dbo].[PersonStatus] DROP CONSTRAINT PK_PersonStatus
IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersonStatus') AND o.Name = 'IX_Bis') DROP INDEX PersonStatus.IX_Bis
IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersonStatus') AND o.Name = 'IX_Von') DROP INDEX PersonStatus.IX_Von
GO
PRINT('ALTER PersonStatus Time ...')
ALTER TABLE PersonStatus ALTER COLUMN StartTime TIME(0) NULL
ALTER TABLE PersonStatus ALTER COLUMN EndTime TIME(0) NULL
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersonStatus') AND o.Name = 'IX_PersonStatus_EndDate') 
BEGIN
	PRINT('CREATE Index PersonStatus  ...')
	ALTER TABLE dbo.PersonStatus ADD CONSTRAINT PK_PersonStatus PRIMARY KEY CLUSTERED (PersonStatusId) 
	CREATE NONCLUSTERED INDEX IX_PersonStatus_EndDate ON PersonStatus (EndDate) INCLUDE (StartDate, ApprovalStatus, PersonId, PersonStatusTypeId) ON [PRIMARY]
END
GO
PRINT('Check Status IsCollectiveStatus ...')
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PersonStatusTypes') AND [name] = 'IsCollectiveStatus')
BEGIN
	PRINT('Adding PersonStatusTypes IsCollectiveStatus ...')
	ALTER TABLE PersonStatusTypes ADD IsCollectiveStatus BIT NOT NULL CONSTRAINT DF_PersonStatusTypes_IsCollectiveStatus DEFAULT 0
	EXEC ('UPDATE  [PersonStatusTypes] SET IsCollectiveStatus = 1 WHERE StatusArt = 17')
END
GO
ALTER TABLE PersonStatusTypes ALTER COLUMN TimeAccountId INT NOT NULL
UPDATE PersonStatusTypes SET DefaultApproveStatus = 5 WHERE DefaultApproveStatus IS NULL
ALTER TABLE PersonStatusTypes ALTER COLUMN DefaultApproveStatus TINYINT NOT NULL
GO
ALTER TABLE PersonStatusTypes ALTER COLUMN TemplateStartTime TIME(0) NULL
ALTER TABLE PersonStatusTypes ALTER COLUMN TemplateEndTime TIME(0) NULL
GO
ALTER TABLE ActivityTypes ALTER COLUMN DefaultRehearsalStartTimeMorning TIME(0) NULL
ALTER TABLE ActivityTypes ALTER COLUMN DefaultRehearsalStartTimeEvening TIME(0) NULL
	

GO
ALTER VIEW [dbo].[PublicStatus]
AS
	SELECT			st.*, p.KeyName, p.OwnerGroupId, p.PersonCategoryId, TimeAccountId,
	1 AS AvailableStatus
	FROM			PersonStatus st
		INNER JOIN  Persons			AS P	ON st.PersonId = P.PersonId
		INNER JOIN  PersonCategories			AS pk	ON P.PersonCategoryId = pk.PersonCategoryId
		INNER JOIN  PersonStatusTypes		AS sr	ON st.PersonStatusTypeId = sr.PersonStatusTypeId
	WHERE    
		pk.PersonCategoryType BETWEEN 10 AND 200 
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbPersStatusNameList')) DROP VIEW dbo.AbPersStatusNameList
GO
CREATE VIEW dbo.AbPersStatusNameList
AS 
SELECT 
	CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN sr.PersonStatusTypeId ELSE -1 END AS PersonStatusTypeId,
	CASE WHEN z.Formel = 1 THEN 2  WHEN z.Formel = 4050 THEN 4 ELSE 1 END AS AvailableStatus,
	sr.ApprovalStatus, st.StartDate, st.EndDate, st.StartTime, st.EndTime,
	p.KeyName, p.OwnerGroupId, p.PersonCategoryId
FROM PersonStatus AS sr
	INNER JOIN Persons AS p ON sr.PersonId = p.PersonId 
	INNER JOIN PersonStatus AS st ON sr.PersonStatusId =st.PersonStatusId 
	INNER JOIN PersonStatusTypes AS stt ON sr.PersonStatusTypeId =stt.PersonStatusTypeId 
	INNER JOIN TimeAccounts AS z ON stt.TimeAccountId = z.TimeAccountId
	INNER JOIN Permissions AS ug ON p.OwnerGroupId = ug.OwnerGroupId
	INNER JOIN Users ON ug.Userid = Users.Userid
WHERE Users.Username = CURRENT_USER AND PermissionArea = 8 
GO
GRANT SELECT ON AbPersStatusNameList TO [public]
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Activities') AND o.Name = 'IX_Activities_RehearsalCount')
CREATE NONCLUSTERED INDEX [IX_Activities_RehearsalCount] ON [dbo].[Activities]
(	[ProductionId] ASC,
	[ActivityTypeId] ASC,
	[VariantId] ASC,
	[Date] ASC, [StartTime]
) INCLUDE ([Status]) ON [PRIMARY]
--#endregion

--#region nicht mehr verwendete Spalten aus PlanLayoutContent, Plan, PlanColumns, Persons entfernen
Print ('PlanColumnContent')
GO
dropcolumn 'PlanColumnContent', 'Fett'
GO
dropcolumn 'PlanColumnContent', 'LeerZ'
GO
dropcolumn 'PlanColumnContent', 'Tab'
GO
dropcolumn 'PlanColumnContent', 'Schrift'
GO
dropcolumn 'PlanColumnContent', 'CR'
GO
dropcolumn 'PlanColumnContent', 'Zeichen'
GO
dropcolumn 'PlanColumnContent', 'Gross'
GO
dropcolumn 'PlanColumnContent', 'Underline'
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PlanColumnContent') AND [name] = 'Description')
BEGIN
	PRINT('Adding PlanColumnContent Description ...')
	
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PlanColumnContent') AND o.Name = 'Sort') DROP INDEX PlanColumnContent.Sort
	UPDATE PlanColumnContent SET Sort = 0  WHERE Sort IS NULL
	UPDATE PlanLayouts SET Sort = 0  WHERE Sort IS NULL

	ALTER TABLE PlanColumnContent ALTER COLUMN Sort SMALLINT NOT NULL
	ALTER TABLE PlanLayouts ALTER COLUMN Sort SMALLINT NOT NULL
	IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_PlanColumnContent_Sort') ALTER TABLE PlanColumnContent DROP CONSTRAINT DF_PlanColumnContent_Sort
	ALTER TABLE PlanColumnContent ADD CONSTRAINT DF_PlanColumnContent_Sort DEFAULT 0 FOR Sort
	ALTER TABLE PlanLayouts ADD CONSTRAINT DF_PlanLayouts_Sort DEFAULT 0 FOR Sort
	
	ALTER TABLE PlanColumnContent ADD Description VARCHAR(250) NULL
END
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PlanLayouts') AND [name] = 'Field1')
BEGIN
	Print 'PlanLayouts'
	DELETE FROM PlanColumnContent WHERE PlanColumnId IN (SELECT PlanColumnId FROM PlanColumns WHERE PlanLayoutId IN (SELECT PlanLayoutId FROM PlanLayouts WHERE ISNULL(PlanLayoutType,0) < 10))
	DELETE FROM PlanColumns WHERE PlanLayoutId IN (SELECT PlanLayoutId FROM PlanLayouts WHERE ISNULL(PlanLayoutType,0) < 10)
	DELETE FROM PlanZR WHERE SpalteID IN (SELECT PlanLayoutId FROM PlanLayouts WHERE ISNULL(PlanLayoutType,0) < 10)
	DELETE FROM PlanLayouts WHERE ISNULL(PlanLayoutType,0) < 10
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PlanLayouts') AND o.Name = 'IX_Plan_PlanArt') DROP INDEX PlanLayouts.IX_Plan_PlanArt
	ALTER TABLE PlanLayouts ALTER COLUMN PlanLayoutType TINYINT NOT NULL
	CREATE INDEX IX_PlanLayouts_PlanLayoutType ON PlanLayouts (PlanLayoutType)
	UPDATE PlanLayouts SET NAME = '--' WHERE Name IS NULL 
	ALTER TABLE PlanLayouts ALTER COLUMN NAME VARCHAR(50) NOT NULL
	ALTER TABLE PlanLayouts ALTER COLUMN Note VARCHAR(500) NULL

	EXEC sp_rename  'PlanLayouts.T2', 'Field2', 'COLUMN'
	EXEC sp_rename  'PlanLayouts.T3', 'Field3', 'COLUMN'
	EXEC sp_rename  'PlanLayouts.F1', 'Field4', 'COLUMN'
	EXEC sp_rename  'PlanLayouts.EndTime1', 'Field5', 'COLUMN'
	EXEC sp_rename  'PlanLayouts.T1', 'Field1', 'COLUMN'
END
GO
IF  EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RapportColumns') AND [name] = 'Sort' AND system_type_id = 48)
BEGIN
	Print 'RapportColumns.Sort'
	IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_RapportColumns_Sort') ALTER TABLE RapportColumns DROP CONSTRAINT DF_RapportColumns_Sort
	ALTER TABLE RapportColumns ALTER COLUMN Sort SMALLINT NOT NULL
	ALTER TABLE RapportColumns ADD CONSTRAINT DF_RapportColumns_Sort DEFAULT 0 FOR Sort
	ALTER TABLE RapportColumns ALTER COLUMN HeaderText1 VARCHAR(20) NULL
	UPDATE TimeAccounts SET Name = CAST([TimeAccountId] AS VARCHAR(MAX)) WHERE Name IS NULL
	ALTER TABLE TimeAccounts ALTER COLUMN Name VARCHAR(30) NOT NULL
END
GO
dropcolumn 'PlanColumns', 'VsPro'
GO
dropcolumn 'PlanLayouts', 'Nachbis'
GO
dropcolumn 'PlanLayouts', 'StdStab'
GO
dropcolumn 'PlanLayouts', 'T3Ausri'
GO
dropcolumn 'PlanLayouts', 'T1Fett'
GO
dropcolumn 'PlanLayouts', 'T2Fett'
GO
dropcolumn 'PlanLayouts', 'T3Fett'
GO
dropcolumn 'PlanLayouts', 'T1Schrift'
GO
dropcolumn 'PlanLayouts', 'T2Schrift'
GO
dropcolumn 'PlanLayouts', 'F1Ausri'
GO
dropcolumn 'PlanLayouts', 'NachVon'
GO
dropcolumn 'PlanLayouts', 'BesetzungSort'
GO
dropcolumn 'PlanLayouts', 'VName'
GO
dropcolumn 'PlanLayouts', 'Besetzung'
GO
dropcolumn 'PlanLayouts', 'T3Schrift'
GO
dropcolumn 'PlanLayouts', 'TrennRegie'
GO
dropcolumn 'PlanLayouts', 'TrennSoli'
GO
dropcolumn 'PlanLayouts', 'Usort'
GO
dropcolumn 'PlanLayouts', 'ZrSort'
GO
dropcolumn 'PlanLayouts', 'AboPos'
GO
dropcolumn 'PlanLayouts', 'T2Ausri'
GO
dropcolumn 'PlanLayouts', 'Oben'
GO
dropcolumn 'PlanLayouts', 'Datumsformat'
GO
dropcolumn 'PlanLayouts', 'Dekade'
GO
dropcolumn 'PlanLayouts', 'AbendUntenCR'
GO
dropcolumn 'PlanLayouts', 'VsFett'
GO
dropcolumn 'PlanLayouts', 'CrDel'
GO
dropcolumn 'PlanLayouts', 'CrDir'
GO
dropcolumn 'PlanLayouts', 'AboLang'
GO
dropcolumn 'PlanLayouts', 'Zeiten'
GO
dropcolumn 'PlanLayouts', 'AbendUnten'
GO
dropcolumn 'PlanLayouts', 'GastGross'
GO
dropcolumn 'PlanLayouts', 'Wochenteilung'
GO
dropcolumn 'PlanLayouts', 'datumsformatWT'
GO
dropcolumn 'PlanLayouts', 'ZeileAuff'
GO
dropcolumn 'PlanLayouts', 'Makro'
GO
dropcolumn 'PlanLayouts', 'KeyName'
GO
dropcolumn 'PlanLayouts', 'ProdAllePro'
GO
dropcolumn 'PlanLayouts', 'Links'
GO
dropcolumn 'PlanLayouts', 'F1Schrift'
GO
dropcolumn 'PlanLayouts', 'AblageDatei'
GO
dropcolumn 'PlanLayouts', 'VorStab'
GO
dropcolumn 'PlanLayouts', 'VorSoli'
GO
dropcolumn 'PlanLayouts', 'ProdSnr'
GO
dropcolumn 'PlanLayouts', 'PremFarbe'
GO
dropcolumn 'PlanLayouts', 'TageTrennung'
GO
dropcolumn 'PlanLayouts', 'VorHerren'
GO
dropcolumn 'PlanLayouts', 'SoliStr'
GO
dropcolumn 'PlanLayouts', 'LtgStr'
GO
dropcolumn 'PlanLayouts', 'AboZr'
GO
dropcolumn 'PlanLayouts', 'SortZrProTag'
GO
dropcolumn 'PlanLayouts', 'ProdPlanTitel'
GO
dropcolumn 'PlanLayouts', 'nurPremWA'
GO
dropcolumn 'PlanLayouts', 'ProdCheckGegen'
GO
dropcolumn 'PlanLayouts', 'Schriftart'
GO
dropcolumn 'PlanLayouts', 'AutoAusgabe'
GO
dropcolumn 'PlanLayouts', 'B1Fett'
GO
dropcolumn 'PlanLayouts', 'B1Schrift'
GO
dropcolumn 'PlanLayouts', 'B1Ausri'
GO
dropcolumn 'PlanLayouts', 'T1Ausri'
GO
dropcolumn 'PlanLayouts', 'Rahmen'
GO
dropcolumn 'PlanLayouts', 'Regie'
GO
dropcolumn 'PlanLayouts', 'AusgabeIn'
GO
dropcolumn 'PlanLayouts', 'Unten'
GO
dropcolumn 'PlanLayouts', 'Rechts'
GO
dropcolumn 'PlanLayouts', 'IsLandscape'
GO
dropcolumn 'PlanLayouts', 'A3'
GO
dropcolumn 'PlanLayouts', 'F1Fett'
GO
dropcolumn 'PlanLayouts', 'von'
GO
dropcolumn 'PlanLayouts', 'bis'
GO
dropcolumn 'PlanLayouts', 'PlanExportID'
GO
dropcolumn 'Persons', 'IsSecret'
GO
--#endregion

--#region 20190626
Print ('Check	AllocationGroup.Settings')
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('AllocationGroup') AND [name] = 'Settings')
BEGIN
	PRINT('Add	AllocationGroup.Settings')
	ALTER TABLE AllocationGroup ADD Settings XML NULL
END
GO


Print ('Check	FK_Activities_Activities_LinkedActivityId')
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Activities_Activities_LinkedActivityId') AND type = 'F') 
BEGIN
Print ('Add	FK_Activities_Activities_LinkedActivityId')
	UPDATE Activities SET LinkedActivityId = NULL WHERE NOT LinkedActivityId IS NULL AND  NOT EXISTS (SELECT * FROM Activities AS s WHERE s.ActivityId = Activities.LinkedActivityId)
	ALTER TABLE Activities  WITH CHECK ADD CONSTRAINT FK_Activities_Activities_LinkedActivityId FOREIGN KEY(LinkedActivityId)
	REFERENCES Activities (ActivityId)
	ALTER TABLE Activities CHECK CONSTRAINT FK_Activities_Activities_LinkedActivityId
END
GO
Print ('Check	FK_ContractDepartments_Contracts')
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ContractDepartments_Contracts') AND type = 'F') 
BEGIN

	IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_ContractDepartments_SpecialLeaveDays') ALTER TABLE ContractDepartments DROP CONSTRAINT DF_ContractDepartments_SpecialLeaveDays
	ALTER TABLE ContractDepartments ALTER COLUMN SpecialLeaveDays TINYINT NOT NULL
	ALTER TABLE ContractDepartments ADD CONSTRAINT DF_ContractDepartments_SpecialLeaveDays DEFAULT 0 FOR SpecialLeaveDays
	IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_ContractDepartments_HandicappedLeaveDays') ALTER TABLE ContractDepartments DROP CONSTRAINT DF_ContractDepartments_HandicappedLeaveDays
	ALTER TABLE ContractDepartments ALTER COLUMN HandicappedLeaveDays TINYINT NOT NULL
	ALTER TABLE ContractDepartments ADD CONSTRAINT DF_ContractDepartments_HandicappedLeaveDays DEFAULT 0 FOR HandicappedLeaveDays

	Print ('Add	FK_Contract_Departmentcontract')
	UPDATE ContractDepartments SET CopyShiftFromContractId = NULL WHERE NOT CopyShiftFromContractId IS NULL AND  NOT EXISTS (SELECT * FROM Contracts AS s WHERE s.ContractId = ContractDepartments.ContractId)
	ALTER TABLE ContractDepartments  WITH CHECK ADD CONSTRAINT FK_ContractDepartments_Contracts FOREIGN KEY(CopyShiftFromContractId)
	REFERENCES Contracts (ContractId)
	ALTER TABLE ContractDepartments CHECK CONSTRAINT FK_ContractDepartments_Contracts
END
GO
--#endregion

--#region
GO
dropcolumn 'ActivitySubscriptions', 'PlAbend'
GO
Print ('Check	NumberOfSeats')
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ActivityDetails') AND [name] = 'NumberOfSeats')
BEGIN
	PRINT('Add	NumberOfSeats')
	ALTER TABLE ActivityDetails ADD NumberOfSeats SMALLINT NULL
	ALTER TABLE ActivityDetails ADD PriceCategoryId INT NULL

	ALTER TABLE ActivityDetails WITH CHECK ADD  CONSTRAINT FK_ActivityDetails_PriceCategories FOREIGN KEY(PriceCategoryId)
	REFERENCES PriceCategories (PriceCategoryId)
	ALTER TABLE ActivityDetails CHECK CONSTRAINT FK_ActivityDetails_PriceCategories

	EXEC ('INSERT INTO ActivityDetails (ActivityId, lm, lc, um, uc)
		SELECT ActivityId,  a.lm, a.lc, a.um, a.uc FROM Activities AS a INNER JOIN Locations  on a.LocationId = Locations.LocationId 
			INNER JOIN ActivityTypes ON a.ActivityTypeId = ActivityTypes.ActivityTypeId
			WHERE ActivityTypes.Category > 1000  AND ((ISNULL(PL, 0) <> 0 AND PL <> Locations.Places) OR NOT PriceCategoryId IS NULL) AND NOT EXISTS (SELECT * FROM ActivityDetails WHERE a.ActivityId = ActivityDetails.ActivityId )')
	EXEC ('UPDATE ActivityDetails SET PriceCategoryId = Activities.PriceCategoryId, NumberOfSeats = pl FROM ActivityDetails INNER JOIN Activities ON ActivityDetails.ActivityId = Activities.ActivityId')
	IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.SetActivetyDetails')) DROP PROCEDURE SetActivetyDetails
	IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.SP_SetPreis')) DROP PROCEDURE SP_SetPreis
END
GO

ALTER PROCEDURE [dbo].[GetActivitiesInternal]
	@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.StartDate), @permissionPeriodEnd = MAX(s.EndDate)
		FROM Seasons AS s
			INNER JOIN SeasonPermissions AS us	ON s.SeasonId = us.SeasonId
		WHERE us.UserId = @userId 

	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 (PermissionId INT NOT NULL, PermissionArea INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #Permissions SELECT Permissions.OwnerGroupId, Permissions.PermissionArea, OptionsFlag  FROM Permissions WHERE UserId = @userId AND PermissionArea 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  =', Activities.ActivityId, Activities.LocationId,
					Activities.Date, Activities.StartTime, Activities.EndTime, Activities.PrintEndTime, Activities.PrintStartTime,  
					Activities.Status, Activities.LinkedActivityId, Activities.IsSecret, Activities.CreateCountDownId, 
					Activities.IsTimeSpan, Activities.IsExtraPayLiable, Activities.VariantId, 
					Activities.LM, Activities.UM, Activities.LC, Activities.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  Activities.ActivityId, CASE WHEN  Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1)  THEN 1	ELSE 0 END'

			SET @secretfields  =       'CASE WHEN NoPermission = 1 THEN -100 ELSE Activities.ProductionId		END	AS ProductionId,
										CASE WHEN NoPermission = 1 THEN 0	 ELSE Activities.ActivityTypeId		END	AS ActivityTypeId,
										CASE WHEN NoPermission = 1 THEN NULL ELSE Activities.LongNote		END	AS LongNote,
										CASE WHEN NoPermission = 1 THEN NULL ELSE Activities.ArtisticNote	END AS ArtisticNote,
										CASE WHEN NoPermission = 1 THEN NULL ELSE Activities.TechnicalNote END AS TechnicalNote'
		END
	ELSE
		BEGIN
			IF (@ShowActivitiesWithoutRights = 1)
				
				SET @secretfields  =   'CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN -100 ELSE Activities.ProductionId		END	AS ProductionId,
										CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN 0	 ELSE Activities.ActivityTypeId		END	AS ActivityTypeId,
										CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN NULL ELSE Activities.LongNote			END	AS LongNote,
										CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN NULL ELSE Activities.ArtisticNote	END AS ArtisticNote,
										CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN NULL ELSE Activities.TechnicalNote END AS TechnicalNote'
			ELSE 
				SET @secretfields  =   'Activities.ProductionId,
										Activities.ActivityTypeId,
										Activities.LongNote,
										Activities.ArtisticNote,
										Activities.TechnicalNote'

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

	-- ***	Immer auf Produktionen unf Berechtigungen ***
		SET @SQLQuery =  @SQLQuery + '	 FROM  Activities 
										INNER JOIN  Productions AS p ON Activities.ProductionId = p.ProductionId '

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

	-- *** Weitere Joins ***	 
		IF (@joins&1 = 1)
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN ActivityDetails ON Activities.ActivityId = ActivityDetails.ActivityId '

		IF (@joins&4 = 4 OR (@include = 0 AND CHARINDEX('Locations.', @order) > 0 )) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN Locations ON Activities.LocationId = Locations.LocationId '

		IF (@joins&8 = 8 OR (@include = 0 AND CHARINDEX('ActivityTypes.', @order) > 0 )) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN ActivityTypes ON Activities.ActivityTypeId = ActivityTypes.ActivityTypeId '

		IF (@joins&16 = 16)
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN ProductionDetails ON Activities.ProductionId = ProductionDetails.ProductionId '

		IF (@joins&32 = 32)
			SET @SQLQuery = @SQLQuery + ' INNER JOIN OwnerGroups ON p.OwnerGroupId = OwnerGroups.OwnerGroupId '
			
		SET @SQLQuery = @SQLQuery + ' WHERE Activities.Date 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 IsSecret erforderlich
		IF (EXISTS(SELECT * FROM #Permissions WHERE PermissionArea = 2 AND OptionsFlag&1 <> 1)) 
		BEGIN
			IF (@ShowActivitiesWithoutRights = 0)
					SET @SQLQuery = @SQLQuery  + ' AND (Activities.IsSecret = 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 Activities AS Activities 
																	INNER JOIN  #ActivitiesNP ON Activities.ActivityId = #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('Locations.', @order) > 0) BEGIN
					SET @SQLQuery = @SQLQuery + ' INNER JOIN Locations ON Activities.LocationId = Locations.LocationId '
				END
				IF (CHARINDEX('Title', @order) > 0) BEGIN
					SET @SQLQuery = @SQLQuery + ' INNER JOIN  Productions AS p ON Activities.ProductionId = p.ProductionId '
				END
				IF (CHARINDEX('ActivityTypes', @order) > 0) BEGIN
					SET @SQLQuery = @SQLQuery + ' INNER JOIN ActivityTypes ON Activities.ActivityTypeId = ActivityTypes.ActivityTypeId '
				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], ActivityDetails.*
		FROM ActivityDetails 
			INNER JOIN #ActivitiesNP On ActivityDetails.ActivityId = #ActivitiesNP.ActivityId

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

	IF (@include&4 = 4)
		SELECT NULL AS [#4], ActivitySubscriptions.*, Subscriptions.SubscriptionTypeId
		FROM ActivitySubscriptions 
			INNER JOIN Subscriptions ON ActivitySubscriptions.SubscriptionId = Subscriptions.SubscriptionId
			INNER JOIN #ActivitiesNP ON ActivitySubscriptions.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&8 = 8)
		SELECT NULL AS [#8], B.CastId, B.RoleId, CASE WHEN B.IsSecret = 1 AND ug.OptionsFlag&1 <> 1 THEN -1 ELSE b.PersonId END AS PersonId, B.ActivityId, B.StartOffset, B.EndOffset, B.Note, B.PrintMode, B.LM, B.UM, B.LC, B.UC, B.IsSecret, B.GroupPosition, B.CastStatusId,
					B.IsCover, B.IsCanceled, B.Creditable, B.BackColorArgb, B.IsReplacement, B.ContractId
		FROM Cast AS B 
			INNER JOIN #ActivitiesNP ON B.ActivityId = #ActivitiesNP.ActivityId
			INNER JOIN Roles ON Roles.RoleId = B.RoleId
			INNER JOIN #Permissions AS UG ON UG.PermissionId  = Roles.OwnerGroupId AND  ug.PermissionArea = 4 AND (@ShowActivitiesWithoutRights = 1 OR B.IsSecret = 0 OR ug.OptionsFlag&1 = 1)	

	IF (@include&16 = 16) 
	BEGIN
		DECLARE @changeSince DATETIME
		SET @changeSince = GETDATE() - 21 
		SELECT NULL AS [#16],ax.*
		FROM  ActivityHistory AS ax
			INNER JOIN #ActivitiesNP ON ax.ActivityId = #ActivitiesNP.ActivityId
			LEFT JOIN (SELECT xhid FROM HistoryConfirmations WHERE TableName = 'Activities' 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], ActivityDepartmentData.*
		FROM ActivityDepartmentData 
			INNER JOIN #ActivitiesNP ON ActivityDepartmentData.ActivityId = #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], TechnicalJobs.*
		FROM TechnicalJobs 
			INNER JOIN #ActivitiesNP ON TechnicalJobs.ActivityId = #ActivitiesNP.ActivityId

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

--#endregion

--#endregion -------- (4.194.x) -------------------------------

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

--#region Bugfix Arbeitsbereiche Dispo DH 20190812
GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.WorkAreas to DispoAdmin
GO
--#endregion Bugfix Arbeitsbereiche Dispo DH 20190812

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

--#region ----------- 4.195.x ---------------------------------

--#region 2019-08-02 Bankdatenschreiben ohne Schreibrecht auf Person
ALTER VIEW [dbo].[AbBankAccount_Update]
AS
	SELECT  BankAccounts.*  FROM  BankAccounts WHERE PersonId IN (SELECT pp.PersonId 
	FROM Persons AS PP
		INNER JOIN Permissions AS UG ON pp.OwnerGroupId =  UG.OwnerGroupId 
		INNER JOIN Users ON Ug.Userid = Users.Userid 
	WHERE  ug.PermissionArea = 0 AND ug.OptionsFlag & 32 = 32 AND Username = CURRENT_USER GROUP BY pp.PersonId)

	WITH CHECK OPTION
GO
--#endregion 2019-08-02 Bankdatenschreiben ohne Schreibrecht auf Person

--#region 2019-08-28 DH Spielzeitstart Pro Abteilung
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('SeasonOwnerGroupSettings') AND [name] = 'SeasonStartDate')
BEGIN
	PRINT('Adding column SeasonOwnerGroupSettings.SeasonStartDate ...')
	ALTER TABLE dbo.SeasonOwnerGroupSettings ADD SeasonStartDate DATE NULL
	ALTER TABLE dbo.SeasonOwnerGroupSettings ADD SeasonEndDate DATE NULL
END
GO
IF EXISTS (SELECT * FROM dbo.Seasons st WHERE st.OrchestraStartDate IS NOT NULL AND st.OrchestraStartDate <> st.StartDate )
BEGIN
	PRINT('Updating SeasonOwnerGroupSettings.SeasonStart ...')
-- Alle abweichenden Orchesterstarttermine eintragen
	INSERT INTO dbo.SeasonOwnerGroupSettings (SeasonId, OwnerGroupId, seasonStartDate, lm, lc, uc, um)
		SELECT st.SeasonId, g.OwnerGroupId, st.OrchestraStartDate, GETDATE(), GETDATE(), -1, -1 FROM dbo.Seasons st CROSS JOIN OwnerGroups g 
		WHERE st.OrchestraStartDate IS NOT NULL AND st.OrchestraStartDate <> st.StartDate AND g.Modul IN(2, 16, 32) 
		AND NOT EXISTS (SELECT  * FROM SeasonOwnerGroupSettings a WHERE a.SeasonId =st.SeasonId AND a.OwnerGroupId =  g.OwnerGroupId  )
END
GO
--#endregion 2019-08-28 DH Spielzeitstart Pro Abteilung

--#region SH 2019-08-15 Reminders

--#region Tabelle Reminder löschen
IF EXISTS (SELECT * FROM sys.tables WHERE [name]='Reminder')
BEGIN
	PRINT 'Deleting table Reminder...'
	DROP TABLE [Reminder]
END
GO
--#endregion Tabelle Reminder löschen

--#region Tabelle Reminders anlegen
IF NOT EXISTS (SELECT * FROM sys.tables WHERE [name]='Reminders')
BEGIN
       PRINT 'Creating table Reminders...'
       CREATE TABLE [Reminders](
             [ReminderId] INT IDENTITY(1,1) NOT NULL,
             [UserId] INT NOT NULL, --benachrichtigter benutzer/benutzergruppe
			 [ObjectId] INT NOT NULL, -- id vom objekt an dem der reminder hängt
			 [ObjectTypeId] INT NOT NULL, -- id vom objekttyp (person, vertrag, etc.) an dem der reminder hängt
			 [Time] SMALLDATETIME NULL, -- datum und uhrzeit wann die erinnerung angezeigt wird
			 [Completed] BIT NOT NULL CONSTRAINT DF_Reminders_Completed DEFAULT 0, -- erledigt
			 [Text] NVARCHAR(max) NULL, -- text
			 [OwnerGroupId] INT NOT NULL, --besitzer
             [LM] SMALLDATETIME NOT NULL,
             [UM] INT NULL,
             [LC] SMALLDATETIME NOT NULL,
             [UC] INT NULL,
             --CONSTRAINT PK_Reminders PRIMARY KEY CLUSTERED (ReminderId) ON [PRIMARY],
             CONSTRAINT FK_Reminders_OwnerGroups FOREIGN KEY(OwnerGroupId) REFERENCES OwnerGroups (OwnerGroupId),
			 CONSTRAINT FK_Reminders_Users FOREIGN KEY(UserId) REFERENCES Users (UserId) ON DELETE CASCADE
       ) ON [PRIMARY]

	   	CREATE CLUSTERED INDEX IX_Reminders_ObjectId_ObjectTypeId ON Reminders (ObjectId, ObjectTypeId) ON [PRIMARY]
		CREATE NONCLUSTERED INDEX IX_Reminders_Completed_Time_LM ON Reminders  (Completed, Time, LM) ON [PRIMARY]
END
GO
--#endregion Tabelle Reminders anlegen

--#region View AbReminders
IF EXISTS (SELECT * FROM sys.views WHERE [name]='AbReminders')
BEGIN
	DROP VIEW [AbReminders]
END
GO

PRINT 'Creating view AbReminders...'
GO

CREATE VIEW dbo.[AbReminders]
AS 
	SELECT r.*
	FROM [Reminders] r
	INNER JOIN [Users] ru ON ru.UserId = r.UserId
	WHERE
		r.OwnerGroupId IN (
			SELECT ug.OwnerGroupId FROM Permissions ug
			INNER JOIN Users up ON ug.UserID = up.UserID
			WHERE ug.PermissionArea = 19 AND up.UserName = CURRENT_USER
		)
		OR (ru.IsGroup = 0 AND ru.UserName = CURRENT_USER)
		OR (ru.IsGroup = 1 AND ru.UserId IN (
			SELECT uig.GroupId
			FROM UsersInGroups uig
			INNER JOIN Users up ON uig.UserId = up.UserId
			WHERE up.UserName = CURRENT_USER))
GO
GRANT SELECT ON [AbReminders] to Public
GO

--#endregion View AbReminders

--#region View AbReminders_Update

IF EXISTS (SELECT * FROM sys.views WHERE [name]='AbReminders_Update')
BEGIN
	DROP VIEW [AbReminders_Update]
END
GO

PRINT 'Creating view AbReminders_Update...'
GO

CREATE VIEW dbo.[AbReminders_Update]
AS
	SELECT * FROM [Reminders] WHERE [ReminderId] IN (
			SELECT r.ReminderId
			FROM [Reminders] r
			INNER JOIN [Users] ru ON ru.UserId = r.UserId
			WHERE
				r.OwnerGroupId IN (
					SELECT ug.OwnerGroupId FROM Permissions ug
					INNER JOIN Users up ON ug.UserID = up.UserID
					WHERE ug.PermissionArea = 19 AND up.UserName = CURRENT_USER
				)
				OR (ru.IsGroup = 0 AND ru.UserName = CURRENT_USER)
				OR (ru.IsGroup = 1 AND ru.UserId IN (
					SELECT uig.GroupId
					FROM UsersInGroups uig
					INNER JOIN Users up ON uig.UserId = up.UserId
					WHERE up.UserName = CURRENT_USER))
	)
GO

GRANT SELECT, UPDATE, INSERT, DELETE ON [AbReminders_Update] to Public
GO

--#endregion View AbReminders_Update

--#endregion SH 2019-08-15 Reminders

--#region TK 2019-07-04 BasicCast Umbau

--#region BasicCast Tabelle und Views

IF EXISTS(SELECT * FROM sysobjects o WHERE o.name = 'BasicCast') EXEC sp_rename 'BasicCast', 'BasicCast' 
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.BasicCast') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	Print 'Table BasicCast'
	CREATE TABLE dbo.BasicCast (
		BasicCastId INT IDENTITY(1,1) NOT NULL,
		RoleId INT NOT NULL,
		PersonId INT NOT NULL,
		SeasonId INT NULL,
		UnderstudyPosition TINYINT NOT NULL CONSTRAINT DF_BasicCast_UnderstudyPosition DEFAULT 1,
		GroupPosition SMALLINT NOT NULL CONSTRAINT DF_BasicCast_GroupPosition DEFAULT 1,
		IsSecret BIT NOT NULL CONSTRAINT DF_BasicCast_IsSecret DEFAULT 0,
		Note VARCHAR(256) SPARSE NULL,
		LM SMALLDATETIME NOT NULL,
		UM INT NULL,
		LC SMALLDATETIME NOT NULL,
		UC INT NULL,
		CONSTRAINT PK_BasicCast PRIMARY KEY NONCLUSTERED (BasicCastId),
		CONSTRAINT FK_BasicCast_Roles FOREIGN KEY(RoleId) REFERENCES Roles (RoleId),
		CONSTRAINT FK_BasicCast_Persons FOREIGN KEY(PersonId) REFERENCES Persons (PersonId),
		CONSTRAINT FK_BasicCast_Seasons FOREIGN KEY(SeasonId) REFERENCES Seasons (SeasonId),
	) ON [PRIMARY]
	CREATE CLUSTERED INDEX IX_BasicCast_Seasons_Roles ON BasicCast (SeasonId, RoleId)
	CREATE INDEX IX_BasicCast_Persons ON BasicCast (PersonId)

	ALTER TABLE BasicCast WITH CHECK ADD CONSTRAINT CK_BasicCast_UnderstudyPosition
	CHECK (UnderstudyPosition > 0)
	ALTER TABLE BasicCast CHECK CONSTRAINT CK_BasicCast_UnderstudyPosition

	DECLARE @upf INT
	SET @upf = 3
	SET IDENTITY_INSERT BasicCast ON
	INSERT INTO BasicCast (BasicCastId, RoleId, PersonId, IsSecret, GroupPosition, UnderstudyPosition, SeasonId, lm, um, lc, uc, Note)
		SELECT BesetzungStdSoliId, bs.RoleId, Persnr1, IsPerson1Locked|IsSecret AS locked, GroupPosition,
			   CASE WHEN  UnderstudyPosition >= @upf AND OwnerGroups.Modul NOT IN (2,16) THEN UnderstudyPosition+2 ELSE UnderstudyPosition+1 END,
			   CASE WHEN SeasonId = 0 THEN NULL ELSE SeasonId END, bs.lm, bs.um, bs.lm, bs.uc, bs.Note
			FROM BesetzungStdSoliTabelle AS bs 
				INNER JOIN Roles ON bs.RoleId = Roles.RoleId
				INNER JOIN OwnerGroups ON Roles.OwnerGroupId = OwnerGroups.OwnerGroupId
			WHERE NOT Persnr1 IS NULL AND SeasonId IN (SELECT SeasonId FROM Seasons) AND Persnr1 IN (SELECT PersonId FROM Persons)
	SET IDENTITY_INSERT BasicCast OFF

	INSERT INTO BasicCast (RoleId, PersonId, IsSecret, GroupPosition,UnderstudyPosition, SeasonId, lm, um, lc, uc)
		SELECT RoleId, Persnr2, IsPerson2Locked|IsSecret AS locked, GroupPosition, UnderstudyPosition + 2, CASE WHEN SeasonId = 0 THEN NULL ELSE SeasonId END, lm, um, lc, uc
			FROM BesetzungStdSoliTabelle
			WHERE NOT Persnr2 IS NULL AND SeasonId IN (SELECT SeasonId FROM Seasons) AND Persnr2 IN (SELECT PersonId FROM Persons)

	INSERT INTO BasicCast (RoleId, PersonId, IsSecret, GroupPosition, UnderstudyPosition, SeasonId, lm, um, lc, uc)
		SELECT RoleId, Persnr3, IsPerson3Locked|IsSecret AS locked, GroupPosition, UnderstudyPosition + 3, CASE WHEN SeasonId = 0 THEN NULL ELSE SeasonId END, lm, um, lc, uc
			FROM BesetzungStdSoliTabelle
			WHERE NOT Persnr3 IS NULL AND SeasonId IN (SELECT SeasonId FROM Seasons) AND Persnr3 IN (SELECT PersonId FROM Persons) 

	INSERT INTO BasicCast (RoleId, PersonId, IsSecret, GroupPosition, UnderstudyPosition, SeasonId, lm, um, lc, uc)
		SELECT RoleId, Persnr4, IsPerson4Locked|IsSecret AS locked, GroupPosition, UnderstudyPosition + 4, CASE WHEN SeasonId = 0 THEN NULL ELSE SeasonId END, lm, um, lc, uc
			FROM BesetzungStdSoliTabelle
			WHERE NOT Persnr4 IS NULL AND SeasonId IN (SELECT SeasonId FROM Seasons) AND Persnr4 IN (SELECT PersonId FROM Persons)
	Print 'Role_Season IsSecret'
	ALTER TABLE Role_Season ADD IsSecret BIT NOT NULL CONSTRAINT DF_Role_Season_IsSecret DEFAULT 0
	EXEC('INSERT INTO Role_Season (RoleId, SeasonId, IsSecret, lm, um, lc, uc)
			SELECT RoleId, SeasonId, 1 ,MAX(''19000101''), MAX(ISNULL(um,-1)), MAX(ISNULL(lm,''19000101'')), MAX(ISNULL(uc,-1)) FROM BesetzungStdSoliTabelle WHERE IsSecret = 1 AND  NOT EXISTS (SELECT * FROM Role_Season AS rs WHERE RoleId= rs.RoleId AND SeasonId = rs.SeasonId ) GROUP BY  RoleId, SeasonId')
END
GO
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.BesetzungStdSoli'))  DROP VIEW dbo.BesetzungStdSoli
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_BasicCastHistory_BesetzungStdSoliTabelle_BasicCastId') AND type = 'F') 
	ALTER TABLE [dbo].[BasicCastHistory] DROP CONSTRAINT FK_BasicCastHistory_BesetzungStdSoliTabelle_BasicCastId
GO
ALTER TABLE BasicCastHistory ALTER COLUMN SeasonId INT NULL
UPDATE BasicCastHistory SET SeasonId = NULL WHERE SeasonId = 0

GO
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.ABBasicCast'))  DROP VIEW dbo.ABBasicCast
GO
CREATE VIEW [dbo].ABBasicCast
AS
SELECT bc.*
FROM  BasicCast AS bc
	INNER JOIN Roles AS R ON bc.RoleId = R.RoleId
	INNER JOIN OwnerGroups AS G ON R.OwnerGroupId = G.OwnerGroupId
	INNER JOIN Permissions AS Ug ON  G.OwnerGroupId = Ug.OwnerGroupId
	INNER JOIN Users ON Ug.Userid = Users.Userid 
WHERE Users.Username = CURRENT_USER AND PermissionArea = 4 AND (bc.IsSecret = 0 OR Ug.OptionsFlag&1 = 1 OR ug.HasWritePermission = 1)
GO
GRANT SELECT ON ABBasicCast TO [public]
GO
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.ABBasicCast_Update')) DROP VIEW dbo.ABBasicCast_Update
GO
CREATE VIEW [dbo].ABBasicCast_Update
AS
SELECT bc.*
FROM BasicCast AS Bc
	WHERE RoleId IN (SELECT r.Roleid FROM Roles AS R 
						INNER JOIN OwnerGroups AS G ON R.OwnerGroupId = G.OwnerGroupId
						INNER JOIN Permissions AS Ug ON  G.OwnerGroupId = Ug.OwnerGroupId
						INNER JOIN Users ON Ug.Userid = Users.Userid 
					WHERE Users.Username = CURRENT_USER AND PermissionArea = 4 AND ug.HasWritePermission = 1)
GO

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

--#endregion BasicCast Tabelle und Views

--#region AbXHDelBasicCast
ALTER VIEW dbo.AbXHDelBasicCast
	AS
	SELECT * FROM BasicCastHistory WHERE BasicCastId IN (SELECT BasicCastId FROM AbBasicCast)
GO
--#endregion AbXHDelBasicCast

--#region AbXHDelBasicCast_Update
ALTER VIEW dbo.AbXHDelBasicCast_Update
	AS
	SELECT * FROM BasicCastHistory WHERE BasicCastId IN (SELECT BasicCastId FROM AbBasicCast_Update)
WITH CHECK OPTION
GO
--#endregion AbXHDelBasicCast_Update

IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbBesetzungStdSoli'))  DROP VIEW dbo.AbBesetzungStdSoli
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.AbBesetzungStdSoli_Update'))  DROP VIEW dbo.AbBesetzungStdSoli_Update
GO

--#endregion TK 2019-09-04 BasicCast Umbau

--#region SH 2019-09-17 typ tsIntList entfernen

IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'tsIntList')
	DROP TYPE [dbo].[tsIntList]
GO

--#endregion SH 2019-09-17 typ tsIntList entfernen

--#region SH 2019-09-18 prozedur CalculateTimeAccountMonthValuesSums
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].CalculateTimeAccountMonthValuesSums'))
BEGIN
	DROP PROCEDURE dbo.CalculateTimeAccountMonthValuesSums
END
GO

CREATE PROCEDURE dbo.CalculateTimeAccountMonthValuesSums 
	@ContractIds IdFilterTable READONLY, --vertrags-ids
	@AccountIds IdFilterTable READONLY, --konten-ids
	@startMonth INT, --startmonat
	@endMonth INT, -- endemonat
	@monthValuesUntil INT, --monatswerte bis, null wenn keine monatswerte gewünscht sind
	@forwardsOnly BIT, --nur vorträge
	@addAnnualForwardsOfNextMonth BIT, --jahresvortrag folgeperiode hinzufügen
	@nextMonth INT --monat in dem folgeperiode anfängt, folgemonat von endMonth
AS
BEGIN
	DECLARE @permissions AS TABLE
	(OwnerGroupId INT, PermissionArea INT);

	INSERT INTO @permissions
	SELECT p.OwnerGroupId, p.PermissionArea
	FROM [permissions] p 
	INNER JOIN Users u ON u.UserID = p.UserID
	WHERE u.UserName = CURRENT_USER AND p.PermissionArea IN (1,5)


	SELECT
		zm.ContractId,
		zm.TimeAccountId, 
		SUM(CASE WHEN ZmType = 16 THEN zm.DataValue ELSE 0 END) AS Annual, 
		SUM(CASE WHEN ZmType = 32 THEN zm.DataValue ELSE 0 END) AS Forward, 
		CASE WHEN @forwardsOnly = 1 THEN CAST(0 AS FLOAT) ELSE SUM(CASE WHEN ZmType = 1 AND ((@monthValuesUntil IS NULL AND zm.YearMonth = -1) OR (@monthValuesUntil IS NOT NULL AND zm.YearMonth <= @monthValuesUntil)) AND FromDifferentTimeAccountId IS NULL THEN zm.DataValue ELSE 0 END) END AS MonthValue, 
		CASE WHEN @forwardsOnly = 1 THEN CAST(0 AS FLOAT) ELSE SUM(CASE WHEN ZmType = 1 AND NOT FromDifferentTimeAccountId IS NULL THEN zm.DataValue ELSE 0 END) END AS MonthValueFromOtherAccount,
		CASE WHEN @forwardsOnly = 1 THEN CAST(0 AS FLOAT) ELSE SUM(CASE WHEN ZmType <> 2 AND ZmType < 16 AND ZmType > 1 THEN zm.DataValue ELSE 0 END) END AS Correction,
		CASE WHEN @forwardsOnly = 1 THEN CAST(0 AS FLOAT) ELSE SUM(CASE WHEN ZmType = 64 THEN zm.DataValue ELSE 0 END) END AS TransferTo, 
		CASE WHEN @forwardsOnly = 1 THEN CAST(0 AS FLOAT) ELSE SUM(CASE WHEN ZmType = 128 THEN zm.DataValue ELSE 0 END) END AS TransferFrom 
	FROM [TimeAccountMonthValues] AS zm 
	WHERE 
		zm.ContractId IN (
			SELECT c.Id FROM @ContractIds c
			INNER JOIN Contracts cc ON c.Id = cc.ContractId
			INNER JOIN ContractDepartments cd ON cc.ContractId = cd.ContractId
			INNER JOIN WorkAreas wa ON wa.WorkAreaId = cd.WorkAreaId
			INNER JOIN Departments AS d ON d.DepartmentId = wa.DepartmentId
			INNER JOIN @permissions AS p ON 
				(p.OwnerGroupId = cc.OwnerGroupId AND p.PermissionArea = 1) 
				OR (p.OwnerGroupId = d.OwnerGroupId AND p.PermissionArea = 5)
		)
		AND zm.TimeAccountId IN (SELECT Id FROM @AccountIds)
		AND (
			(zm.YearMonth >= @startMonth AND zm.YearMonth <= @endMonth)
			OR (@addAnnualForwardsOfNextMonth = 1 AND zm.YearMonth = @nextMonth AND ZmType = 16)
		)
	GROUP BY zm.ContractId, zm.TimeAccountId
END
GO

GRANT EXECUTE ON dbo.CalculateTimeAccountMonthValuesSums TO PUBLIC
GO
--#endregion SH 2019-09-18 prozedur CalculateTimeAccountMonthValuesSums

--#region GetCastByPeriodInternal

ALTER 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.StartDate), @permissionPeriodEnd = MAX(s.EndDate)
	FROM Seasons AS s
		INNER JOIN SeasonPermissions AS us	ON s.SeasonId = us.SeasonId
	WHERE us.UserId = @userId 

	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 (PermissionId INT NOT NULL, PermissionArea INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #Permissions	SELECT Permissions.OwnerGroupId, Permissions.PermissionArea, OptionsFlag
								FROM Permissions
								WHERE UserId = @userId AND PermissionArea IN (1, 2, 4)

	DECLARE @fields VARCHAR(MAX)
	DECLARE @secretfields VARCHAR(MAX)
	SET @fields  = ', B.CastId, B.RoleId, B.ActivityId, B.StartOffset, B.EndOffset, B.Note, B.PrintMode, B.LM, B.UM, B.LC, B.UC, B.IsSecret, B.GroupPosition,
					  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.PersonId END AS PersonId,
									 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.CastId, CASE WHEN B.IsSecret = 1 AND ugC.OptionsFlag&1 <> 1 THEN 1 ELSE 0 END '
		END	
	ELSE
		BEGIN
			SET @secretfields =	'CASE WHEN B.IsSecret = 1 AND ugC.OptionsFlag&1 <> 1 THEN -1 ELSE B.PersonId END AS PersonId,
								 CASE WHEN B.IsSecret = 1 AND ugC.OptionsFlag&1 <> 1 THEN -1 ELSE B.ContractId END AS ContractId,
								 CASE WHEN B.IsSecret = 1 AND ugC.OptionsFlag&1 <> 1 THEN  0 ELSE B.CastStatusId END AS CastStatusId '
			SET @SQLQuery = 'SELECT ' + @secretfields + @fields
		END	

	SET @SQLQuery = @SQLQuery + 
	'FROM  Cast			AS B
		INNER JOIN Roles		AS ro	ON b.RoleId = ro.RoleId
		INNER JOIN Activities	AS A	ON B.ActivityId = A.ActivityId
		INNER JOIN Productions			AS p	ON A.ProductionId = p.ProductionId
		INNER JOIN #Permissions		AS ugA	ON ugA.PermissionId = P.OwnerGroupId AND ugA.PermissionArea = 2
		INNER JOIN #Permissions		AS ugC	ON ugC.PermissionId = ro.OwnerGroupId AND ugC.PermissionArea = 4'

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

		IF (@joins&4 = 4) 
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN ProductionDetails ON A.ProductionId = ProductionDetails.ProductionId '

		IF (@joins&8 = 8) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN ActivityTypes AS AT ON A.ActivityTypeId = AT.ActivityTypeId '
			
		SET @SQLQuery = @SQLQuery + ' WHERE A.Date 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 IsSecret erforderlich
		IF (EXISTS(SELECT * FROM #Permissions WHERE PermissionArea = 2 AND OptionsFlag&1 <> 1)) 
		BEGIN
			SET @SQLQuery = @SQLQuery  + ' AND (a.IsSecret = 0 OR uga.OptionsFlag&1 = 1)'
		END

		IF (@ShowCastWithoutRights = 0) 
		BEGIN
			SET @SQLQuery = @SQLQuery  + ' AND (b.IsSecret = 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 Cast AS b 
														INNER JOIN  #Cast ON b.CastId = #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 ContractEngagements vr ON cd.ContractEngagementId = vr.ContractEngagementId
		INNER JOIN Contracts v ON vr.ContractId = v.ContractId
		INNER JOIN #Permissions p ON p.PermissionArea = 1 AND p.PermissionId = v.OwnerGroupId

		--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
GO

--#endregion

--#region GetCastByCastIdInternal

ALTER PROCEDURE [dbo].[GetCastByCastIdInternal]
	@CastId VARCHAR(MAX),
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN

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

	if (@include <> 0)  CREATE TABLE #Cast (CastId INT NOT NULL)
	
	DECLARE @fields VARCHAR(MAX)
	SET @fields  = 'B.CastId, B.RoleId, B.PersonId, B.ActivityId, B.StartOffset, B.EndOffset, B.Note, B.PrintMode, B.LM, B.UM, B.LC, B.UC, B.IsSecret, B.GroupPosition, B.CastStatusId, 
					B.IsCover, B.IsCanceled, B.Creditable, B.BackColorArgb, B.IsReplacement, B.ContractId '

	--Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben
	if (@include <> 0) 
		SET @SQLQuery = 'INSERT INTO #Cast '
	ELSE
		SET @SQLQuery = 'SELECT ' + @fields
					
	 SET @SQLQuery =  @SQLQuery + '	 FROM  Cast AS B '
			
		IF (@joins&1 = 1) 
			SET @SQLQuery = @SQLQuery + 'INNER JOIN (SELECT * FROM ContractDates WHERE IsCanceled = 0) AS cd ON b.CastId = cd.CastID  '

		SET @SQLQuery = @SQLQuery + ' WHERE b.CastId IN (' + @CastId + ')'
			
				print @SQLQuery
		 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 ' + @fields +' FROM Cast AS b 
														INNER JOIN  #Cast ON b.CastId = #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 ContractEngagements vr ON cd.ContractEngagementId = vr.ContractEngagementId
			INNER JOIN Contracts v ON vr.ContractId = v.ContractId
			INNER JOIN Permissions ug ON ug.OwnerGroupId = v.OwnerGroupId AND ug.PermissionArea = 1 AND ug.UserID = @userId

		--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
	END
END
GO

--#rendregion

--#region GetCastByActivityIdInternal

ALTER 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 (PermissionId INT NOT NULL, PermissionArea INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #Permissions SELECT Permissions.OwnerGroupId, Permissions.PermissionArea, OptionsFlag  FROM Permissions WHERE UserId = @userId AND PermissionArea IN (1,4)


	DECLARE @fields VARCHAR(MAX) --<
	DECLARE @secretfields VARCHAR(MAX)
	SET @fields = ', B.CastId, B.RoleId, B.ActivityId, B.StartOffset, B.EndOffset, B.Note, B.PrintMode, B.LM, B.UM, B.LC, B.UC, B.IsSecret, B.GroupPosition, 
					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.PersonId END AS PersonId,
									 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.CastId, CASE WHEN B.IsSecret = 1 AND ugC.OptionsFlag&1 <> 1 THEN 1 ELSE 0 END '
		END	
	ELSE
		BEGIN
			SET @secretfields  =	'CASE WHEN B.IsSecret = 1 AND ugC.OptionsFlag&1 <> 1 THEN -1 ELSE B.PersonId END AS PersonId,
									 CASE WHEN B.IsSecret = 1 AND ugC.OptionsFlag&1 <> 1 THEN -1 ELSE B.ContractId END AS ContractId,
									 CASE WHEN B.IsSecret = 1 AND ugC.OptionsFlag&1 <> 1 THEN  0 ELSE B.CastStatusId END AS CastStatusId '
			
			SET @SQLQuery = 'SELECT ' + @secretfields + @fields
		END

		SET @SQLQuery =  @SQLQuery + '	FROM Cast AS B
										INNER JOIN Roles	AS ro ON b.RoleId = ro.roleId
										INNER JOIN #Permissions AS ugC ON ugC.PermissionId = ro.OwnerGroupId AND ugC.PermissionArea = 4'

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

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

		IF (@ShowCastWithoutRights = 0) 
		BEGIN
			SET @SQLQuery = @SQLQuery  + ' AND (b.IsSecret = 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 Cast AS b 
														INNER JOIN  #Cast ON b.CastId = #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 ContractEngagements vr ON cd.ContractEngagementId = vr.ContractEngagementId
				INNER JOIN Contracts v ON vr.ContractId = v.ContractId
				INNER JOIN #Permissions p ON p.PermissionArea = 1 AND p.PermissionId = v.OwnerGroupId

		--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
	UPDATE PlanColumnContent SET ContentSettings = Convert(XML, Replace(Convert(VARCHAR(max),  ContentSettings),'&lt;eStatusStatus&gt;approved&lt;/eStatusStatus&gt;',
		 '&lt;eStatusStatus&gt;approved&lt;/eStatusStatus&gt;
		  &lt;eStatusStatus&gt;WithCertificate&lt;/eStatusStatus&gt;
		  &lt;eStatusStatus&gt;WithoutCertificate&lt;/eStatusStatus&gt;')) 
	FROM PlanColumnContent ps
		INNER JOIN PlanColumns sp ON ps.PlanColumnId = sp.PlanColumnId
		INNER JOIN PlanLayouts p ON sp.PlanLayoutId = p.PlanLayoutId
	WHERE PlanLayoutType IN (30, 120, 130, 160)
	AND NOT ContentSettings IS NULL
	AND CONVERT(VARCHAR(max), ContentSettings) LIKE '%PersStatusListConverterFieldSettings%'
	AND CONVERT(VARCHAR(max), ContentSettings) LIKE '%&lt;eStatusStatus&gt;approved&lt;/eStatusStatus&gt;%'
	AND NOT CONVERT(VARCHAR(max), ContentSettings) LIKE '%&lt;eStatusStatus&gt;WithCertificate&lt;/eStatusStatus&gt;%'

GO
--#endregion

ALTER TABLE Activities ALTER COLUMN ArtisticNote NVARCHAR(256) NULL


--#region 20190906
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.SeasonPermissions') AND o.Name = 'IX_SeasonPermissions_UserId')
			CREATE INDEX IX_SeasonPermissions_UserId ON SeasonPermissions (UserId)
GO

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetPossibleCastByPeriodInternal'))	DROP PROCEDURE dbo.GetPossibleCastByPeriodInternal 
GO

CREATE PROCEDURE [dbo].[GetPossibleCastByPeriodInternal]
	@start DATE,
	@end DATE,
	@personIds IdFilterTable READONLY,
	@activityTypeIds IdFilterTable READONLY,
	@variantIds IdFilterTable READONLY,
	@understudyPosition TINYINT,
	@productionTeamInInvariantSeason BIT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN

SET NOCOUNT ON

DECLARE @seasonSetting TINYINT
SELECT @seasonSetting = DataValue FROM Settings WHERE Section = 'BasicCast' AND KeyName = 'Season'
IF @seasonSetting IS NULL SET @seasonSetting = 0

IF  EXISTS(SELECT * FROM @activityTypeIds)
BEGIN
--Mit Activitytype Filter
SELECT DISTINCT d.PersonId, d.ActivityId, c.CastId, d.RoleId, IsMandatory
	FROM (
			SELECT a.ActivityId, bs.RoleId, need.IsMandatory, bs.PersonId
			FROM Activities AS a 
				INNER JOIN Seasons AS s ON a.Date >= s.StartDate AND a.Date <= s.EndDate
				INNER JOIN ProductionChilds AS st ON a.ProductionId = st.ProductionId
				INNER JOIN Productions AS p ON st.ProductionId = p.ProductionId
				INNER JOIN Roles AS r ON st.ChildProductionId = r.ProductionId
				INNER JOIN BasicCast AS bs ON r.RoleId = bs.RoleId AND bs.UnderstudyPosition < @understudyPosition AND
						(((@seasonSetting = 0 OR (@seasonSetting = 2 AND r.IsProductionTeam = 1)) AND bs.SeasonId IS NULL) 
					OR   ((@seasonSetting = 1 OR (@seasonSetting = 2 AND r.IsProductionTeam = 0)) AND bs.SeasonId = s.SeasonId))
				INNER JOIN CastRules AS need ON r.RoleTypeId = need.RoleTypeId AND a.ActivityTypeId = need.ActivityTypeId
			WHERE Date BETWEEN @start AND @end AND VariantId IN (SELECT id FROM @variantIds) AND a.Status >= 0
				AND bs.PersonId IN (SELECT Id FROM @personIds)
				AND a.ActivityTypeId IN (SELECT Id FROM @activityTypeIds)
				AND s.SeasonId IN (SELECT SeasonId FROM SeasonPermissions WHERE UserID = @userId)
				AND p.OwnerGroupId IN (SELECT OwnerGroupId FROM Permissions WHERE UserId = @userId AND PermissionArea = 2)
				AND r.OwnerGroupId IN (SELECT OwnerGroupId FROM Permissions WHERE UserId = @userId AND PermissionArea = 4)
		) AS d
		LEFT JOIN ( SELECT * 
					FROM Cast
					WHERE IsCanceled = 0 AND IsCover = 0 ) AS c 
			ON d.ActivityId = c.ActivityId AND d.RoleId = c.RoleId
		WHERE c.CastId IS NULL OR c.PersonId <> d.PersonId
		ORDER BY 1,2
END 
ELSE
BEGIN
--Ohne Activitytype Filter
SELECT DISTINCT d.PersonId, d.ActivityId, c.CastId, d.RoleId, IsMandatory
	FROM (
			SELECT a.ActivityId, a.Date, StartTime, EndTime, bs.RoleId, need.IsMandatory, bs.PersonId
			FROM Activities AS a 
				INNER JOIN Seasons AS s ON a.Date >= s.StartDate AND a.Date <= s.EndDate
				INNER JOIN ProductionChilds AS st ON a.ProductionId = st.ProductionId
				INNER JOIN Productions AS p ON st.ProductionId = p.ProductionId
				INNER JOIN Roles AS r ON st.ChildProductionId = r.ProductionId
				INNER JOIN BasicCast AS bs ON r.RoleId = bs.RoleId AND bs.UnderstudyPosition < @understudyPosition AND
						(((@seasonSetting = 0 OR (@seasonSetting = 2 AND r.IsProductionTeam = 1)) AND bs.SeasonId IS NULL) 
					OR   ((@seasonSetting = 1 OR (@seasonSetting = 2 AND r.IsProductionTeam = 0)) AND bs.SeasonId = s.SeasonId))
				INNER JOIN CastRules AS need ON r.RoleTypeId = need.RoleTypeId AND a.ActivityTypeId = need.ActivityTypeId
			WHERE Date BETWEEN @start AND @end AND VariantId IN (SELECT id FROM @variantIds) AND a.Status >= 0
				AND bs.PersonId IN (SELECT Id FROM @personIds)
				AND s.SeasonId IN (SELECT SeasonId FROM SeasonPermissions WHERE UserID = @userId)
				AND p.OwnerGroupId IN (SELECT OwnerGroupId FROM Permissions WHERE UserId = @userId AND PermissionArea = 2)
				AND r.OwnerGroupId IN (SELECT OwnerGroupId FROM Permissions WHERE UserId = @userId AND PermissionArea = 4)
		) AS d
		LEFT JOIN ( SELECT * 
					FROM Cast 
					WHERE IsCanceled = 0 AND IsCover = 0 ) AS c 
			ON d.ActivityId = c.ActivityId AND d.RoleId = c.RoleId  
		WHERE c.CastId IS NULL OR c.PersonId <> d.PersonId
		ORDER BY 1,2
END
END
GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetPossibleCastByPeriod'))	DROP PROCEDURE dbo.GetPossibleCastByPeriod 
GO
CREATE PROCEDURE [dbo].[GetPossibleCastByPeriod]
	@start DATE,
	@end DATE,
	@personIds IdFilterTable READONLY,
	@activityTypeIds IdFilterTable READONLY,
	@variantIds IdFilterTable READONLY,
	@understudyPosition TINYINT,
	@productionTeamInInvariantSeason BIT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
	EXECUTE GetPossibleCastByPeriodInternal @start, @end, @personIds,@activityTypeIds,@variantIds,@understudyPosition,@productionTeamInInvariantSeason, @userId
END
GO
GRANT EXECUTE ON dbo.GetPossibleCastByPeriod TO PUBLIC
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('TravelSteps') AND [name] = 'DailyCosts')
BEGIN
	PRINT('Adding TravelSteps DailyCosts ...')
	ALTER TABLE dbo.TravelSteps ADD DailyCosts MONEY NOT NULL CONSTRAINT DF_TravelSteps_DailyCosts DEFAULT 0
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.LocationRates') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	Print 'Table Locations'
	CREATE TABLE dbo.LocationRates (
		LocationRateId INT IDENTITY(1,1) NOT NULL,
		LocationId INT NOT NULL,
		StartDate DATE NULL,
		EndDate DATE NULL,
		DefaultDailyCosts MONEY NOT NULL  CONSTRAINT DF_LocationRates_DefaultDailyCosts DEFAULT 0,
		DefaultFlatCosts MONEY NOT NULL  CONSTRAINT DF_LocationRates_DefaultFlatCosts DEFAULT 0,
		Note VARCHAR(256) SPARSE NULL,
		LM SMALLDATETIME NOT NULL,
		UM INT NULL,
		LC SMALLDATETIME NOT NULL,
		UC INT NULL,
		CONSTRAINT PK_LocationRates PRIMARY KEY NONCLUSTERED (LocationRateId),
		CONSTRAINT FK_LocationRates_Locations FOREIGN KEY(LocationId) REFERENCES Locations (LocationId) ON DELETE CASCADE
	) ON [PRIMARY]
	CREATE CLUSTERED INDEX IX_LocationRates_Locations ON LocationRates (LocationId)
END
GO
GRANT SELECT ON dbo.LocationRates to public
GRANT INSERT, UPDATE, DELETE ON dbo.LocationRates to DispoAdmin
--#endregion



--#endregion -------- (4.195.x) -------------------------------

--#endregion -------- (4.195.x) -------------------------------

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

--#region Bugfix-DH-20191010
GRANT UPDATE,INSERT,DELETE on dbo.FormulaConfigurations TO DispoAdmin
GO
GRANT UPDATE,INSERT,DELETE on dbo.FormulaConfigurations_Departments TO DispoAdmin
GO
--#endregion Bugfix-DH-20191010

--#region Bugfix FirstStudyCastRank
IF EXISTS (SELECT * FROM NVDATA WHERE ByModulScript = 1 AND (Major * 100000000) + (Minor * 1000) + Build  < 400196003) 
BEGIN
	Print 'DispoSettings'
	UPDATE settings SET DataValue = '4' WHERe Section = 'DispoSettings' AND KeyName = 'FirstStudyCastRank' AND DataValue = '3'
END
GO
--#endregion

--#region Berechtigung auf YearCloseTypes
GRANT INSERT, UPDATE, DELETE ON dbo.YearCloseTypes to MasterAdmin
GO
--#endregion Berechtigung auf YearCloseTypes

--#region SH 2019-10-23 Bugfix DeleteRole, Löschen von BasicCast hinzugefügt
--obsolete da in bereich db 2.0
--#endregion SH 2019-10-23

--#region CreateFreeDayPersonStatusTypes

IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'CreateFreeDayPersonStatusTypes'))	DROP PROCEDURE dbo.CreateFreeDayPersonStatusTypes
GO
CREATE PROCEDURE CreateFreeDayPersonStatusTypes
AS
BEGIN
	DECLARE @timeAccountId INT
	DECLARE @yearCloseTypeId INT
	SET NOCOUNT ON

	IF NOT EXISTS (SELECT * FROM PersonStatusTypes  AS st INNER JOIN TimeAccounts AS zk ON st.TimeAccountId = zk.TimeAccountId  WHERE zk.Formel = 3050 AND st.IsCollectiveStatus = 0)
	BEGIN
		IF NOT EXISTS (SELECT * FROM TimeAccounts AS zk WHERE zk.Formel = 3050)
			BEGIN
				PRINT 'Add TimeAccount: Frei'

				SELECT @yearCloseTypeId= YearCloseTypeId FROM  YearCloseTypes
	
				INSERT INTO TimeAccounts (Name, Formel, Module, YearCloseTypeId, LM, LC)
				VALUES ('Frei', 3050, 0, @yearCloseTypeId, GETDATE(), GETDATE())

				SELECT @timeAccountId = SCOPE_IDENTITY() 
			END
		ELSE 
			BEGIN
				UPDATE TimeAccounts SET Module= Module | 1 WHERE Formel = 3050 AND Module <> 0   
				SELECT @timeAccountId = TimeAccountId FROM TimeAccounts AS zk WHERE zk.Formel = 3050
			END
		PRINT 'Add Status: NV-Solo Frei'
		INSERT INTO PersonStatusTypes (Name, Code, TimeAccountId, DefaultApproveStatus, LM, LC)
		VALUES ('NV-Solo Frei', 'f', @timeAccountId, 10, GETDATE(), GETDATE())
	END

	IF NOT EXISTS (SELECT * FROM PersonStatusTypes AS st INNER JOIN TimeAccounts AS zk ON st.TimeAccountId = zk.TimeAccountId  WHERE zk.Formel = 3051 AND st.IsCollectiveStatus = 0)
	BEGIN

		IF NOT EXISTS (SELECT * FROM TimeAccounts AS zk WHERE zk.Formel = 3051)
			BEGIN
				PRINT 'Add TimeAccount: ½ Frei'
			
				SELECT @yearCloseTypeId= YearCloseTypeId FROM  YearCloseTypes
	
				INSERT INTO TimeAccounts (Name,Formel,Module,YearCloseTypeId,LM,LC)
				VALUES ('½ Frei', 3051, 0, @yearCloseTypeId, GETDATE(), GETDATE())

				SELECT @timeAccountId = SCOPE_IDENTITY() 
			END
		ELSE 
			BEGIN
			UPDATE TimeAccounts SET Module= Module | 1 WHERE Formel = 3051 AND Module <> 0   
				SELECT @timeAccountId = TimeAccountId FROM TimeAccounts AS zk WHERE zk.Formel = 3051
			END

		PRINT 'Add Status: Nachmittag Frei'
		INSERT INTO PersonStatusTypes (Name, Code, TimeAccountId, TemplateStartTime, DefaultApproveStatus, LM,LC)
		VALUES ('NV-Solo Nachm. Frei', 'nm', @timeAccountId,'14:00', 10, GETDATE(), GETDATE())

		PRINT 'Add Status: Vormittag Frei'
		INSERT INTO PersonStatusTypes (Name, Code, TimeAccountId, TemplateEndTime, DefaultApproveStatus, LM, LC)
		VALUES ('NV-Solo Vorm. Frei', 'vm', @timeAccountId, '14:00', 10, GETDATE() ,GETDATE())
	END
END
GO
GRANT EXECUTE ON dbo.CreateFreeDayPersonStatusTypes TO PUBLIC
GO
--#endregion CreateFreeDayPersonStatusTypes

--#region 20191105 BestMatchingContracts
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'GetCastAsDbo'))	DROP PROCEDURE dbo.GetCastAsDbo
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'GetActivitiesAsDBO'))	DROP PROCEDURE dbo.GetActivitiesAsDBO
GO
CREATE PROCEDURE [dbo].[GetActivitiesAsDBO]
	@start DATE,
	@end DATE
AS
BEGIN
	SET NOCOUNT ON	
	SELECT Activities.* FROM Activities WHERE Activities.Date BETWEEN @start AND @end 
	SELECT NULL AS [#8], Cast.* FROM Activities INNER JOIN Cast ON Activities.ActivityId = Cast.ActivityId  WHERE Activities.Date BETWEEN @start AND @end 
END
GO

IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'GetContractsASDBO'))	DROP PROCEDURE dbo.GetContractsASDBO
GO
CREATE PROCEDURE [dbo].[GetContractsASDBO]
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @SQLQuery AS NVARCHAR(MAX)
	CREATE TABLE #Contract (ContractId INT NOT NULL PRIMARY KEY)
	SET @SQLQuery = 'INSERT INTO #Contract SELECT v.ContractId FROM Contracts AS v '
	IF (@joins&1 = 1)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN Persons AS P ON v.PersonId = p.PersonId '

	IF (@joins&2 = 2)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN OwnerGroups AS g ON v.OwnerGroupId = g.OwnerGroupId '

	IF (@joins&4 = 4)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN ContractTypes AS vv ON vv.ContractTypeId = v.ContractTypeId '

	IF (@joins&8 = 8)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN ContractDetails vd ON vd.ContractId = v.ContractId '

	IF (@joins&16 = 16)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN PersonDetails pd ON v.PersonId = pd.PersonId '
	IF (@condition IS NOT NULL  AND @condition <> '')
	SET @SQLQuery = @SQLQuery + ' WHERE ' + @condition 

	EXECUTE sp_Executesql @SQLQuery
	
	SELECT * FROM Contracts AS V INNER JOIN #Contract ON v.ContractId = #Contract.ContractId 
	
	IF (@include&1 = 1) --Alle zugeordneten Perso Verträge
		SELECT NULL AS [#1], ContractDepartments.*
		FROM ContractDepartments
			INNER JOIN #Contract ON ContractDepartments.ContractId = #Contract.ContractId

	IF (@include&4 = 4)
	SELECT NULL AS [#4],
		vr.ContractId, vr.RoleId, vr.ContractEngagementId, vr.ProductionId, vr.StartDate, vr.EndDate, vr.RehearsalsCompensatedByPerformance, vr.CompensatedRehearselDays, vr.ProjectedPerformanceCount, vr.LM, vr.UM, vr.LC, vr.UC 
	FROM  
		ContractEngagements AS vr 
				INNER JOIN #Contract ON vr.ContractId = #Contract.ContractId
				
	IF (@include&8 = 8) 
		SELECT NULL AS [#8], ContractDetails.*
		FROM ContractDetails
			INNER JOIN #Contract ON ContractDetails.ContractId = #Contract.ContractId

	IF (@include&16 = 16)
		SELECT NULL AS [#16], ContractBonus.* 
		FROM ContractBonus 
			INNER JOIN #Contract ON ContractBonus.ContractId = #Contract.ContractId

	IF (@include&32 = 32)
		SELECT NULL AS [#32], Contract_Qualification_Person.*
		FROM Contract_Qualification_Person
			INNER JOIN #Contract ON Contract_Qualification_Person.ContractId = #Contract.ContractId

	IF (@include&64 = 64)
		SELECT NULL AS [#64], ContractFields.*
		FROM ContractFields
			INNER JOIN #Contract ON ContractFields.ContractId = #Contract.ContractId

	IF (@include&128 = 128)
		SELECT NULL AS [#128], TimeAccountUsage.*
		FROM TimeAccountUsage
			INNER JOIN #Contract ON TimeAccountUsage.ContractId = #Contract.ContractId

	IF (@include&256 = 256)
		SELECT NULL AS [#256], ContractPartTimePeriods.*
		FROM ContractPartTimePeriods
			INNER JOIN #Contract ON ContractPartTimePeriods.ContractId = #Contract.ContractId

	IF (@include&512 = 512)
		SELECT NULL AS [#512], ContractWorkingTimeModels.*
		FROM ContractWorkingTimeModels
			INNER JOIN #Contract ON ContractWorkingTimeModels.ContractId = #Contract.ContractId

	IF (@include&1024 = 1024)
		SELECT NULL AS [#1024], ContractSalaryRules.*
		FROM ContractSalaryRules
			INNER JOIN #Contract ON ContractSalaryRules.ContractId = #Contract.ContractId

	DROP TABLE #Contract
END
GO
--#endregion

--#region JourneyTimetables auf Minuten umstellen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'OffsetMinutes' AND o.id = OBJECT_ID(N'JourneyTimetables'))
BEGIN
	PRINT('Adding column JourneyTimetables.OffsetMinutes...')
	ALTER TABLE JourneyTimetables ADD OffsetMinutes SMALLINT NOT NULL CONSTRAINT DF_JourneyTimetables_OffsetMinutes DEFAULT 0
	Exec('UPDATE JourneyTimetables SET OffsetMinutes = OffsetHours * 60')
	Exec DropColumn 'JourneyTimetables', 'OffsetHours'
	ALTER TABLE JourneyTimetables ALTER COLUMN ExactJourneyTimeMinutes SMALLINT NULL
	EXEC sp_rename  'JourneyTimetables.ExactjourneyTimeMinutes', 'ExactJourneyTimeMinutes', 'COLUMN'
	
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'OffsetMinutes' AND o.id = OBJECT_ID(N'JourneyTimetableProductionDefaults'))
BEGIN
	PRINT('Adding column JourneyTimetableProductionDefaults.OffsetMinutes...')
	ALTER TABLE JourneyTimetableProductionDefaults ADD OffsetMinutes SMALLINT NOT NULL CONSTRAINT DF_JourneyTimetableProductionDefaults_OffsetMinutes DEFAULT 0
	Exec('UPDATE JourneyTimetableProductionDefaults SET OffsetMinutes = ISNULL(OffsetHours,0) * 60')
	Exec DropColumn 'JourneyTimetableProductionDefaults', 'OffsetHours'
END
GO

--#endregion JourneyTimetables auf Minuten umstellen

--#region DH 2019-11-06 / 2019-12-17 Bugfix [GetRelatedDataOfRole]

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(*), 'ContractEngagements'		 FROM ContractEngagements WHERE RoleId = @RoleId	
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'ContractDateConfirmations' FROM ContractDateConfirmations WHERE ContractDateId IN (SELECT ContractDateId FROM ContractDates WHERE CastId IN (SELECT CastId FROM Cast WHERE RoleId = @RoleId))
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'ContractDates'			 FROM ContractDates WHERE CastId IN (SELECT CastId FROM Cast WHERE RoleId = @RoleId)
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Cast'						 FROM Cast WHERE RoleId = @RoleId
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'TechnicalJobs'			 FROM TechnicalJobs WHERE RoleId = @RoleId
	
SELECT * FROM #Msg
END
GO
--#endregion DH 2019-11-06 Bugfix [GetRelatedDataOfRole]

--#region Nicht verwendete Soliprobenrollen und Rolle aus Produktion 0 entfernen
PRINT 'Deleting BesetzungStdSoli entries for soloist rehearsal roles...'
DELETE bsst FROM BesetzungStdSoliTabelle bsst
INNER JOIN Roles bs ON bsst.RoleId = bs.RoleId
WHERE bs.ProductionId <= 0
GO
PRINT 'Deleting BasicCast entries for soloist rehearsal roles...'
DELETE BasicCast FROM BasicCast
INNER JOIN Roles bs ON BasicCast.RoleId = bs.RoleId
WHERE bs.ProductionId <= 0
GO
PRINT 'Deleting Repertoire entries for soloist rehearsal roles...'
DELETE CastRepertoire FROM CastRepertoire 
INNER JOIN Roles bs ON CastRepertoire.RoleId = bs.RoleId
WHERE bs.ProductionId <= 0
GO
PRINT 'Deleting not used soloist rehearsal roles...'
DELETE FROM Roles WHERE ProductionId = -1 AND RoleId <> -1 AND NOT EXISTS (SELECT * FROM Cast WHERE RoleId = Roles.RoleId)
DELETE FROM Cast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = 0 AND RoleId NOT IN (-1,0) AND OwnerGroupId IN (SELECT OwnerGroupId FROM OwnerGroups WHERE Modul <> 4) )
DELETE FROM Roles WHERE ProductionId = 0 AND RoleId NOT IN (-1,0) AND OwnerGroupId IN (SELECT OwnerGroupId FROM OwnerGroups WHERE Modul <> 4) 
GO
--#endregion

--#region SH 2019-11-11 Berechtigung auf SeasonOwnerGroupSettings für Orchester und Chor

GRANT UPDATE, INSERT, DELETE ON SeasonOwnerGroupSettings TO OrchesterAdmin, ChorAdmin
GO
--#endregion SH 2019-11-11 Berechtigung auf SeasonOwnerGroupSettings für Orchester und Chor


--#region DeleteProduction

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

DECLARE @UserGroup int
SELECT @UserGroup = OwnerGroupId FROM Productions WHERE ProductionId = @ProductionId

--Berechtigungsprüfung
IF (dbo.GetCurrentPermission(@UserGroup, 3) < 2 ) 
	BEGIN
		SELECT 1 AS Attribut, 'No Permissions' 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 BasicCast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId)
				DELETE FROM ContractEngagements WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId)
				DELETE FROM CastRepertoire WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId)
				DELETE FROM ContractDateConfirmations WHERE ContractDateId IN (SELECT ContractDateId FROM ContractDates WHERE CastId IN (SELECT CastId FROM Cast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId)))
				DELETE FROM ContractDates WHERE CastId IN (SELECT CastId FROM Cast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId))
				DELETE FROM CastBonus WHERE CastId IN (SELECT CastId FROM Cast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId))
				DELETE FROM CashCommandPos_Cast WHERE CastId IN (SELECT CastId FROM Cast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId))
				DELETE FROM CastCredits WHERE ServiceCastId IN (SELECT CastId FROM Cast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId))
				DELETE FROM CastCredits WHERE ReplacementCastId IN (SELECT CastId FROM Cast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId))
				UPDATE ContractDates SET  CastId = NULL WHERE CastId IN (SELECT CastId FROM Cast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId))
				DELETE FROM Cast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId)
				DELETE FROM TechnicalJobs WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId)
				DELETE FROM RoleBonus WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId)
				DELETE FROM Role_Season WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId)
				DELETE FROM Roles_Scenes WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId)
				DELETE FROM Qualification_Role WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId)
				DELETE FROM Roles WHERE RoleId IN (SELECT RoleId FROM Roles WHERE ProductionId = @ProductionId)	
				DELETE FROM ProductionChilds WHERE ProductionId = @ProductionId
				DELETE FROM ProductionChilds WHERE ChildProductionId = @ProductionId
				DELETE FROM ActivityScenes WHERE ActivityId IN (SELECT ActivityId FROM Activities WHERE ProductionId = @ProductionId)
				DELETE FROM ActivityDepartmentData WHERE ActivityId IN (SELECT ActivityId FROM Activities WHERE ProductionId = @ProductionId)
				DELETE FROM TechnicalJobs WHERE ActivityId IN (SELECT ActivityId FROM Activities WHERE ProductionId = @ProductionId)
				DELETE FROM ActivityCosts WHERE ActivityId IN (SELECT ActivityId FROM Activities WHERE ProductionId = @ProductionId)
				DELETE FROM PresseText WHERE ActivityId IN (SELECT ActivityId FROM Activities WHERE ProductionId = @ProductionId)
				DELETE FROM ActivityDetails WHERE ActivityId IN (SELECT ActivityId FROM Activities WHERE ProductionId = @ProductionId)
				DELETE FROM JourneyTimetables WHERE ActivityId IN (SELECT ActivityId FROM Activities WHERE ProductionId = @ProductionId)
				DELETE FROM CostUnitWorkingTimes WHERE ActivityId IN (SELECT ActivityId FROM Activities WHERE ProductionId = @ProductionId)
				DELETE FROM ActivityDetails WHERE ActivityId IN (SELECT ActivityId FROM Activities WHERE ProductionId = @ProductionId)
				DELETE FROM ActivitySubscriptions WHERE ActivityId IN (SELECT ActivityId FROM Activities WHERE ProductionId = @ProductionId)
				DELETE FROM Activities WHERE ActivityId IN (SELECT ActivityId FROM Activities WHERE ProductionId = @ProductionId)
				UPDATE Activities SET LinkedActivityId = NULL WHERE LinkedActivityId IN (SELECT ActivityId FROM Activities WHERE ProductionId = @ProductionId)
			END
		END
END
GO

--#endregion DeleteProduction

--#region
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_BesetzungStdSoliTabelle_Roles') AND type = 'F') ALTER TABLE dbo.BesetzungStdSoliTabelle DROP CONSTRAINT FK_BesetzungStdSoliTabelle_Roles
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.BasicCastPublic')) DROP VIEW dbo.BasicCastPublic
GO
--#endregion

--#region DH 2019-12-09 Bugfix 15288 Berechtigung für DataCleaningAdmin
GRANT EXECUTE ON GetActivitiesAsDBO TO DataCleaningAdmin;
--#endregion

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

--#region ----------- 4.196.x ---------------------------------

--#region aufräumen
DELETE FROM Subscriptions WHERE SeasonId = 0
DELETE FROM Seasons WHERE SeasonId = 0
DELETE FROM NVData WHERE ByModulScript = 0
DELETE FROM Settings WHERE Section = 'TK' AND KeyName = 'FaxPrefix'
GO
--#endregion

--#region FK_JourneyGroups_JourneyGroupBranches
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_JourneyGroups_JourneyGroupBranches') AND type = 'F') 
BEGIN
	Print ('create FK_JourneyGroups_JourneyGroupBranches')
	SET IDENTITY_INSERT JourneyGroupBranches ON
	INSERT INTO JourneyGroupBranches (Sort,Name,JourneyGroupBranchID,lm,lc)

	SELECT 1,JourneyGroups.Name,JourneyGroups.JourneyGroupBranchId,GetDate(),GetDate() FROM JourneyGroups LEFT JOIN JourneyGroupBranches ON JourneyGroups.JourneyGroupBranchId=JourneyGroupBranches.JourneyGroupBranchId
		WHERE JourneyGroupBranches.JourneyGroupBranchId IS NULL 
	SET IDENTITY_INSERT JourneyGroupBranches OFF

	ALTER TABLE dbo.JourneyGroups  WITH CHECK ADD  CONSTRAINT FK_JourneyGroups_JourneyGroupBranches FOREIGN KEY(JourneyGroupBranchId)
		REFERENCES dbo.JourneyGroupBranches (JourneyGroupBranchId)
	ALTER TABLE dbo.JourneyGroups CHECK CONSTRAINT FK_JourneyGroups_JourneyGroupBranches
END
GO
--#endregion FK_JourneyGroups_JourneyGroupBranches

--#region Locations.TravelMinutes
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Locations') AND [name] = 'TravelMinutes')
BEGIN
	PRINT('Adding column Locations.TravelMinutes ...')
	UPDATE Locations SET NoOverlapCheck = 0 WHERE NoOverlapCheck IS NULL
	ALTER TABLE Locations ADD CONSTRAINT DF_Locations_NoOverlapCheck  DEFAULT 0 FOR NoOverlapCheck
	
	ALTER TABLE dbo.Locations ADD TravelMinutes SMALLINT NOT NULL CONSTRAINT DF_Locations_TravelMinutes DEFAULT 0
	EXEC ('UPDATE Locations SET TravelMinutes = TravelHours * 60 WHERE NOT TravelHours IS NULL')
	 ALTER TABLE Locations DROP COLUMN TravelHours
END
GO
--#endregion Locations.TravelMinutes

--#region IX_Permissions_UserId_OwnerGroupId_PermissionArea
IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.Permissions') AND o.Name = 'IX_Group_GroupIdUserIdPermissionArea') DROP INDEX Permissions.IX_Group_GroupIdUserIdPermissionArea
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.Permissions') AND o.Name = 'IX_Permissions_UserId_OwnerGroupId_PermissionArea') 
BEGIN
PRINT('Adding IX_Permissions_UserId_OwnerGroupId_PermissionArea ...')
	CREATE UNIQUE NONCLUSTERED INDEX IX_Permissions_UserId_OwnerGroupId_PermissionArea ON Permissions
		(UserID ,OwnerGroupId, PermissionArea) INCLUDE(HasWritePermission,OptionsFlag)
END
GO
--#endregion IX_Permissions_UserId_OwnerGroupId_PermissionArea

--#region 20191013 Unbezahlte Proben in NumberUnpaid
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ContractEngagements') AND [name] = 'ProbUnbez')
BEGIN
	Print 'ContractSalaryRules NumberUnpaid'
	EXEC('UPDATE ContractSalaryRules SET NumberUnpaid = ProbUnbez  
	FROM ContractSalaryRules csr 
		INNER JOIN TimeAccounts ON csr.AccountId = TimeAccounts.TimeAccountId
		INNER JOIN contractEngagements ON csr.contractEngagementid = contractEngagements.contractEngagementid
	WHERE TimeAccounts.Formel = 4020 AND CAST(TimeAccounts.settings AS varchar(MAX)) LIKE ''%RehearsalFee%'' AND 
		  contractEngagements.ProbUnbez > 0')
	EXEC DropColumn 'ContractEngagements', 'ProbUnbez'
END
GO
--#endregion 20191016

--#region 20191016 Feiertagsformel übertragen
UPDATE TimeAccounts SET Formel = 1278, Settings = 
'<HolidaySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <HolidayTimesettings>
    <HolidayTimeSetting>
      <HolidayType>Wochenfeiertag</HolidayType>
      <SundayExtra>false</SundayExtra>
    </HolidayTimeSetting>
    <HolidayTimeSetting>
      <HolidayType>Sonntagsfeiertag</HolidayType>
      <SundayExtra xsi:nil="true" />
    </HolidayTimeSetting>
  </HolidayTimesettings>
    <PaidOut>false</PaidOut>
</HolidaySettings>'
WHERE Formel = 1270

UPDATE TimeAccounts SET Formel = 1278, Settings = 
'<HolidaySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <HolidayTimesettings>
    <HolidayTimeSetting>
      <HolidayType>Wochenfeiertag</HolidayType>
      <SundayExtra>false</SundayExtra>
    </HolidayTimeSetting>
    <HolidayTimeSetting>
      <HolidayType>Sonntagsfeiertag</HolidayType>
      <SundayExtra xsi:nil="true" />
    </HolidayTimeSetting>
  </HolidayTimesettings>
  <PaidOut>true</PaidOut>
</HolidaySettings>'
WHERE Formel = 1271

UPDATE TimeAccounts SET Formel = 1278, Settings = 
'<HolidaySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <HolidayTimesettings>
    <HolidayTimeSetting>
      <HolidayType>Wochenfeiertag</HolidayType>
      <SundayExtra>true</SundayExtra>
    </HolidayTimeSetting>
  </HolidayTimesettings>
  <PaidOut>false</PaidOut>
  <HolidayEndsOnMidnight>false</HolidayEndsOnMidnight>
  <HolidayStartsOnMidnight>false</HolidayStartsOnMidnight>
</HolidaySettings>'
WHERE Formel = 1272


UPDATE TimeAccounts SET Formel = 1278, Settings = 
'<HolidaySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <HolidayTimesettings>
    <HolidayTimeSetting>
      <HolidayType>Wochenfeiertag</HolidayType>
      <SundayExtra>true</SundayExtra>
    </HolidayTimeSetting>
  </HolidayTimesettings>
  <PaidOut>true</PaidOut>
  <HolidayEndsOnMidnight>false</HolidayEndsOnMidnight>
  <HolidayStartsOnMidnight>false</HolidayStartsOnMidnight>
</HolidaySettings>'
WHERE Formel = 1273

--Im Replaceteile werden die Zeiten Übernommen
UPDATE TimeAccounts SET Formel = 1278, Settings = 
'<HolidaySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <HolidayTimesettings>
    <HolidayTimeSetting>
      <HolidayType>VorFeiertagSteuerfrei</HolidayType>'+
	REPLACE(REPLACE(CAST(ISNULL(settings,'') AS VARCHAR(MAX)),'TimeRangeSettings','TimeRange'),'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"','')
	+'<SundayExtra xsi:nil="true" />
    </HolidayTimeSetting>
  </HolidayTimesettings>
  <PaidOut>true</PaidOut>
</HolidaySettings>'
WHERE Formel = 1274

--Im Replaceteile werden die Zeiten Übernommen
UPDATE TimeAccounts SET Formel = 1278, Settings = 
'<HolidaySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <HolidayTimesettings>
    <HolidayTimeSetting>
      <HolidayType>VorFeiertagSteuerfrei</HolidayType>'+
	REPLACE(REPLACE(CAST(ISNULL(settings,'') AS VARCHAR(MAX)),'TimeRangeSettings','TimeRange'),'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"','')
	+'<SundayExtra xsi:nil="true" />
    </HolidayTimeSetting>
  </HolidayTimesettings>
  <PaidOut>false</PaidOut>
</HolidaySettings>'
WHERE Formel = 1275 

UPDATE TimeAccounts SET Formel = 1278, Settings = 
'<HolidaySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <HolidayTimesettings>
    <HolidayTimeSetting>
      <HolidayType>Wochenfeiertag</HolidayType>
      <SundayExtra xsi:nil="true" />
    </HolidayTimeSetting>
    <HolidayTimeSetting>
      <HolidayType>Sonntagsfeiertag</HolidayType>
      <SundayExtra xsi:nil="true" />
    </HolidayTimeSetting>
  </HolidayTimesettings>
  <PaidOut>false</PaidOut>
</HolidaySettings>'
WHERE Formel = 1276

UPDATE TimeAccounts SET Formel = 1278, Settings = 
'<HolidaySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <HolidayTimesettings>
    <HolidayTimeSetting>
      <HolidayType>Wochenfeiertag</HolidayType>
      <SundayExtra xsi:nil="true" />
    </HolidayTimeSetting>
  </HolidayTimesettings>
  <PaidOut>false</PaidOut>
</HolidaySettings>'
WHERE Formel = 1277


--ZulageA21 = 1301
UPDATE TimeAccounts SET Formel = 1210, Settings =
'<DailyOvertimeSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FromMinutesMode>Explicit</FromMinutesMode>
  <FromMinutes>0</FromMinutes>
  <UntilMinutes xsi:nil="true" />
  <Round>NoRound</Round>
  <HasPresentWorkingTime>true</HasPresentWorkingTime>
  <BonusList>
    <ValueBonus><Value>180</Value><Bonus>1</Bonus></ValueBonus>
    <ValueBonus><Value>240</Value><Bonus>2</Bonus></ValueBonus>
    <ValueBonus><Value>360</Value><Bonus>3</Bonus></ValueBonus>
    <ValueBonus><Value>600</Value><Bonus>4</Bonus></ValueBonus>
  </BonusList>
</DailyOvertimeSettings>'
WHERE Formel = 1303

--ZulageA26 = 1302
UPDATE TimeAccounts SET Formel = 1210, Settings =
'<DailyOvertimeSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FromMinutesMode>Explicit</FromMinutesMode>
  <FromMinutes>0</FromMinutes>
  <UntilMinutes xsi:nil="true" />
  <Round>NoRound</Round>
  <HasPresentWorkingTime>true</HasPresentWorkingTime>
  <BonusList>
    <ValueBonus><Value>180</Value><Bonus>1</Bonus></ValueBonus>
    <ValueBonus><Value>240</Value><Bonus>2</Bonus></ValueBonus>
    <ValueBonus><Value>480</Value><Bonus>3</Bonus></ValueBonus>
  </BonusList>
</DailyOvertimeSettings>'
WHERE Formel = 1302

--ZulageC3 = 1303
UPDATE TimeAccounts SET Formel = 1210, Settings =
'<DailyOvertimeSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FromMinutesMode>Explicit</FromMinutesMode>
  <FromMinutes>0</FromMinutes>
  <UntilMinutes xsi:nil="true" />
  <Round>NoRound</Round>
  <HasPresentWorkingTime>true</HasPresentWorkingTime>
  <BonusList>
    <ValueBonus><Value>180</Value><Bonus>2</Bonus></ValueBonus>
    <ValueBonus><Value>360</Value><Bonus>3</Bonus></ValueBonus>
    <ValueBonus><Value>480</Value><Bonus>4</Bonus></ValueBonus>
    <ValueBonus><Value>600</Value><Bonus>5</Bonus></ValueBonus>
  </BonusList>
</DailyOvertimeSettings>'
WHERE Formel = 1303

--ZulageC4 = 1304
UPDATE TimeAccounts SET Formel = 1210, Settings =
'<DailyOvertimeSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FromMinutesMode>Explicit</FromMinutesMode>
  <FromMinutes>0</FromMinutes>
  <UntilMinutes xsi:nil="true" />
  <Round>NoRound</Round>
  <HasPresentWorkingTime>true</HasPresentWorkingTime>
  <BonusList>
    <ValueBonus><Value>180</Value><Bonus>2</Bonus></ValueBonus>
    <ValueBonus><Value>300</Value><Bonus>3</Bonus></ValueBonus>
    <ValueBonus><Value>480</Value><Bonus>5</Bonus></ValueBonus>
    <ValueBonus><Value>600</Value><Bonus>6</Bonus></ValueBonus>
  </BonusList>
</DailyOvertimeSettings>'
WHERE Formel = 1304

--ZulageC5 = 1305
UPDATE TimeAccounts SET Formel = 1210, Settings =
'<DailyOvertimeSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FromMinutesMode>Explicit</FromMinutesMode>
  <FromMinutes>0</FromMinutes>
  <UntilMinutes xsi:nil="true" />
  <Round>NoRound</Round>
  <HasPresentWorkingTime>true</HasPresentWorkingTime>
  <BonusList>
    <ValueBonus><Value>180</Value><Bonus>2</Bonus></ValueBonus>
    <ValueBonus><Value>240</Value><Bonus>3</Bonus></ValueBonus>
    <ValueBonus><Value>360</Value><Bonus>4</Bonus></ValueBonus>
    <ValueBonus><Value>420</Value><Bonus>5</Bonus></ValueBonus>
	<ValueBonus><Value>480</Value><Bonus>6</Bonus></ValueBonus>
	<ValueBonus><Value>540</Value><Bonus>7</Bonus></ValueBonus>
	<ValueBonus><Value>600</Value><Bonus>8</Bonus></ValueBonus>
  </BonusList>
</DailyOvertimeSettings>'
WHERE Formel = 1305

--ZulageC6 = 1306
UPDATE TimeAccounts SET Formel = 1210, Settings =
'<DailyOvertimeSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FromMinutesMode>Explicit</FromMinutesMode>
  <FromMinutes>0</FromMinutes>
  <UntilMinutes xsi:nil="true" />
  <Round>NoRound</Round>
  <HasPresentWorkingTime>true</HasPresentWorkingTime>
  <BonusList>
    <ValueBonus><Value>180</Value><Bonus>1</Bonus></ValueBonus>
    <ValueBonus><Value>240</Value><Bonus>2</Bonus></ValueBonus>
    <ValueBonus><Value>360</Value><Bonus>3</Bonus></ValueBonus>
    <ValueBonus><Value>600</Value><Bonus>4</Bonus></ValueBonus>
  </BonusList>
</DailyOvertimeSettings>'
WHERE Formel = 1306

--ZulageC7 = 1307
UPDATE TimeAccounts SET Formel = 1210, Settings =
'<DailyOvertimeSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FromMinutesMode>Explicit</FromMinutesMode>
  <FromMinutes>60</FromMinutes>
  <UntilMinutes>540</UntilMinutes>
  <Round>NoRound</Round>
  <HasPresentWorkingTime>true</HasPresentWorkingTime>
  <ConsiderTimeAccountFilterWhenCalculating>false</ConsiderTimeAccountFilterWhenCalculating>
  <MinBonusIfRegularWorkingtimeIsReached>0</MinBonusIfRegularWorkingtimeIsReached>
  <WeeklyOvertimeBonusFromMinutes>0</WeeklyOvertimeBonusFromMinutes>
  <IsWeeklyOvertimeBonusFixValue>false</IsWeeklyOvertimeBonusFixValue>
  <OnlyIfNoWeeklyOvertime>false</OnlyIfNoWeeklyOvertime>
  <SubtractPaidBreaks>false</SubtractPaidBreaks>
</DailyOvertimeSettings>'
WHERE Formel = 1307
--#endregion 20191016 Feiertagsformel übertragen

--#region DeleteTimeAccount
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.DeleteTimeAccount'))
	DROP PROCEDURE dbo.DeleteTimeAccount
GO
CREATE PROCEDURE dbo.DeleteTimeAccount
	@timeAccountId INT,
	@checkOnly BIT,
	@message VARCHAR(1024) OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @CRLF char(2)
	SET @CRLF =  '|'

	SET @message = ''
	DECLARE @count INT
	SELECT @count = COUNT(*) FROM RapportColumns WHERE TimeAccountId = @timeAccountId OR InOtherTimeAccountId = @timeAccountId 
	IF (@count > 0)  SET @message = @message +  '[RapportColumns]: ' + CAST(@count AS VARCHAR(10)) + @CRLF

	SELECT @count = COUNT(*) FROM ShiftTypes WHERE TimeAccountId = @timeAccountId
	IF (@count > 0)  SET @message = @message +  '[ShiftTypes]: ' + CAST(@count AS VARCHAR(10)) + @CRLF

	SELECT @count = COUNT(*) FROM PersonStatusTypes WHERE TimeAccountId = @timeAccountId
	IF (@count > 0)  SET @message = @message + '[PersonStatusTypes]: '+ CAST(@count AS VARCHAR(10)) + @CRLF

	SELECT @count = COUNT(*) FROM Bonus WHERE TimeAccountId = @timeAccountId
	IF (@count > 0)  SET @message = @message  + '[Bonus]: ' + CAST(@count AS VARCHAR(10)) + @CRLF

	SELECT @count = COUNT(*) FROM ContractSalaryRules WHERE AccountId = @timeAccountId
	IF (@count > 0)  SET @message = @message  + '[ContractSalaryRules]: ' + CAST(@count AS VARCHAR(10)) + @CRLF

	
	IF (@message <> '')
	BEGIN
		RETURN
	END
	SELECT @count = COUNT(*) FROM  TimeAccountMonthValues WHERE TimeAccountId = @timeAccountId OR FromDifferentTimeAccountId =@timeAccountId
	IF (IS_MEMBER('DataCleaningAdmin') = 0 AND IS_MEMBER('db_owner') = 0 AND  @count > 0)
	BEGIN
		SET @message = '[TimeAccountMonthValues]: '+ CAST(@count AS VARCHAR(10))
		RETURN
	END
	
	IF @checkOnly = 1
	BEGIN
    	RETURN
    END

	DELETE FROM TimeAccountMonthValues WHERE TimeAccountId = @timeAccountId
	--zmSort setzen um eindeutigen Index zu erlangen
	UPDATE TimeAccountMonthValues SET FromDifferentTimeAccountId = NULL, zmSort  = @timeAccountId  WHERE FromDifferentTimeAccountId = @timeAccountId
	DELETE FROM TimeAccountUsage WHERE TimeAccountId = @timeAccountId
	RETURN 1
END
GO
GRANT EXECUTE on dbo.DeleteTimeAccount TO PersoAdmin
GRANT EXECUTE on dbo.DeleteTimeAccount TO OrchesterAdmin
GRANT EXECUTE on dbo.DeleteTimeAccount TO ChorAdmin
GRANT EXECUTE on dbo.DeleteTimeAccount TO BallettAdmin
GRANT EXECUTE on dbo.DeleteTimeAccount TO DispoAdmin
GO
--#endregion DeleteTimeAccount

--#region DH20191014 WebPublishCastSoli/Team
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ProductionDetails') AND [name] = 'WebPublishSoli')
BEGIN
	
	ALTER TABLE productiondetails ADD WebPublishTeam BIT NOT NULL CONSTRAINT DF_ProductionDetails_WebPublishTeam DEFAULT 0;	
	EXEC sp_rename N'dbo.DF_ProductionDetails_PublicCast', N'DF_ProductionDetails_WebPublishSoli', N'OBJECT'
	EXEC sp_rename 'ProductionDetails.PublicCast', 'WebPublishSoli';		
END
GO
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 196 OR (Minor = 196 AND Build <=2)))))
BEGIN
	UPDATE ProductionDetails Set WebPublishTeam=WebPublishSoli;
END
--#endregion DH20191014 WebPublishCastSoli/Team

--#region DH20191023 Bonus Timeaccount not null
IF EXISTS (SELECT * FROM bonus WHERE TimeAccountId IS NULL)
BEGIN
	print 'Set TimeAccount for Bonus'
	DECLARE @YEAR INT;
	SELECT @YEAR= YearCloseTypeId FROM  TimeAccounts WHERE Formel=2000;
	IF ( @YEAR IS NULL) 
	BEGIN
		SELECT @YEAR= YearCloseTypeId FROM  TimeAccounts GROUP BY YearCloseTypeId ORDER BY COUNT(YEARCLOSETYPEID);
	END
	INSERT INTO TimeAccounts([Name],[Formel],[Module],[YearCloseTypeId],LM,LC,UM,UC	)
	SELECT [Name],2000,Module,@YEAR,LM,LC,UM,UC
	FROM Bonus 
	WHERE TimeAccountId IS NULL;

	UPDATE B
	SET TimeAccountId=T.TimeAccountId
	FROM TimeAccounts T INNER JOIN  Bonus B ON T.NAME=B.NAME WHERE B.TimeAccountId IS NULL;
	
	print 'Finished Set TimeAccount for Bonus'	
END
GO
IF EXISTS (SELECT * FROM NVDATA WHERE ByModulScript = 1 AND (Major * 100000000) + (Minor * 1000) + Build  < 400196102) 
BEGIN
ALTER TABLE Bonus ALTER COLUMN TimeAccountId INT NOT NULL;
END
GO
IF EXISTS (SELECT * FROM NVDATA WHERE ByModulScript = 1 AND (Major * 100000000) + (Minor * 1000) + Build  < 400196105) 
BEGIN
	EXEC DropIndexByTable  'ContractEngagements'
	ALTER TABLE ContractEngagements ALTER COLUMN ContractId INT NOT NULL
	CREATE CLUSTERED INDEX IX_ContractEngagements_ContractId ON ContractEngagements (ContractId)
END
GO
--#endregion DH20191023 Bonus Timeaccount not null

--#region SH 2019-11-13 OptionsFlag in PersonPermissions

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PersonPermissions') AND [name] = 'OptionsFlag')
BEGIN
	PRINT('Adding PersonPermissions.OptionsFlag ...')
	ALTER TABLE dbo.PersonPermissions ADD OptionsFlag INT NOT NULL CONSTRAINT DF_PersonPermissions_OptionsFlag DEFAULT 0
		EXEC ('UPDATE PersonPermissions SET OptionsFlag = 1 WHERE HasAccessToSecretContactData = 1')
		EXEC ('UPDATE pp SET pp.OptionsFlag = 1023 FROM PersonPermissions pp INNER JOIN Persons p ON pp.PersonId = p.PersonId WHERE pp.OwnerGroupId = p.OwnerGroupId')
		EXEC DropColumn 'PersonPermissions', 'PermissionType'
END
GO
--views/prozeduren aktualisieren

--#region ABPersKom_Update
ALTER VIEW [dbo].[ABPersKom_Update]
AS
	SELECT 
	pk.PersonContactDataId, pk.CommunicationTypeId, pk.PersonId, pk.Sort, pk.DataValue, pk.Note, pk.LM, pk.UM, pk.LC, pk.UC,pk.IsSecret,pk.ContactPersonConnectionID

	FROM PersonContactData  as pk

	WHERE pk.PersonId IN (
		SELECT  pp.PersonId
		FROM PersonPermissions AS PP
			INNER JOIN Permissions AS UG ON pp.OwnerGroupId =  UG.OwnerGroupId 
			INNER JOIN Users ON Ug.Userid = Users.Userid 
		WHERE ug.HasWritePermission=1
			AND (IsSecret = 0 OR ug.OptionsFlag&pp.OptionsFlag&1 = 1)
			AND PermissionArea = 0
			AND pp.HasWritePermission = 1
			AND Username = CURRENT_USER 
	)
WITH CHECK OPTION
GO
--#endregion ABPersKom_Update

--#region ABPersAdresse
ALTER VIEW [dbo].[ABPersAdresse]
	AS 
		SELECT 
			pa.AddressId, pa.PersonId, 
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission=0 THEN '**********' ELSE pa.[Street] END AS [Street],
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission=0 THEN '*****' ELSE pa.PostCode END AS PostCode,
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission=0 THEN '**********' ELSE pa.City END AS City,
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission=0 THEN '***' ELSE pa.CountryCode END AS CountryCode,
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission=0 THEN '**********' ELSE pa.co END AS Co,
			  pa.Sort, pa.Name, pa.IsSecret, pa.LM, pa.UM, pa.LC, pa.UC
		FROM PersonAddress  AS pa
			INNER  JOIN  (	SELECT  pp.PersonId, MAX(CASE WHEN ug.OptionsFlag&pp.OptionsFlag&1 <> 1 THEN 0 ELSE 1 END) AS SecretPermission 
							FROM PersonPermissions AS PP
								INNER JOIN Permissions AS UG ON pp.OwnerGroupId =  UG.OwnerGroupId 
								INNER JOIN Users ON Ug.Userid = Users.Userid 
							WHERE PermissionArea = 0 AND Username = CURRENT_USER GROUP BY pp.PersonId) AS sub ON pa.PersonId = sub.PersonId
GO
--#endregion ABPersAdresse

--#region ABPersAdresse_Update
ALTER VIEW [dbo].[ABPersAdresse_Update]
AS
	SELECT 
		Pa.*
	FROM PersonAddress as Pa
	WHERE PersonId IN (SELECT  pp.PersonId
		FROM PersonPermissions AS PP
			INNER JOIN Permissions AS UG ON pp.OwnerGroupId =  UG.OwnerGroupId 
			INNER JOIN Users ON Ug.Userid = Users.Userid 
		WHERE ug.HasWritePermission = 1
		      AND (IsSecret=0 OR ug.OptionsFlag&pp.OptionsFlag&1 = 1)
			  AND PermissionArea = 0
			  AND pp.HasWritePermission = 1
			  AND Username = CURRENT_USER )
WITH CHECK OPTION
GO
--#endregion ABPersAdresse_Update

--#region ABPersKom
ALTER VIEW [dbo].[ABPersKom]
AS
SELECT  
	pk.PersonContactDataId, 
	pk.CommunicationTypeId, 
	pk.PersonId, 
	pk.Sort, 
	pk.IsSecret,
	CASE WHEN IsSecret = 1 AND SecretPermission=0 THEN '**********' ELSE  pk.DataValue	   END AS DataValue,
	CASE WHEN IsSecret = 1 AND SecretPermission=0 THEN '**********' ELSE  pk.Note END AS Note,
	pk.ContactPersonConnectionID,
	pk.LM, pk.UM, pk.LC, pk.UC
FROM PersonContactData AS pk INNER JOIN (
	SELECT  pp.PersonId, MAX(CASE WHEN ug.OptionsFlag&pp.OptionsFlag&1 <> 1 THEN 0 ELSE 1 END) AS SecretPermission 
	FROM PersonPermissions AS PP
		INNER JOIN Permissions AS UG ON pp.OwnerGroupId =  UG.OwnerGroupId 
		INNER JOIN Users ON Ug.Userid = Users.Userid 
		WHERE PermissionArea = 0 AND Username = CURRENT_USER 
		GROUP BY pp.PersonId) AS sub ON pk.PersonId = sub.PersonId
GO
--#endregion ABPersKom

--#region AbPersonal_Update
ALTER VIEW dbo.AbPersonal_Update
AS 
	WITH WriteableOwnerGroupIds AS (
		SELECT
			p.OwnerGroupId
		FROM
			Permissions p
			INNER JOIN Users u ON p.UserID = u.UserID
		WHERE
			p.HasWritePermission = 1
			AND p.PermissionArea = 0
			AND u.UserName = CURRENT_USER 
	)
	SELECT
		p.*
	FROM
		Persons p
	WHERE
		p.PersonId IN (
			SELECT
				pp.PersonId
			FROM
				PersonPermissions AS pp
				INNER JOIN WriteableOwnerGroupIds wogi on wogi.OwnerGroupId = pp.OwnerGroupId
			WHERE
				pp.HasWritePermission=1
			GROUP BY pp.PersonId
		)
		OR EXISTS (SELECT * FROM WriteableOwnerGroupIds wogi WHERE wogi.OwnerGroupId = p.OwnerGroupId)
WITH CHECK OPTION
GO
--#endregion AbPersonal_Update

--#region AbPersonalChild
ALTER VIEW [dbo].[AbPersonalChild]
AS
	WITH LinkablePersonIds AS (
		SELECT pp.PersonId 
		FROM PersonPermissions AS PP
			INNER JOIN Permissions AS UG ON pp.OwnerGroupId =  UG.OwnerGroupId 
			INNER JOIN Users ON Ug.Userid = Users.Userid 
		WHERE ug.PermissionArea = 0
		      AND ug.OptionsFlag&pp.OptionsFlag&512 = 512
			  AND Username = CURRENT_USER
		GROUP BY pp.PersonId
	)
	SELECT PersonRelations.* FROM PersonRelations
	WHERE PersonId IN (SELECT * FROM LinkablePersonIds) OR ChildPersonId IN (SELECT * FROM LinkablePersonIds)
GO
--#endregion AbPersonalChild

--#region AbPersonalChild_Update
ALTER VIEW [dbo].[AbPersonalChild_Update]
AS
	WITH WriteableLinkablePersonIds AS (
		SELECT pp.PersonId 
		FROM PersonPermissions AS PP
			INNER JOIN Permissions AS UG ON pp.OwnerGroupId =  UG.OwnerGroupId 
			INNER JOIN Users ON Ug.Userid = Users.Userid 
		WHERE pp.HasWritePermission=1
		      AND UG.HasWritePermission=1
		      AND ug.PermissionArea = 0
		      AND ug.OptionsFlag&pp.OptionsFlag&512 = 512 
		      AND Username = CURRENT_USER
		GROUP BY pp.PersonId
	)
	SELECT PersonRelations.* FROM PersonRelations
	WHERE (PersonId IN (SELECT * FROM WriteableLinkablePersonIds) OR ChildPersonId IN (SELECT * FROM WriteableLinkablePersonIds))
WITH CHECK OPTION
GO
--#endregion AbPersonalChild_Update

--#region AbQualification_Person_Update
ALTER VIEW [dbo].[AbQualification_Person_Update]
AS 
SELECT
	qp.*
FROM
	Qualification_Person qp
WHERE 
	qp.PersonId IN (
		SELECT  pp.PersonId
		FROM PersonPermissions AS pp
			INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
			INNER JOIN Users u ON p.Userid = u.Userid 
		WHERE 
			p.OptionsFlag&pp.OptionsFlag&2 = 2
			AND PermissionArea = 0
			AND Username = CURRENT_USER
		GROUP BY pp.PersonId
	)
WITH CHECK OPTION
GO
--#endregion AbQualification_Person_Update

--#region AbPersEmployee_Update
ALTER VIEW dbo.AbPersEmployee_Update
AS
	SELECT  *  
	FROM  PersonEmployee 
	WHERE PersonEmployee.PersonId IN (
		SELECT
			pp.PersonId 
		FROM
			PersonPermissions AS pp
			INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
			INNER JOIN Users AS u ON p.Userid = u.Userid 
		WHERE
			p.PermissionArea = 0
			AND p.OptionsFlag&pp.OptionsFlag& 256 = 256
			AND Username = CURRENT_USER
		GROUP BY pp.PersonId
	)
WITH CHECK OPTION
GO
--#endregion AbPersEmployee_Update

--#region AbPersonalHonorar
ALTER VIEW dbo.AbPersonalHonorar
AS 
	SELECT
		ph.* 
	FROM
		dbo.PersonFeeNotes ph 
	WHERE
		ph.PersonId IN (
			SELECT
				pp.PersonId 
			FROM
				PersonPermissions AS pp
				INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
				INNER JOIN Users AS u ON p.Userid = u.Userid 
			WHERE
				p.PermissionArea = 0
				AND (p.OptionsFlag&pp.OptionsFlag&64 = 64 OR p.OptionsFlag&pp.OptionsFlag&128 = 128)
				AND Username = CURRENT_USER
			GROUP BY pp.PersonId
		)
GO
--#endregion

--#region AbPersonalHonorar_Update
ALTER VIEW [dbo].[AbPersonalHonorar_Update]
AS 
	SELECT
		ph.* 
	FROM
		dbo.PersonFeeNotes ph 
	WHERE
		ph.PersonId IN (
			SELECT
				pp.PersonId 
			FROM
				PersonPermissions AS pp
				INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
				INNER JOIN Users AS u ON p.Userid = u.Userid 
			WHERE
				p.PermissionArea = 0
				AND p.OptionsFlag&pp.OptionsFlag&128 = 128
				AND Username = CURRENT_USER
			GROUP BY pp.PersonId
		)
WITH CHECK OPTION
GO
--#endregion AbPersonalHonorar_Update

--#region AbPersonalDetails
ALTER VIEW dbo.AbPersonalDetails
AS
	SELECT
		pd.*
	FROM
		PersonDetails pd
	WHERE
		pd.PersonId IN (
			SELECT
				pp.PersonId 
			FROM
				PersonPermissions AS pp
				INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
				INNER JOIN Users AS u ON p.Userid = u.Userid 
			WHERE
				p.PermissionArea = 0
				AND (p.OptionsFlag&pp.OptionsFlag&4 = 4 OR p.OptionsFlag&pp.OptionsFlag&8 = 8)
				AND Username = CURRENT_USER
			GROUP BY pp.PersonId
		)
GO
--#endregion

--#region AbPersonalDetails_Update
ALTER VIEW dbo.AbPersonalDetails_Update
AS
	SELECT
		pd.*
	FROM
		PersonDetails pd
	WHERE
		pd.PersonId IN (
			SELECT
				pp.PersonId 
			FROM
				PersonPermissions AS pp
				INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
				INNER JOIN Users AS u ON p.Userid = u.Userid 
			WHERE
				p.PermissionArea = 0
				AND p.OptionsFlag&pp.OptionsFlag&8 = 8
				AND Username = CURRENT_USER
			GROUP BY pp.PersonId
		)
WITH CHECK OPTION
GO
--#endregion

--#region AbBankAccount
ALTER VIEW dbo.AbBankAccount
AS
	SELECT
		ba.*
	FROM
		BankAccounts ba
	WHERE
		ba.PersonId IN (
			SELECT
				pp.PersonId 
			FROM
				PersonPermissions AS pp
				INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
				INNER JOIN Users AS u ON p.Userid = u.Userid 
			WHERE
				p.PermissionArea = 0
				AND (p.OptionsFlag&pp.OptionsFlag&16 = 16 OR p.OptionsFlag&pp.OptionsFlag&32 = 32)
				AND Username = CURRENT_USER
			GROUP BY pp.PersonId
		)
GO
--#endregion AbBankAccount

--#region AbBankAccount_Update
ALTER VIEW [dbo].[AbBankAccount_Update]
AS
	SELECT
		ba.*
	FROM
		BankAccounts ba
	WHERE
		ba.PersonId IN (
			SELECT
				pp.PersonId 
			FROM
				PersonPermissions AS pp
				INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
				INNER JOIN Users AS u ON p.Userid = u.Userid 
			WHERE
				p.PermissionArea = 0
				AND p.OptionsFlag&pp.OptionsFlag&32 = 32
				AND Username = CURRENT_USER
			GROUP BY pp.PersonId
		)
WITH CHECK OPTION
GO
--#endregion AbBankAccount_Update

--#region AbPersDataCategoryData
ALTER VIEW dbo.AbPersDataCategoryData
AS
	SELECT
		pfd.*
	FROM
		PersonFieldData pfd
	WHERE
		pfd.PersonId IN (
			SELECT
				pp.PersonId 
			FROM
				PersonPermissions AS pp
				INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
				INNER JOIN Users AS u ON p.Userid = u.Userid 
			WHERE
				p.PermissionArea = 0
				AND (p.OptionsFlag&pp.OptionsFlag&4 = 4 OR p.OptionsFlag&pp.OptionsFlag&8 = 8)
				AND Username = CURRENT_USER
			GROUP BY pp.PersonId
		)
GO
--#endregion AbPersDataCategoryData

--#region AbPersDataCategoryData_Update
ALTER VIEW dbo.AbPersDataCategoryData_Update
AS
	SELECT
		pfd.*
	FROM
		PersonFieldData pfd
	WHERE
		pfd.PersonId IN (
			SELECT
				pp.PersonId 
			FROM
				PersonPermissions AS pp
				INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
				INNER JOIN Users AS u ON p.Userid = u.Userid 
			WHERE
				p.PermissionArea = 0
				AND p.OptionsFlag&pp.OptionsFlag&8 = 8
				AND Username = CURRENT_USER
			GROUP BY pp.PersonId
		)
WITH CHECK OPTION
GO
--#endregion AbPersDataCategoryData_Update

--#region AbPersonalNotizen
ALTER VIEW dbo.AbPersonalNotizen
AS
	SELECT
		pm.*
	FROM
		PersonMemo pm
		LEFT JOIN  (
			SELECT
				OwnerGroupId
			FROM
				Permissions P
				INNER JOIN Users u ON p.Userid = u.Userid
			WHERE
				p.PermissionArea = 0
				AND u.Username = CURRENT_USER
		) UG ON pm.OwnerGroupId = UG.OwnerGroupId
	WHERE
		NOT UG.OwnerGroupId IS NULL
GO
--#endregion AbPersonalNotizen

--#region AbPersonalNotizen_Update
ALTER VIEW [dbo].[AbPersonalNotizen_Update]
AS
	SELECT *
	FROM PersonMemo 
	WHERE OwnerGroupId IN (  
			SELECT
				OwnerGroupId
			FROM Permissions P
				INNER JOIN Users u ON p.Userid = u.Userid
			WHERE
				p.PermissionArea = 0
				AND u.Username = CURRENT_USER
				AND p.HasWritePermission = 1)
WITH CHECK OPTION
GO
--#endregion [AbPersonalNotizen_Update]

--#region DeletePersonReference

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 PersonId
	@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 = OwnerGroupId FROM Persons WHERE PersonId = @personId

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

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

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

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

	/*  Tabelle Contracts  */
	IF (SELECT COUNT(*) FROM Contracts WHERE PersonId = @personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Contract' + @CRLF
	END
	/*  Tabelle Contracts  */
	IF (SELECT COUNT(*) FROM ContractDetails WHERE ContractDetails.AgencyPersonId = @personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Contract (Agency)' + @CRLF
	END

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

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

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

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

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

	/*  Tabelle PersonRelations  */
	IF (@del > 0) 
		BEGIN
			DELETE FROM PersonRelations WHERE ChildPersonId = @personId
			DELETE FROM PersonRelations WHERE PersonId = @personId
		END


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

	/*  Tabelle BasicCastHistory */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM BasicCastHistory 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 BasicCastHistory WHERE PersonOldId = @personId OR PersonNewId = @personId
			END
		END

	/*  Tabelle PersonFeeNotes  */
	IF (@del > 0) DELETE FROM PersonFeeNotes WHERE PersonId=@personId

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


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

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

	/*  Tabelle AbPersZusatzDaten_Update  */
		SELECT  @Temp = 0
		SELECT @Temp = COUNT(*) FROM PersonAdditionalData WHERE PersonId = @personId
		IF (SELECT COUNT(*) FROM AbPersZusatzDaten_Update WHERE PersonId = @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 PersonAdditionalData WHERE PersonId = @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 CashCommands WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'CashCommand' + @CRLF
		END


	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM CashCommands 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 Departments 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

--#endregion SH 2019-11-13 OptionsFlag in PersonPermissions

--#region FK_Roles_OwnerGroups und FK_Roles_RoleCategories
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Roles_OwnerGroups') AND type = 'F') 
BEGIN
	Print 'Add FK_Roles_OwnerGroups'
	UPDATE Roles SET OwnerGroupId = 0 WHERE OwnerGroupId IS NULL OR NOT OwnerGroupId IN (SELECT OwnerGroupId FROM OwnerGroups)
	ALTER TABLE dbo.Roles  WITH CHECK ADD  CONSTRAINT FK_Roles_OwnerGroups FOREIGN KEY(OwnerGroupId)
		REFERENCES dbo.OwnerGroups (OwnerGroupId) ON DELETE CASCADE
	ALTER TABLE dbo.Roles CHECK CONSTRAINT FK_Roles_OwnerGroups
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Roles_RoleCategories') AND type = 'F') 
BEGIN
	Print 'Add FK_Roles_RoleCategories'
	UPDATE Roles SET RoleCategoryId = NULL WHERE NOT RoleCategoryId IS NULL AND NOT RoleCategoryId IN (SELECT RoleCategoryId FROM RoleCategories)
	ALTER TABLE dbo.Roles  WITH CHECK ADD  CONSTRAINT FK_Roles_RoleCategories FOREIGN KEY(RoleCategoryId)
		REFERENCES dbo.RoleCategories (RoleCategoryId) ON DELETE CASCADE
	ALTER TABLE dbo.Roles CHECK CONSTRAINT FK_Roles_RoleCategories
END
GO
--#endregion FK_Roles_OwnerGroups und FK_Roles_RoleCategories

--#region
UPDATE FormulaConfigurations SET 
	FormulaId = 'BalancePeriodCastFormula',
	SerializedParameter = REPLACE(CAST(SerializedParameter AS VARCHAR(MAX)),'BalancePeroidCastFormula','BalancePeriodCastFormula')
WHERE FormulaId = 'BalancePeroidCastFormula'
GO
--#endregion

--#region
ALTER VIEW [dbo].[AbBudgets]
AS 
	SELECT Budgets.* 
			  FROM Budgets 
		INNER JOIN CostCenter_OwnerGroup AS CCG ON Budgets.CostCenterId = CCG.CostCenterId
		INNER JOIN Permissions AS UG ON UG.OwnerGroupId = CCG.OwnerGroupId
		INNER JOIN Users AS U ON U.UserId = UG.UserId
		INNER JOIN CostTypes AS CT ON Budgets.CostTypeId = CT.CostTypeId
	WHERE U.UserName = CURRENT_USER AND 
		  ((UG.PermissionArea = 1 AND CostTypeCategory = 0) OR UG.PermissionArea = 12 AND CostTypeCategory = 1)
GO
--#endregion

--#region SH 2019-12-04 PlanZR auf public stellen, da die views entfernt wurden
GRANT INSERT, UPDATE, DELETE ON PlanZR to PUBLIC
REVOKE SELECT, INSERT, UPDATE, DELETE on PlanZR To VorlagenSchreiben
GO
--#endregion  SH 2019-12-04 PlanZR auf public stellen, da die views entfernt wurden

--#region
UPDATE CAST SET GroupPosition = 1  WHERE GroupPosition = 0
GO
--#endregion
--#endregion -------- (4.196.x) -------------------------------

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

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

--#region SH 2020-01-15 PersNr_Sort_PersKTypID entfernen und anpassungen aus 2017 vornehmen
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PersonContactData]')  AND name = 'PersNr_Sort_PersKTypID')
BEGIN
	DROP Index PersonContactData.[PersNr_Sort_PersKTypID]

	DELETE FROM PersonContactData WHERE PersonId IS NULL
	ALTER TABLE PersonContactData ALTER COLUMN PersonId INT NOT NULL
	CREATE INDEX IX_PersCom_PersonId ON dbo.PersonContactData (PersonId) ON [PRIMARY]
	ALTER TABLE PersonContactData ALTER COLUMN Note VARCHAR(150) SPARSE NULL

	UPDATE PersonContactData Set Sort = 0 WHERE Sort IS NULL
	ALTER TABLE PersonContactData ALTER COLUMN Sort INT NOT NULL 
	ALTER TABLE PersonContactData ADD CONSTRAINT DF_PersonContactData_Sort DEFAULT 0 FOR Sort

	UPDATE CommunicationTypes Set Sort = 0 WHERE Sort IS NULL
	ALTER TABLE CommunicationTypes ALTER COLUMN Sort INT NOT NULL 
	ALTER TABLE CommunicationTypes ADD CONSTRAINT DF_CommunicationTypes_Sort DEFAULT 0 FOR Sort

	UPDATE CommunicationTypes Set IsDefault = 0 WHERE IsDefault IS NULL
	ALTER TABLE CommunicationTypes ALTER COLUMN IsDefault BIT NOT NULL 
	ALTER TABLE CommunicationTypes ADD CONSTRAINT DF_CommunicationTypes_IsDefault DEFAULT 0 FOR IsDefault

	UPDATE CommunicationTypes Set ComumunicationMedium = 0 WHERE ComumunicationMedium IS NULL
	ALTER TABLE CommunicationTypes ALTER COLUMN ComumunicationMedium TINYINT NOT NULL 
	ALTER TABLE CommunicationTypes ADD CONSTRAINT DF_CommunicationTypes_ComumunicationMedium DEFAULT 0 FOR ComumunicationMedium

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

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

	CREATE UNIQUE INDEX IX_PersComTyp_Name ON dbo.CommunicationTypes (Name) ON [PRIMARY]
	
	Update PersonContactData SET CommunicationTypeId = 0  WHERE CommunicationTypeId is null
	ALTER TABLE PersonContactData ALTER COLUMN CommunicationTypeId INT NOT NULL
END
GO
--#endregion SH 2020-01-15 PersNr_Sort_PersKTypID entfernen und anpassungen aus 2017 vornehmen

--#region SH 2020-01-15 spalte PersonContactData.locked entfernen
DropColumn 'PersonContactData','locked'
GO
--#endregion SH 2020-01-15 spalte PErsonContactData.locked entfernen
--#region DH-2020-01-15 Bugfix Casthistorie löschen beim Personen löschen

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 PersonId
	@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 = OwnerGroupId FROM Persons WHERE PersonId = @personId

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

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

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

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

	/*  Tabelle Contracts  */
	IF (SELECT COUNT(*) FROM Contracts WHERE PersonId = @personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Contract' + @CRLF
	END
	/*  Tabelle Contracts  */
	IF (SELECT COUNT(*) FROM ContractDetails WHERE ContractDetails.AgencyPersonId = @personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Contract (Agency)' + @CRLF
	END

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

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

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

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

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

	/*  Tabelle PersonRelations  */
	IF (@del > 0) 
		BEGIN
			DELETE FROM PersonRelations WHERE ChildPersonId = @personId
			DELETE FROM PersonRelations WHERE PersonId = @personId
			UPDATE PersonRelations SET ContactPersonConnectionID=NULL where ContactPersonConnectionID=@personId
		END


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

	/*  Tabelle BasicCastHistory */
	SELECT  @Temp = 0
		--TEMP zählt nur noch die Einträge, die auch in BasicCast noch existieren um das löschen von Personen nicht aufgrund von gelöschten Standardbesetzungen zu verhindern.
		--bei gelöschten Standardbesetzungseinträgen ist eine Berechtigungsprüfung nicht mehr möglich.
	SELECT @Temp = COUNT(*) FROM BasicCastHistory bch inner join BasicCast bc on bch.BasicCastId=bc.BasicCastId 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
			--erneutes zählen um auch die Historie von gelöschten Basiccasts zu löschen. 
			SELECT @Temp = COUNT(*) FROM BasicCastHistory WHERE PersonOldId = @personId OR PersonNewId = @personId;
	
			IF(@Temp) > 0
			BEGIN 
				IF (@del > 0) DELETE FROM BasicCastHistory WHERE PersonOldId = @personId OR PersonNewId = @personId
			END
		END

	/*  Tabelle PersonFeeNotes  */
	IF (@del > 0) DELETE FROM PersonFeeNotes WHERE PersonId=@personId

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


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

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

	/*  Tabelle AbPersZusatzDaten_Update  */
		SELECT  @Temp = 0
		SELECT @Temp = COUNT(*) FROM PersonAdditionalData WHERE PersonId = @personId
		IF (SELECT COUNT(*) FROM AbPersZusatzDaten_Update WHERE PersonId = @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 PersonAdditionalData WHERE PersonId = @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 CashCommands WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'CashCommand' + @CRLF
		END


	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM CashCommands 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 Departments 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 Bugfix

--#region DH 2020-01-17 Löschen von Kontaktzuordnungen
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 PersonId
	@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 = OwnerGroupId FROM Persons WHERE PersonId = @personId

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

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

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

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

	/*  Tabelle Contracts  */
	IF (SELECT COUNT(*) FROM Contracts WHERE PersonId = @personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Contract' + @CRLF
	END
	/*  Tabelle Contracts  */
	IF (SELECT COUNT(*) FROM ContractDetails WHERE ContractDetails.AgencyPersonId = @personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Contract (Agency)' + @CRLF
	END

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

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

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

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

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

	/*  Tabelle PersonRelations  */
	IF (@del > 0) 
		BEGIN
			UPDATE PersonRelations SET ContactPersonConnectionID=NULL where ContactPersonConnectionID in (SELECT PersonRelationId FROM PersonRelations WHERE ChildPersonId=@personid) 
			DELETE FROM PersonRelations WHERE ChildPersonId = @personId;
			DELETE FROM PersonRelations WHERE PersonId = @personId;			
		END


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

	/*  Tabelle BasicCastHistory */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM BasicCastHistory 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 BasicCastHistory WHERE PersonOldId = @personId OR PersonNewId = @personId
			END
		END

	/*  Tabelle PersonFeeNotes  */
	IF (@del > 0) DELETE FROM PersonFeeNotes WHERE PersonId=@personId

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


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

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

	/*  Tabelle AbPersZusatzDaten_Update  */
		SELECT  @Temp = 0
		SELECT @Temp = COUNT(*) FROM PersonAdditionalData WHERE PersonId = @personId
		IF (SELECT COUNT(*) FROM AbPersZusatzDaten_Update WHERE PersonId = @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 PersonAdditionalData WHERE PersonId = @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 CashCommands WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'CashCommand' + @CRLF
		END


	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM CashCommands 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 Departments 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 DH 2020-01-17 Löschen von Kontaktzuordnungen
--#region DH 2020-01-17 Bugfix Budgetverwaltung
ALTER VIEW [dbo].[AbBudgets]
AS 
	SELECT DISTINCT Budgets.* 
			  FROM Budgets 
		INNER JOIN CostCenter_OwnerGroup AS CCG ON Budgets.CostCenterId = CCG.CostCenterId
		INNER JOIN Permissions AS UG ON UG.OwnerGroupId = CCG.OwnerGroupId
		INNER JOIN Users AS U ON U.UserId = UG.UserId
		INNER JOIN CostTypes AS CT ON Budgets.CostTypeId = CT.CostTypeId
	WHERE U.UserName = CURRENT_USER AND 
		  ((UG.PermissionArea = 1 AND CostTypeCategory = 0) OR UG.PermissionArea = 12 AND CostTypeCategory = 1)
GO
--#endregion DH 2020-01-17 Budgetverwaltung
--#region DH 2020-01-31 Bugfix Langsames Sperren
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[TR_Update_Activity] ON [dbo].[Activities] AFTER UPDATE
		AS 
	SET NOCOUNT ON
	IF UPDATE(IsSecret)
	BEGIN
		UPDATE xh SET xh.IsSecret = ins.IsSecret FROM ActivityHistory  AS xh  JOIN  INSERTED AS ins ON xh.ActivityId = ins.ActivityId
		UPDATE x SET x.IsActivitySecret= ins.IsSecret FROM CastHistory AS X JOIN INSERTED AS ins ON x.ActivityId = ins.ActivityId
	END
GO
--#endregion DH 2020-01-31 Bugfix Langsames Sperren

--#endregion -------- (4.196.x 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 ----------- Views aktualisieren ---------------------
--#region ----------- 4.196 Post Cleanup ---------------------

IF EXISTS (SELECT * FROM NVDATA WHERE ByModulScript = 1 AND (Major * 100000000) + (Minor * 1000) + Build  < 400196003) 
BEGIN
	DECLARE @from DATE
	SELECT @from = GETDATE()-1095
	Print 'TruncateUpdateLog from: ' + CAST(@from AS VARCHAR(10))
	EXECUTE TruncateUpdateLog @from

	Print 'CLEANTABLE...'
	EXEC sp_msforeachtable 'DBCC CLEANTABLE(0, ''?'') WITH NO_INFOMSGS'; 

	Print 'REBUILD...'
	EXEC sp_msforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER INDEX ALL ON ? REBUILD'
END


--#endregion ----------- 4.196 Post Cleanup ---------------------
--#region zum Löschen in 2020 vormarkiert
--AbTechnicalPersonalRequirements
--PresseText
--PlanZR
-- VertragDetails UnterkunftVs
--VertragDetails Reisekosten
	--DELETE FROM VertragRolle WHERE VRID IN 
	--		(	SELECT  vr.Vrid 
	--			FROM VertragRolle AS VR 
	--				INNER JOIN Vertrag AS v ON vr.VertragsNr = v.VertragsNr 
	--				INNER JOIN Gruppe AS G ON v.ModulGruppeID = g.GruppeID 
	--			WHERE g.Modul = 4 AND NOT v.CostUnitId IS NULL)
--EXEC DropColumn 'ProductionDetails' ,'T10'
--EXEC DropColumn 'ProductionDetails' ,'T20'
--EXEC DropColumn 'ProductionDetails' ,'T30'
--EXEC DropColumn 'ProductionDetails' ,'T40'
--EXEC DropColumn 'ProductionDetails' ,'F10'
--EXEC DropColumn 'ProductionDetails' ,'F20'
--EXEC DropColumn 'ProductionDetails' ,'F30'
--EXEC DropColumn 'ProductionDetails' ,'F40'
--EXEC DropColumn 'ProductionDetails' ,'L10'
--EXEC DropColumn 'ProductionDetails' ,'L20'
--EXEC DropColumn 'ProductionDetails' ,'L30'
--EXEC DropColumn 'ProductionDetails' ,'L40'
--EXEC DropColumn 'ProductionDetails' ,'L50'
--EXEC DropColumn 'ProductionDetails' ,'L60'
--EXEC DropColumn 'ProductionDetails' ,'LRechts'
--EXEC DropColumn 'ProductionDetails' ,'KRechts'
--EXEC DropColumn 'ProductionDetails' ,'K10'
--EXEC DropColumn 'ProductionDetails' ,'K20'
--EXEC DropColumn 'ProductionDetails' ,'K30'
--EXEC DropColumn 'ProductionDetails' ,'K40'
--EXEC DropColumn 'ProductionDetails' ,'InternetLink'
--EXEC DropColumn 'ProductionDetails' ,'Memo'
--EXEC DropColumn 'ProductionDetails' ,'Memo_en'
--EXEC DropColumn 'ContractDetails' ,'UnterkunftVs'
--EXEC DropColumn 'ContractDetails' ,'ReiseKosten'
--EXEC DropColumn 'ContractDetails' ,'Memo1'
--EXEC DropColumn 'ContractDetails' ,'Memo2'
--EXEC DropColumn 'ContractDetails' ,'Memo3'
--EXEC DropColumn 'ContractDetails' ,'Memo4'
--EXEC DropColumn 'ContractDetails' ,'Memo5'
--EXEC DropColumn 'ContractDetails' ,'Memo6'
--EXEC DropColumn 'ContractDetails' ,'Optionen'
--EXEC DropColumn 'ContractDetails' ,'HasPriority'
--EXEC DropColumn 'PersonPermissions', 'HasAccessToSecretContactData'
--#endregion zum löschen in 2020 vormarkiert
---------------------------------------------------------------
--#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'DropDefaultConstraint'))			DROP PROCEDURE dbo.DropDefaultConstraint 
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].DropDefaultConstraint'))		DROP PROCEDURE dbo.DropDefaultConstraint 
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 ----------- Wegräumen der Hilfsprozeduren -----------
---------------------------------------------------------------
--#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 = 196
SET @build = 105
SET @Datum = 20200131
--#endregion ----------- Version aus ts_evt in TS_DataClass ------
--#region ----------- Version setzen ---------------------------
PRINT('Updating NvData...')
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

PRINT	('
		Script version ' + CAST(@major AS VARCHAR(4))+'.'+ CAST(@minor AS VARCHAR(4))+'.'+CAST(@build AS VARCHAR(4)) + ' finnished.
		')
GO
--#endregion  ----------- Version setzen ---------------------------
--#endregion ----------- VERSIONIERUNG ---------------------------
--#region ----------- NOEXEC OFF ------------------------------
SET NOEXEC OFF
--#endregion ----------- NOEXEC OFF ------------------------------