/*
	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 176
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 176 OR (Minor=176 AND Build < 100)))))
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='		
																																															Print ''
																																															Print '		Der Versionsunterschied ist zu groß!!!'	
																																															Print '		Bitte führen Sie DbScript_2017.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 191
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major > 4 OR (Major = 4 AND (Minor >= 191))))
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='		
																																															Print ''
																																															Print '		Veraltete Skriptversion!!!'	
																																															Print '		Bitte führen Sie DbScript_2019.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
-- alte varianten entfernen
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].DeleteConstraint'))
BEGIN
	DROP PROCEDURE dbo.DeleteConstraint 
END
GO

IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].DropDefault'))
BEGIN
	DROP PROCEDURE dbo.DropDefault 
END
GO

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(@tablename) AND name = @columnname)

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

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

--#endregion

--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 : 22.01.2017 ---------
--------------------- Datenbankänderungen ab hier -------------
--------------------- möglichst mit regions umschließen -------

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

--Änderungen aus CreateDb_2017.sql

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

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

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

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


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

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

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

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

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

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

GRANT EXECUTE ON MergeDoubletten TO PUBLIC
GO
--#endregion

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

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

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

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

	Rückgabewerte:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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


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


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

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

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

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

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


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

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

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

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

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

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


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

--#region DH 2018-02-13 Bugfix SecurityAdmin deletes User 
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

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

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

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

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

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

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

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

--#endregion

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

--#region ----------- 4.181.x ---------------------------------

--#region Rapport-Bez Extend DH 201801018
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Bez' and o.id = OBJECT_ID(N'dbo.Rapport') and c.prec <> 20)
BEGIN
	PRINT ('UQ_Rapport_Name_Module')
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.Rapport') AND o.Name = 'UQ_Rapport_BezModule') DROP INDEX  Rapport.UQ_Rapport_BezModule
	UPDATE Rapport SET Bez = CONVERT(VARCHAR(10),RID) WHERE Bez IS NULL
	ALTER TABLE Rapport ALTER COLUMN Bez VARCHAR(20) NOT NULL
	CREATE UNIQUE NONCLUSTERED INDEX [UQ_Rapport_Name_Module] ON [dbo].[Rapport] (Bez, Module)
END
GO
--#endregion

--#region SH 2018-01-26 Umstellung von View DienstplanArten da das DISTINCT mit XML Spalte nicht geht
IF EXISTS(SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID('[dbo].[DienstplanArten]'))
BEGIN
	DROP VIEW [dbo].[DienstplanArten]
END
GO
CREATE VIEW [dbo].[DienstplanArten]
AS
	SELECT * FROM DienstplanArtenTabelle dat WHERE dat.DienstplanArtenID IN (
		SELECT
			da.DienstplanArtenID
		FROM
			DienstplanArtenTabelle  AS da	
			LEFT JOIN (SELECT * FROM UserGruppe WHERE BerechtigungsbereichID = 5) AS ug ON da.ModulGruppeID = ug.GruppeID
			LEFT JOIN UserPW AS up ON ug.UserID = up.UserID 
		WHERE
			up.UserName = CURRENT_USER
	)
GO

GRANT SELECT ON [DienstplanArten] TO [public]
GO

--#endregion

--#region SH 2018-01-26 Umstellen von text/ntext auf varchar(max)/nvarchar(max) bzw. auf xml, falls es sich um serialisierte xml settings handelt
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('AdressAusgabe') AND [name] = 'ContentSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'AdressAusgabe' ,@columnname = 'ContentSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('AdressAusgabe') AND [name] = 'ConverterSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'AdressAusgabe' ,@columnname = 'ConverterSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('AdressPlan') AND [name] = 'Kopf' AND system_type_id = 35)
BEGIN
	PRINT('Changing AdressPlan.Kopf to VARCHAR(MAX)...')
	ALTER TABLE AdressPlan ALTER COLUMN Kopf VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('AufführgDetails') AND [name] = 'FieldChangeHistory' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'AufführgDetails' ,@columnname = 'FieldChangeHistory'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('BesRepertoire') AND [name] = 'Memo' AND system_type_id = 35)
BEGIN
	PRINT('Changing BesRepertoire.Memo to VARCHAR(MAX)...')
	ALTER TABLE BesRepertoire ALTER COLUMN Memo VARCHAR(MAX) SPARSE NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('BodyMeasurements') AND [name] = 'Note' AND system_type_id = 35)
BEGIN
	PRINT('Changing BodyMeasurements.Note to VARCHAR(MAX)...')
	ALTER TABLE BodyMeasurements ALTER COLUMN Note VARCHAR(MAX) SPARSE NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('BonusDefaultAmounts') AND [name] = 'FilterSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'BonusDefaultAmounts' ,@columnname = 'FilterSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('CheckListItem') AND [name] = 'Note' AND system_type_id = 35)
BEGIN
	PRINT('Changing CheckListItem.Note to VARCHAR(MAX)...')
	ALTER TABLE CheckListItem ALTER COLUMN Note VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ContractBonus') AND [name] = 'RuleSettings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'ContractBonus' ,@columnname = 'RuleSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ContractConfirmations') AND [name] = 'Summary' AND system_type_id = 35)
BEGIN
	PRINT('Changing ContractConfirmations.Summary to VARCHAR(MAX)...')
	ALTER TABLE ContractConfirmations ALTER COLUMN Summary VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Dienstplan') AND [name] = 'BreakCorridorSettings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'Dienstplan' ,@columnname = 'BreakCorridorSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('DienstplanArtenTabelle') AND [name] = 'HeaderSettings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'DienstplanArtenTabelle' ,@columnname = 'HeaderSettings', @endTag = '</DutyRosterHeaderSettings>'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('DienstplanArtenTabelle') AND [name] = 'LayoutSettings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'DienstplanArtenTabelle' ,@columnname = 'LayoutSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('DienstplanArtenTabelle') AND [name] = 'DepartmentWorkingTimeSettings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'DienstplanArtenTabelle' ,@columnname = 'DepartmentWorkingTimeSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ExportProfiles') AND [name] = 'ExportAreaProviderSettings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'ExportProfiles' ,@columnname = 'ExportAreaProviderSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ExportProfiles') AND [name] = 'ExportProviderSettings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'ExportProfiles' ,@columnname = 'ExportProviderSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ExportProfiles') AND [name] = 'ZipSettings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'ExportProfiles' ,@columnname = 'ZipSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ExportProfiles') AND [name] = 'TransferSettings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'ExportProfiles' ,@columnname = 'TransferSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ExportProfiles') AND [name] = 'MailingSettings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'ExportProfiles' ,@columnname = 'MailingSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('HDMVorlagen') AND [name] = 'FilterSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'HDMVorlagen' ,@columnname = 'FilterSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('HDM') AND [name] = 'ColumnSettings' AND system_type_id = 167)
BEGIN
	--nur 4000 zeichen lang
	EXEC ConvertColumnToXml @tablename = 'HDM' ,@columnname = 'ColumnSettings', @endTag = '</ArrayOfColumnSetting>'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('HDMVorlagen') AND [name] = 'ColumnSettings' AND system_type_id = 167)
BEGIN
	--nur 4000 zeichen lang
	EXEC ConvertColumnToXml @tablename = 'HDMVorlagen' ,@columnname = 'ColumnSettings', @endTag = '</ArrayOfColumnOrder>'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('HDMVorlagen') AND [name] = 'FixedColumnSettings' AND system_type_id = 167)
BEGIN
	--nur 4000 zeichen lang
	EXEC ConvertColumnToXml @tablename = 'HDMVorlagen' ,@columnname = 'FixedColumnSettings', @endTag = '</ArrayOfConfigurableColumnSetting>'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('HDMVorlagen') AND [name] = 'Settings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'HDMVorlagen' ,@columnname = 'Settings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Instrumenbestand') AND [name] = 'Memo' AND system_type_id = 35)
BEGIN
	PRINT('Changing Instrumenbestand.Memo to VARCHAR(MAX)...')
	ALTER TABLE Instrumenbestand ALTER COLUMN Memo VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Kalender') AND [name] = 'Memo' AND system_type_id = 35)
BEGIN
	PRINT('Changing Kalender.Memo to VARCHAR(MAX)...')
	ALTER TABLE Kalender ALTER COLUMN Memo VARCHAR(MAX) SPARSE NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PeriodNotes') AND [name] = 'Note' AND system_type_id = 35)
BEGIN
	PRINT('Changing PeriodNotes.Note to VARCHAR(MAX)...')
	ALTER TABLE PeriodNotes ALTER COLUMN Note VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PersonalDetails') AND [name] = 'Memo' AND system_type_id = 35)
BEGIN
	PRINT('Changing PersonalDetails.Memo to VARCHAR(MAX)...')
	ALTER TABLE PersonalDetails ALTER COLUMN Memo VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PersonalDetails') AND [name] = 'MemoExtern' AND system_type_id = 99)
BEGIN
	PRINT('Changing PersonalDetails.MemoExtern to NVARCHAR(MAX)...')
	ALTER TABLE PersonalDetails ALTER COLUMN MemoExtern NVARCHAR(MAX) SPARSE NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PersonalDetails') AND [name] = 'MemoExtern_en' AND system_type_id = 99)
BEGIN
	PRINT('Changing PersonalDetails.MemoExtern_en to NVARCHAR(MAX)...')
	ALTER TABLE PersonalDetails ALTER COLUMN MemoExtern_en NVARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PersonalHonorar') AND [name] = 'MemoVertraulich' AND system_type_id = 35)
BEGIN
	PRINT('Changing PersonalHonorar.MemoVertraulich to VARCHAR(MAX)...')
	ALTER TABLE PersonalHonorar ALTER COLUMN MemoVertraulich VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PersoParameter') AND [name] = 'PolicySettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'PersoParameter', @columnname = 'PolicySettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PersoParameter') AND [name] = 'BreakRules' AND system_type_id = 167)
BEGIN
	--nur 2000 zeichen lang
	EXEC ConvertColumnToXml @tablename = 'PersoParameter', @columnname = 'BreakRules', @endTag = '</BreakRules>'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Plan') AND [name] = 'F1' AND system_type_id = 35)
BEGIN
	PRINT('Changing Plan.F1 to VARCHAR(MAX)...')
	ALTER TABLE [Plan] ALTER COLUMN F1 VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Plan') AND [name] = 'T1' AND system_type_id = 35)
BEGIN
	PRINT('Changing Plan.T1 to VARCHAR(MAX)...')
	ALTER TABLE [Plan] ALTER COLUMN T1 VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Plan') AND [name] = 'T2' AND system_type_id = 35)
BEGIN
	PRINT('Changing Plan.T2 to VARCHAR(MAX)...')
	ALTER TABLE [Plan] ALTER COLUMN T2 VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Plan') AND [name] = 'T3' AND system_type_id = 35)
BEGIN
	PRINT('Changing Plan.T3 to VARCHAR(MAX)...')
	ALTER TABLE [Plan] ALTER COLUMN T3 VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PlanSort') AND [name] = 'ContentSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'PlanSort' ,@columnname = 'ContentSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PlanSort') AND [name] = 'Settings' AND system_type_id = 35)
BEGIN
	PRINT('Changing PlanSort.Settings to VARCHAR(MAX)...')
	ALTER TABLE PlanSort ALTER COLUMN Settings VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PlanSpalte') AND [name] = 'ColumnSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'PlanSpalte' ,@columnname = 'ColumnSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ProductionResources') AND [name] = 'Note' AND system_type_id = 35)
BEGIN
	PRINT('Changing ProductionResources.Note to VARCHAR(MAX)...')
	ALTER TABLE ProductionResources ALTER COLUMN Note VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Rapport') AND [name] = 'FormatSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'Rapport', @columnname = 'FormatSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RapportSpalte') AND [name] = 'FilterSettings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'RapportSpalte', @columnname = 'FilterSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RapportSpalte') AND [name] = 'FormulaSettings' AND system_type_id = 167)
BEGIN
	--nur 2000 zeichen lang
	EXEC ConvertColumnToXml @tablename = 'RapportSpalte', @columnname = 'FormulaSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RapportSpalte') AND [name] = 'PayOutRule' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'RapportSpalte', @columnname = 'PayOutRule'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Reminder') AND [name] = 'Body' AND system_type_id = 35)
BEGIN
	PRINT('Changing Reminder.Body to VARCHAR(MAX)...')
	ALTER TABLE Reminder ALTER COLUMN Body VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ResourceBlockPeriods') AND [name] = 'Note' AND system_type_id = 35)
BEGIN
	PRINT('Changing ResourceBlockPeriods.Note to VARCHAR(MAX)...')
	ALTER TABLE ResourceBlockPeriods ALTER COLUMN Note VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Role_Season') AND [name] = 'Note' AND system_type_id = 35)
BEGIN
	PRINT('Changing Role_Season.Note to VARCHAR(MAX)...')
	ALTER TABLE Role_Season ALTER COLUMN Note VARCHAR(MAX) SPARSE NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RollenLtg') AND [name] = 'Settings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'RollenLtg', @columnname = 'Settings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('SalaryLevel') AND [name] = 'FeeRuleSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'SalaryLevel', @columnname = 'FeeRuleSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('SalaryLevelData') AND [name] = 'FeeRuleSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'SalaryLevelData', @columnname = 'FeeRuleSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Serienbrief') AND [name] = 'SBInhalt' AND system_type_id = 35)
BEGIN
	PRINT('Changing Serienbrief.SBInhalt to VARCHAR(MAX)...')
	ALTER TABLE Serienbrief ALTER COLUMN SBInhalt VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Settings') AND [name] = 'Wert' AND system_type_id = 35)
BEGIN
	PRINT('Changing Settings.Wert to VARCHAR(MAX)...')
	ALTER TABLE Settings ALTER COLUMN Wert VARCHAR(MAX) SPARSE NULL 
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Status') AND [name] = 'FormatSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'Status', @columnname = 'FormatSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Status') AND [name] = 'Settings' AND system_type_id = 167)
BEGIN
	--nur 600 zeichen lang
	EXEC ConvertColumnToXml @tablename = 'Status', @columnname = 'Settings', @endTag = '</PersStatusTypSettings>'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('StückeDetails') AND [name] = 'Memo' AND system_type_id = 35)
BEGIN
	PRINT('Changing StückeDetails.Memo to VARCHAR(MAX)...')
	ALTER TABLE StückeDetails ALTER COLUMN Memo VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('StückeDetails') AND [name] = 'Memo_en' AND system_type_id = 35)
BEGIN
	PRINT('Changing StückeDetails.Memo_en to VARCHAR(MAX)...')
	ALTER TABLE StückeDetails ALTER COLUMN Memo_en VARCHAR(MAX) SPARSE NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('StückeDetails') AND [name] = 'MemoIntern' AND system_type_id = 35)
BEGIN
	PRINT('Changing StückeDetails.MemoIntern to VARCHAR(MAX)...')
	ALTER TABLE StückeDetails ALTER COLUMN MemoIntern VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Typ') AND [name] = 'FormatSettings' AND system_type_id = 167)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'Typ' ,@columnname = 'FormatSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('UserGruppe') AND [name] = 'Options' AND system_type_id = 167)
BEGIN
	--nur 2000 zeichen lang
	EXEC ConvertColumnToXml @tablename = 'UserGruppe', @columnname = 'Options', @endTag = '</OrchestraSecurityOptions>'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('UrlaubsberechnungsModell') AND [name] = 'XmlSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'UrlaubsberechnungsModell', @columnname = 'XmlSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Verteiler') AND [name] = 'sqlString' AND system_type_id = 35)
BEGIN
	PRINT('Changing Verteiler.sqlString to VARCHAR(MAX)...')
	ALTER TABLE Verteiler ALTER COLUMN sqlString VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('VerteilerFeld') AND [name] = 'TextBoxValue' AND system_type_id = 35)
BEGIN
	PRINT('Changing VerteilerFeld.TextBoxValue to VARCHAR(MAX)...')
	ALTER TABLE VerteilerFeld ALTER COLUMN TextBoxValue VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('VertragDetails') AND [name] = 'Memo1' AND system_type_id = 35)
BEGIN
	PRINT('Changing VertragDetails.Memo1 to VARCHAR(MAX)...')
	ALTER TABLE VertragDetails ALTER COLUMN Memo1 VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('VertragDetails') AND [name] = 'Memo2' AND system_type_id = 35)
BEGIN
	PRINT('Changing VertragDetails.Memo2 to VARCHAR(MAX)...')
	ALTER TABLE VertragDetails ALTER COLUMN Memo2 VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('VertragDetails') AND [name] = 'Memo3' AND system_type_id = 35)
BEGIN
	PRINT('Changing VertragDetails.Memo3 to VARCHAR(MAX)...')
	ALTER TABLE VertragDetails ALTER COLUMN Memo3 VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('VertragDetails') AND [name] = 'Memo4' AND system_type_id = 35)
BEGIN
	PRINT('Changing VertragDetails.Memo4 to VARCHAR(MAX)...')
	ALTER TABLE VertragDetails ALTER COLUMN Memo4 VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('VertragDetails') AND [name] = 'Memo5' AND system_type_id = 35)
BEGIN
	PRINT('Changing VertragDetails.Memo5 to VARCHAR(MAX)...')
	ALTER TABLE VertragDetails ALTER COLUMN Memo5 VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('VertragDetails') AND [name] = 'Memo6' AND system_type_id = 35)
BEGIN
	PRINT('Changing VertragDetails.Memo6 to VARCHAR(MAX)...')
	ALTER TABLE VertragDetails ALTER COLUMN Memo6 VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('VertragRolle') AND [name] = 'FeeComment' AND system_type_id = 35)
BEGIN
	PRINT('Changing VertragRolle.FeeComment to VARCHAR(MAX)...')
	ALTER TABLE VertragRolle ALTER COLUMN FeeComment VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('VertragRolle') AND [name] = 'RehearsalFeeComment' AND system_type_id = 35)
BEGIN
	PRINT('Changing VertragRolle.RehearsalFeeComment to VARCHAR(MAX)...')
	ALTER TABLE VertragRolle ALTER COLUMN RehearsalFeeComment VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('VertragsVorlagen') AND [name] = 'CastWorkingHoursSettings' AND system_type_id = 167)
BEGIN
	--nur 2000 zeichen lang
	EXEC ConvertColumnToXml @tablename = 'VertragsVorlagen', @columnname = 'CastWorkingHoursSettings', @endTag = '</CastWorkingHoursSettings>'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('VertragsVorlagen') AND [name] = 'Note' AND system_type_id = 35)
BEGIN
	PRINT('Changing VertragsVorlagen.Note to VARCHAR(MAX)...')
	ALTER TABLE VertragsVorlagen ALTER COLUMN Note VARCHAR(MAX) SPARSE NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Vorlagen') AND [name] = 'Beschreibung' AND system_type_id = 35)
BEGIN
	PRINT('Changing Vorlagen.Beschreibung to VARCHAR(MAX)...')
	ALTER TABLE Vorlagen ALTER COLUMN Beschreibung VARCHAR(MAX) SPARSE NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Vorlagen') AND [name] = 'TemplateParameterData' AND system_type_id = 231)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'Vorlagen', @columnname = 'TemplateParameterData'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('WageDataExportProfiles') AND [name] = 'ExportProviderSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'WageDataExportProfiles', @columnname = 'ExportProviderSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('WageDataExportProfiles') AND [name] = 'SendMailSettings' AND system_type_id = 35)
BEGIN
	EXEC ConvertColumnToXml @tablename = 'WageDataExportProfiles', @columnname = 'SendMailSettings'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Works') AND [name] = 'Description' AND system_type_id = 35)
BEGIN
	PRINT('Changing Works.Description to VARCHAR(MAX)...')
	ALTER TABLE Works ALTER COLUMN Description VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('WorkVersionRoles') AND [name] = 'Description' AND system_type_id = 35)
BEGIN
	PRINT('Changing WorkVersionRoles.Description to VARCHAR(MAX)...')
	ALTER TABLE WorkVersionRoles ALTER COLUMN Description VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('WorkVersionRoles_Repertoire') AND [name] = 'Description' AND system_type_id = 35)
BEGIN
	PRINT('Changing WorkVersionRoles_Repertoire.Description to VARCHAR(MAX)...')
	ALTER TABLE WorkVersionRoles_Repertoire ALTER COLUMN Description VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('WorkVersions') AND [name] = 'Note' AND system_type_id = 35)
BEGIN
	PRINT('Changing WorkVersions.Note to VARCHAR(MAX)...')
	ALTER TABLE WorkVersions ALTER COLUMN Note VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('WorkVersions') AND [name] = 'PurchaseNote' AND system_type_id = 35)
BEGIN
	PRINT('Changing WorkVersions.PurchaseNote to VARCHAR(MAX)...')
	ALTER TABLE WorkVersions ALTER COLUMN PurchaseNote VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('XHDelAufführg') AND [name] = 'Bem' AND system_type_id = 35)
BEGIN
	PRINT('Changing XHDelAufführg.Bem to VARCHAR(MAX)...')
	ALTER TABLE XHDelAufführg ALTER COLUMN Bem VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('XHDelAufführg') AND [name] = 'XHBem' AND system_type_id = 35)
BEGIN
	PRINT('Changing XHDelAufführg.XHBem to VARCHAR(MAX)...')
	ALTER TABLE XHDelAufführg ALTER COLUMN XHBem VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('XHDelAufführg') AND [name] = 'XHDetails' AND system_type_id = 35)
BEGIN
	PRINT('Changing XHDelAufführg.XHDetails to VARCHAR(MAX)...')
	ALTER TABLE XHDelAufführg ALTER COLUMN XHDetails VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('XHDelBesetzung') AND [name] = 'Bem' AND system_type_id = 35)
BEGIN
	PRINT('Changing XHDelBesetzung.Bem to VARCHAR(MAX)...')
	ALTER TABLE XHDelBesetzung ALTER COLUMN Bem VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('XHDelBesetzung') AND [name] = 'XHBem' AND system_type_id = 35)
BEGIN
	PRINT('Changing XHDelBesetzung.XHBem to VARCHAR(MAX)...')
	ALTER TABLE XHDelBesetzung ALTER COLUMN XHBem VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('XHDelBesetzung') AND [name] = 'XHDetails' AND system_type_id = 35)
BEGIN
	PRINT('Changing XHDelBesetzung.XHDetails to VARCHAR(MAX)...')
	ALTER TABLE XHDelBesetzung ALTER COLUMN XHDetails VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ZR') AND [name] = 'FontFormatString' AND system_type_id = 167)
BEGIN
	--nur 600 zeichen lang
	EXEC ConvertColumnToXml @tablename = 'ZR' ,@columnname = 'FontFormatString', @endTag = '</FontFormat>'
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ZrAbschnitte') AND [name] = 'MemoA' AND system_type_id = 35)
BEGIN
	PRINT('Changing ZrAbschnitte.MemoA to VARCHAR(MAX)...')
	ALTER TABLE ZrAbschnitte ALTER COLUMN MemoA VARCHAR(MAX) NULL
END
GO
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ZrAbschnitte') AND [name] = 'MemoB' AND system_type_id = 35)
BEGIN
	PRINT('Changing ZrAbschnitte.MemoB to VARCHAR(MAX)...')
	ALTER TABLE ZrAbschnitte ALTER COLUMN MemoB VARCHAR(MAX) NULL
END
GO
--#endregion

--#region SH 2018-01-26 Default Bindings umstellen auf Default Constraints
IF EXISTS (SELECT * FROM sys.all_objects ao WHERE ao.type = 'D' AND ao.parent_object_id = 0 AND ao.is_ms_shipped = 0)
BEGIN
	-- tabelle für die bekannten defaults
	DECLARE @defaultNames TABLE (
		id INT IDENTITY (1,1),
		defaultName VARCHAR(50)
	)

	-- defaults einfügen
	INSERT INTO @defaultNames (defaultName)
	SELECT ao.name FROM sys.all_objects ao WHERE ao.type = 'D' AND ao.parent_object_id = 0 AND ao.is_ms_shipped = 0

	-- tabelle für die umzustellenden defaults
	DECLARE @FixList TABLE (
		Number INT NOT NULL PRIMARY KEY CLUSTERED
	   ,TableName SYSNAME NOT NULL
	   ,ColumnName SYSNAME NOT NULL
	   ,DefaultObject SYSNAME NOT NULL
	)

	-- umzustellende defaults einfügen, das sind die die verwendeten defaults
	INSERT @FixList (Number, TableName, ColumnName, DefaultObject)
	SELECT
		Number = ROW_NUMBER() OVER (ORDER BY e.name, c.name),
		e.name as table_name,
		c.name as column_name,
		ex.name as default_object
	FROM sys.columns c
	JOIN sys.tables e ON e.object_id = c.object_id  
	LEFT JOIN sys.all_objects ex ON ex.object_id = c.default_object_id 
	JOIN sys.types t ON c.user_type_id = t.user_type_id  
	Where OBJECTPROPERTY(c.object_id, 'IsMsShipped')=0  
	and ex.name IN (SELECT defaultName FROM @defaultNames)
	order by 1, 2

	DECLARE @RowID INT, @SQL VARCHAR(1000)
	SELECT @RowID = 1, @SQL = ''''
	DECLARE @TableName SYSNAME
	DECLARE @ColumnName SYSNAME
	DECLARE @DefaultObject SYSNAME
	DECLARE @I INT
	DECLARE @debug BIT

	--fehlerbehandlung
	declare @error int, @line INT, @severity INT, @state INT, @procedure NVARCHAR(128), @message nvarchar(4000), @xstate int;

	SET @debug = 0
	-- defaults umstellen

	SET @I = 1

	SELECT @RowID = Number, @TableName = TableName, @ColumnName = ColumnName, @DefaultObject = DefaultObject FROM @FixList WHERE NUMBER = @I
	WHILE @TableName IS NOT NULL
	BEGIN
		-- unbind default object
		BEGIN TRY
			PRINT ('Unbinding Default of ' + @TableName + '.' + @ColumnName + '...')
			SET @SQL = 'EXECUTE sp_unbindefault N''['+@TableName+'].['+@ColumnName+']'''

			IF @debug = 1
				PRINT @SQL

			EXEC(@SQL)

			IF @DefaultObject = 'UW_SpaceDefault'
				SET @SQL = 'ALTER TABLE ['+@TableName+'] ADD CONSTRAINT DF_'+@TableName+'_'+@ColumnName+' DEFAULT '''' FOR ['+@ColumnName+'] '
			
			ELSE IF @DefaultObject = 'UW_ZeroDefault'
				SET @SQL = 'ALTER TABLE ['+@TableName+'] ADD CONSTRAINT DF_'+@TableName+'_'+@ColumnName+' DEFAULT 0 FOR ['+@ColumnName+'] '

			ELSE IF @DefaultObject IN ('UW_OneDefault', 'Wochenplan_Pos_D', 'Wochenplan_Leerzeile_D', 'Wochenplan_JahresP_D', 'Wochenplan_Alle_D'
					, 'Wochenplan_AboCr_D', 'Wochenplan_Abo_D', 'Wochenplan_A3_D', 'Typ_Farbe_D', 'TagSparteSort_Seite_D', 'StückeDetails_VonDru_D'
					, 'StückeDetails_BisZeit_D', 'PresseText_VonDru_D', 'PresseText_BisZeit_D', 'FahrplanStd_RichtungHin_D', 'Fahrplan_RichtungHin_D'
					, 'BesetzungStd_nameDrucken_D', 'Aufführg_DiplaDru_D', 'AdressPlan_AllePersKat_D')
				SET @SQL = 'ALTER TABLE ['+@TableName+'] ADD CONSTRAINT DF_'+@TableName+'_'+@ColumnName+' DEFAULT 1 FOR ['+@ColumnName+'] '

			ELSE IF @DefaultObject = 'UW_NullDefault'
				SET @SQL = 'ALTER TABLE ['+@TableName+'] ADD CONSTRAINT DF_'+@TableName+'_'+@ColumnName+' DEFAULT NULL FOR ['+@ColumnName+'] '

			ELSE IF @DefaultObject IN ('ZrAbschnitte_SGB_D', 'ZrAbschnitte_SGA_D', 'WochenplanSpalte_Schrift_D', 'AdressAusgabe_Schrift_D')
				SET @SQL = 'ALTER TABLE ['+@TableName+'] ADD CONSTRAINT DF_'+@TableName+'_'+@ColumnName+' DEFAULT 8 FOR ['+@ColumnName+'] '

			ELSE IF @DefaultObject IN ('Status_StatusArt_D')
				SET @SQL = 'ALTER TABLE ['+@TableName+'] ADD CONSTRAINT DF_'+@TableName+'_'+@ColumnName+' DEFAULT 10 FOR ['+@ColumnName+'] '

			ELSE IF @DefaultObject = '[SpzBeTagesplan_Dat_D]'
				SET @SQL = 'ALTER TABLE ['+@TableName+'] ADD CONSTRAINT DF_'+@TableName+'_'+@ColumnName+' DEFAULT convert(datetime,convert(varchar,getdate(),1)) FOR ['+@ColumnName+'] '

			ELSE IF @DefaultObject IN ('RingBez_TageD_D')
				SET @SQL = 'ALTER TABLE ['+@TableName+'] ADD CONSTRAINT DF_'+@TableName+'_'+@ColumnName+' DEFAULT 21 FOR ['+@ColumnName+'] '

			ELSE IF @DefaultObject IN ('PlanSpalte_VsPro_D')
				SET @SQL = 'ALTER TABLE ['+@TableName+'] ADD CONSTRAINT DF_'+@TableName+'_'+@ColumnName+' DEFAULT 3 FOR ['+@ColumnName+'] '

			ELSE IF @DefaultObject IN ('AdressPlan_Geschlecht_D', 'AdressPlan_Gast_D')
				SET @SQL = 'ALTER TABLE ['+@TableName+'] ADD CONSTRAINT DF_'+@TableName+'_'+@ColumnName+' DEFAULT 2 FOR ['+@ColumnName+'] '

			ELSE
				SET @SQL = ''

			IF @SQL <> ''
			BEGIN
				
				PRINT('Creating default constraint DF_'+@TableName+'_'+@ColumnName+'...')

				IF @debug = 1
					PRINT @SQL 

				EXEC(@SQL)
			END
		END TRY
		
		BEGIN CATCH
			PRINT 'Failed on table: '+@TableName+' Column: '+@ColumnName
			
			select @error = ERROR_NUMBER(), @line = ERROR_LINE(), @severity = ERROR_SEVERITY(), @state = ERROR_STATE(),
			       @procedure = ERROR_PROCEDURE(), @message = ERROR_MESSAGE(),@xstate = XACT_STATE();
			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 gibt,
			-- diese rückgängig machen,
			-- da sonst folgefehler auftreten können
			-- tritt bei tests auf sql 2008 auf
			IF @xstate = -1 BEGIN
				PRINT('		Rolling back open transaction...')
				ROLLBACK;
			END
		END CATCH

		SET @I = @I + 1
		SELECT @RowID = Number, @TableName = TableName, @ColumnName = ColumnName, @DefaultObject = DefaultObject FROM @FixList WHERE Number = @I
		
		IF @@ROWCOUNT = 0
			BREAK
	END

	-- delete defaults
	DECLARE @cnt INT
	DECLARE @defaultName VARCHAR(50)

	SELECT @i = MIN(id) - 1, @cnt = MAX(id) FROM @defaultNames

	WHILE @i < @cnt
	BEGIN
		SELECT @i = @i + 1
		SELECT @defaultName = defaultName FROM @defaultNames WHERE id = @i
		SET @SQL = 'DROP DEFAULT [dbo].[' + @defaultName + ']'
	
		PRINT('Dropping default '+@defaultName+'...')

		BEGIN TRY
			IF @debug = 1
				PRINT @SQL

			EXEC (@SQL)
		END TRY
		BEGIN CATCH
			PRINT 'Failed for: '+@defaultName

			select @error = ERROR_NUMBER(), @line = ERROR_LINE(), @severity = ERROR_SEVERITY(), @state = ERROR_STATE(),
			       @procedure = ERROR_PROCEDURE(), @message = ERROR_MESSAGE(),@xstate = XACT_STATE();
			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 gibt,
			-- diese rückgängig machen,
			-- da sonst folgefehler auftreten können
			-- tritt bei tests auf sql 2008 auf
			IF @xstate = -1 BEGIN
				PRINT('		Rolling back open transaction...')
				ROLLBACK;
			END
		END CATCH
	END
END
GO
--#endregion

--#region SH 2018-01-26 Default Constraints für PersNr1-4 bei BesetzungStdSoliTabelle entfernen
IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_BesetzungStdSoliTabelle_PersNr1')
BEGIN  
	PRINT('Dropping constraint DF_BesetzungStdSoliTabelle_PersNr1...')
	ALTER TABLE [dbo].[BesetzungStdSoliTabelle] DROP CONSTRAINT [DF_BesetzungStdSoliTabelle_PersNr1]
END
GO

IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_BesetzungStdSoliTabelle_PersNr2')
BEGIN  
	PRINT('Dropping constraint DF_BesetzungStdSoliTabelle_PersNr2...')
	ALTER TABLE [dbo].[BesetzungStdSoliTabelle] DROP CONSTRAINT [DF_BesetzungStdSoliTabelle_PersNr2]
END
GO

IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_BesetzungStdSoliTabelle_PersNr3')
BEGIN  
	PRINT('Dropping constraint DF_BesetzungStdSoliTabelle_PersNr3...')
	ALTER TABLE [dbo].[BesetzungStdSoliTabelle] DROP CONSTRAINT [DF_BesetzungStdSoliTabelle_PersNr3]
END
GO

IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_BesetzungStdSoliTabelle_PersNr4')
BEGIN  
	PRINT('Dropping constraint DF_BesetzungStdSoliTabelle_PersNr4...')
	ALTER TABLE [dbo].[BesetzungStdSoliTabelle] DROP CONSTRAINT [DF_BesetzungStdSoliTabelle_PersNr4]
END
GO

--#endregion 

--#region TK 20180130 veraltete Spalten löschen
exec dropcolumn 'PersoParameter', 'Ueberstd'
exec dropcolumn 'PersoParameter', 'UeberStdAb'
exec dropcolumn 'PersoParameter', 'MehrAzBis'
exec dropcolumn 'PersoParameter', 'OvertimePremiumIsFixValue'
exec dropcolumn 'PersoParameter', 'Garantiestunden'
exec dropcolumn 'Settings', 'SettingsTS'
exec dropcolumn 'BesetzungStd', 'BesetzungStdTS'
exec dropcolumn 'Status', 'ImTagesplan'
exec dropcolumn 'SpielzeitTabelle', 'SpielzeitTS'
exec dropcolumn 'Sparte', 'SparteTS'
exec dropcolumn 'AufführgDetails', 'AufführgDetailsTS'
exec dropcolumn 'AufR', 'AufRTS'
exec dropcolumn 'FahrplanSparten', 'FahrplanSpartenTS'
exec dropcolumn 'AufführgDetails', 'AufführgDetailsTS'
exec dropcolumn 'BesRepertoire', 'BesRepertoireTS'
exec dropcolumn 'FahrplanGruppen', 'FahrplanGruppenTS'
exec dropcolumn 'Feiertage', 'FeiertageTS'
exec dropcolumn 'RepArt', 'RepArtTS'
exec dropcolumn 'Ring', 'RingTS'
exec dropcolumn 'RingBez', 'RepArtTS'
exec dropcolumn 'RepArt', 'RingBezTS'
exec dropcolumn 'KenntnisDel', 'KenntnisDelTS'
exec dropcolumn 'Kosten', 'KostenTS'
exec dropcolumn 'Kosten_Aufführg', 'Kosten_AufführgTS'
exec dropcolumn 'Kosten_Stück', 'Kosten_StückTS'
exec dropcolumn 'Land', 'LandTS'
exec dropcolumn 'PersAdresse', 'PersAdresseTS'
exec dropcolumn 'PersAgentur', 'PersAgenturTS'
exec dropcolumn 'ZR', 'ZRTS'
exec dropcolumn 'ZrAbschnitte', 'ZrAbschnitteTS'
exec dropcolumn 'Zulagen', 'ZulagenTS'
exec dropcolumn 'PersZusatzDaten', 'PersZusatzDatenTS'
exec dropcolumn 'PersZusatzDatenTyp', 'PersZusatzDatenTypTS'
exec dropcolumn 'PersZusatzDatenTyp', 'Typ'
exec dropcolumn 'PersoParameter', 'MonatsAbrechnung'
exec dropcolumn 'PersoParameter', 'MonatsAzProz'
exec dropcolumn 'PersoParameter', 'AzvAb'
exec dropcolumn 'PersoParameter', 'Art'
exec dropcolumn 'PersoParameter', 'UrlKrkTag'
exec dropcolumn 'PersoParameter', 'Bereitschaftsdienst'
exec dropcolumn 'PersoParameter', 'RID2'
exec dropcolumn 'PersoParameter', 'VertragsNr'
exec dropcolumn 'PersoParameter', 'PAUSE1'
exec dropcolumn 'PersoParameter', 'AZPAUSE1'
exec dropcolumn 'PersoParameter', 'Pause2'
exec dropcolumn 'PersoParameter', 'AzPause2'
exec dropcolumn 'PersoParameter', 'Pause3AfterMinutes'
exec dropcolumn 'PersoParameter', 'Pause3DurationMinutes'
exec dropcolumn 'PersoParameter', 'TotalCastShiftsPerWeek'
exec dropcolumn 'PersoParameter', 'PerformanceCastShiftsPerWeek'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_StückeDetails_AbrechSparte') AND type = 'F') ALTER TABLE dbo.StückeDetails	DROP CONSTRAINT FK_StückeDetails_AbrechSparte
exec dropcolumn 'StückeDetails', 'AbrechSparteNr'
exec dropcolumn 'AufführgDetails', 'Erlöse'
exec dropcolumn 'BesetzungStd', 'RolleMann'
exec dropcolumn 'BesetzungStd', 'RolleFrau'
exec dropcolumn 'BesetzungStdSoliTabelle', 'Fee'
exec dropcolumn 'BesetzungStdSoliTabelle', 'EnsembleCount'
exec dropcolumn 'BesetzungStdSoliTabelle', 'FeeNote'
exec dropcolumn 'BesetzungStdSoliTabelle', 'OvernightFee'
exec dropcolumn 'BesetzungStdSoliTabelle', 'BesetzungStdSoliTS'
exec dropcolumn 'UserPw', 'Inactive'
exec dropcolumn 'Vorlagen', 'SpeicherName'

exec dropcolumn 'XHDelAufführg', 'XHCount'
exec dropcolumn 'XHDelAufführg', 'ZuAuffNr'
exec dropcolumn 'XHDelAufführg', 'Doppel'
exec dropcolumn 'XHDelAufführg', 'DiplaDru'
exec dropcolumn 'XHDelAufführg', 'VonZeit'
exec dropcolumn 'XHDelAufführg', 'pl'
exec dropcolumn 'XHDelAufführg', 'Gesperrt'

exec dropcolumn 'ZrAbschnitte', 'FettA'
exec dropcolumn 'ZrAbschnitte', 'FettB'

exec dropcolumn 'ZrAbschnitte', 'SGA'
exec dropcolumn 'ZrAbschnitte', 'SGB'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Module]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) DROP TABLE Module
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.AbrechSparte') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)DROP TABLE AbrechSparte
GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.AbBesetzungStd') AND type = 'V')
BEGIN
	PRINT('Dropping view AbBesetzungStd...')
	DROP VIEW AbBesetzungStd
END
GO

--#endregion

--#region TK 20180201 PersZusatzDaten
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersZusatzDaten_PersH_PersNr') AND type = 'F') ALTER TABLE dbo.PersZusatzDaten	DROP CONSTRAINT FK_PersZusatzDaten_PersH_PersNr
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersZusatzDate_PersZusatzDate') AND type = 'F') ALTER TABLE dbo.PersZusatzDaten	DROP CONSTRAINT FK_PersZusatzDate_PersZusatzDate
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersZusatzDaten_PersZusatzDatenTyp_PersZDTypID') AND type = 'F') ALTER TABLE dbo.PersZusatzDaten	DROP CONSTRAINT FK_PersZusatzDaten_PersZusatzDatenTyp_PersZDTypID

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersZusatzDaten_Persons') AND type = 'F') 
BEGIN
	Print ('PersZusatzDaten Delete NUll')
	DELETE FROM PersZusatzDaten WHERE PersNr IS NULL
	DELETE FROM PersZusatzDaten WHERE PersZDTypID IS NULL

	Print ('PersZusatzDaten drop index')
	ALTER TABLE dbo.PersZusatzDaten DROP CONSTRAINT PRIMARYKEY_PersZusatzDaten
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersZusatzDaten') AND o.Name = 'PersNr') DROP INDEX  PersZusatzDaten.PersNr
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersZusatzDaten') AND o.Name = 'iPersZDTypID') DROP INDEX  PersZusatzDaten.iPersZDTypID

	Print ('PersZusatzDaten alter column PersNr, PersZDTypID')
	ALTER TABLE PersZusatzDaten ALTER COLUMN PersNr INT NOT NULL
	ALTER TABLE PersZusatzDaten ALTER COLUMN PersZDTypID INT NOT NULL

	Print ('PersZusatzDaten create IX_PersZusatzDaten_Persnr')
	CREATE CLUSTERED INDEX IX_PersZusatzDaten_Persnr ON PersZusatzDaten (PersNr) ON [PRIMARY]

	Print ('PersZusatzDaten create PK_PersZusatzDatenId')
	ALTER TABLE dbo.PersZusatzDaten ADD CONSTRAINT PK_PersZusatzDatenId PRIMARY KEY (PersZusatzDatenID) ON [PRIMARY]

	Print ('PersZusatzDaten create IX_PersZDTypID')
	CREATE INDEX IX_PersZDTypId ON PersZusatzDaten (PersZDTypID)
	
	Print ('PersZusatzDaten create FK_PersZusatzDaten_Persons')
	ALTER TABLE dbo.PersZusatzDaten  WITH CHECK ADD  CONSTRAINT FK_PersZusatzDaten_Persons FOREIGN KEY(PersNr)
		REFERENCES dbo.PersH (PersNr) ON DELETE CASCADE
	ALTER TABLE dbo.PersZusatzDaten CHECK CONSTRAINT FK_PersZusatzDaten_Persons

	Print ('PersZusatzDaten create FK_PersZusatzDaten_PersZusatzDatenTyp')
	ALTER TABLE dbo.PersZusatzDaten  WITH CHECK ADD  CONSTRAINT FK_PersZusatzDaten_PersZusatzDatenTyp FOREIGN KEY(PersZDTypID)
		REFERENCES dbo.PersZusatzDatenTyp (PersZDTypId) ON DELETE CASCADE
	ALTER TABLE dbo.PersZusatzDaten CHECK CONSTRAINT FK_PersZusatzDaten_PersZusatzDatenTyp
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects so WHERE so.id = OBJECT_ID(N'dbo.DF_PersZusatzDaten_Sort'))
BEGIN
	Print ('PersZusatzDatenTyp  alter column sort')
	UPDATE PersZusatzDatenTyp SET Sort = 0 WHERE Sort IS NULL
	ALTER TABLE PersZusatzDatenTyp ALTER COLUMN Sort INT NOT NULL
	ALTER TABLE dbo.PersZusatzDatenTyp ADD CONSTRAINT DF_PersZusatzDaten_Sort DEFAULT 0 FOR Sort

	UPDATE [dbo].[VertragsVorlagen] SET CastWorkingHoursSettings =  REPLACE(CONVERT(VARCHAR(MAX), CastWorkingHoursSettings), 'Categotys','Categories') WHERE NOT CastWorkingHoursSettings IS NULL
 END
--#endregion 

--#region Activity ResourceObject DH 201801018
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Activities_ResourceObjects]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
Print 'Table Activities_ResourceObjects';
	CREATE TABLE dbo.Activities_ResourceObjects(
		ActivitiesResourceObjectsId INT IDENTITY(1,1) NOT NULL,
		ActivityId INT NOT NULL,
		ResourceObjectId INT NOT NULL,
		StartOffset INT NOT NULL CONSTRAINT DF_Activities_ResourceObjects_StartOffset DEFAULT 0,
		EndOffset INT NOT NULL CONSTRAINT DF_Activities_ResourceObjects_EndOffset DEFAULT 0,
		Note VARCHAR(1000) SPARSE NULL ,		
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_Activities_ResourceObjects PRIMARY KEY NONCLUSTERED (ActivitiesResourceObjectsId) ON [PRIMARY],
		CONSTRAINT FK_Activities_ResourceObjects_Activity FOREIGN KEY(ActivityId) REFERENCES AufführgTabelle (Auffnr) ON DELETE CASCADE,
		CONSTRAINT FK_Activities_ResourceObjects_ResourceObject FOREIGN KEY(ResourceObjectId) REFERENCES ResourceObjects (ResourceObjectId) ON DELETE CASCADE,
	) ON [PRIMARY];

	CREATE UNIQUE NONCLUSTERED INDEX IX_Activities_ResourceObjects_ActivityId_ResourceObjectId ON Activities_ResourceObjects (ActivityId, ResourceObjectId) ON [PRIMARY];
	CREATE CLUSTERED INDEX IX_Activities_ResourceObjects_ActivityId ON Activities_ResourceObjects (ActivityId) ON [PRIMARY];
END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbActivitiesResourceObjects')) DROP VIEW dbo.[AbActivitiesResourceObjects]
GO
CREATE 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 UserGruppe AS ug ON r.OwnerId = ug.GruppeId
		INNER JOIN UserPw AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 16 
	);
GO
GRANT SELECT ON [AbActivitiesResourceObjects] TO PUBLIC;

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbActivitiesResourceObjects_Update')) DROP VIEW dbo.[AbActivitiesResourceObjects_Update];
GO
CREATE 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 UserGruppe AS ug ON r.OwnerId = ug.GruppeId
		INNER JOIN UserPw AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 16 AND Ug.OptionsFlag &1=1)
		WITH CHECK OPTION;
GO
	GRANT SELECT,DELETE,UPDATE,INSERT ON [AbActivitiesResourceObjects_Update] TO PUBLIC;
GO
--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 AuffNr= @ActivityId)
		BEGIN
				SELECT 1 AS Attribut, 'No Permission' AS MSG
			END
		ELSE
	BEGIN
			
		DELETE FROM CastCredits WHERE ServiceCastId IN (SELECT Id FROM BesetzungTabelle WHERE Auffnr = @activityId)
		DELETE FROM CastCredits WHERE ReplacementCastId IN (SELECT Id FROM BesetzungTabelle WHERE Auffnr = @activityId)
		DELETE FROM CastBonus WHERE CastBonus.CastId IN (SELECT Id FROM BesetzungTabelle WHERE Auffnr = @activityId)
		DELETE FROM CashCommandPos_Cast WHERE CastId IN (SELECT Id FROM BesetzungTabelle WHERE Auffnr = @activityId)
		UPDATE ContractDates SET  CastId = NULL WHERE CastId IN (SELECT Id FROM BesetzungTabelle WHERE Auffnr = @activityId)
		DELETE FROM BesetzungTabelle WHERE Auffnr = @activityId
		DELETE FROM ActivityScenes WHERE ActivityId = @activityId
		DELETE FROM AuffDienstplanArten WHERE Auffnr = @activityId
		DELETE FROM AuffTechAufgabe WHERE Auffnr = @activityId
		DELETE FROM Kosten_Aufführg WHERE Auffnr = @activityId
		DELETE FROM PresseText WHERE Auffnr = @activityId
		DELETE FROM AufführgDetails WHERE Auffnr = @activityId
		DELETE FROM Fahrplan WHERE AuffNr = @ActivityId
		DELETE FROM CostUnitWorkingTime WHERE ActivityId = @activityId
		DELETE FROM ActivityScenes WHERE ActivityId = @activityId
		UPDATE AufführgTabelle SET ZuAuffNr = NULL WHERE ZuAuffNr = @ActivityId
		DELETE FROM Activities_ResourceObjects WHERE ActivityId = @ActivityId
	END	
END	
GO
--#endregion Activity ResourceObject

--#region SH 2018-02-06 Löschen von Solibesetzungen für Personen mit ID 0 (nachtrag zum constraint löschen)
PRINT('Deleting Basic cast soli entries for person id 0...')
UPDATE BesetzungStdSoliTabelle SET PersNr1 = NULL WHERE  PersNr1 = 0
UPDATE BesetzungStdSoliTabelle SET PersNr2 = NULL WHERE  PersNr2 = 0
UPDATE BesetzungStdSoliTabelle SET PersNr3 = NULL WHERE  PersNr3 = 0
UPDATE BesetzungStdSoliTabelle SET PersNr4 = NULL WHERE  PersNr4 = 0
GO
--#endregion

--#region TK 20180201
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonNotesPersons') AND type = 'F') ALTER TABLE dbo.PersonalNotizen DROP CONSTRAINT FK_PersonNotesPersons
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonalNotizen_PersH_PersNr') AND type = 'F') ALTER TABLE dbo.PersonalNotizen DROP CONSTRAINT FK_PersonalNotizen_PersH_PersNr
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.PersonalNoteTypPersonNote') AND type = 'F') ALTER TABLE dbo.PersonalNotizen DROP CONSTRAINT PersonalNoteTypPersonNote
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonalNotes_Groups') AND type = 'F') ALTER TABLE dbo.PersonalNotizen DROP CONSTRAINT FK_PersonalNotes_Groups
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonNotes_OwnerGroups') AND type = 'F') 
BEGIN
	UPDATE PersonalNotizen SET Besitzer = 1 WHERE Besitzer NOT IN (SELECT GruppeId FROM Gruppe)
		Print ('create FK_PersonNotes_OwnerGroups')
	ALTER TABLE dbo.PersonalNotizen WITH CHECK ADD  CONSTRAINT FK_PersonNotes_OwnerGroups FOREIGN KEY(Besitzer)
		REFERENCES dbo.Gruppe (GruppeId) ON DELETE CASCADE
	ALTER TABLE dbo.PersonalNotizen CHECK CONSTRAINT FK_PersonNotes_OwnerGroups
END
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonNotes_PersonNoteTypes') AND type = 'F') 
BEGIN
	UPDATE PersonalNotizen SET NotizTypID = 1 WHERE NotizTypID NOT IN (SELECT NotizTypID FROM PersonalNotizenTyp)
		Print ('create FK_PersonNotes_PersonNoteTypes')
	ALTER TABLE dbo.PersonalNotizen WITH CHECK ADD  CONSTRAINT FK_PersonNotes_PersonNoteTypes FOREIGN KEY(NotizTypID)
		REFERENCES dbo.PersonalNotizenTyp (NotizTypID) ON DELETE CASCADE
	ALTER TABLE dbo.PersonalNotizen CHECK CONSTRAINT FK_PersonNotes_PersonNoteTypes

	ALTER TABLE dbo.PersonalNotizen DROP CONSTRAINT PRIMARYKEY_PersonalNotizen
	IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersonalNotizen') AND o.Name = 'IX_PersonNotes_PersonId') DROP INDEX  PersonalNotizen.IX_PersonNotes_PersonId
	Print ('PersZusatzDaten create IX_PersonNotes_PersonId')
	CREATE CLUSTERED INDEX IX_PersonNotes_PersonId ON PersonalNotizen (PersNr) ON [PRIMARY]

	Print ('PersZusatzDaten create PK_PersonalNotizenID')
	ALTER TABLE dbo.PersonalNotizen ADD CONSTRAINT PK_PersonNoteId PRIMARY KEY (PersonalNotizenID) ON [PRIMARY]

END
GO
IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersonalDetails') AND o.Name = 'aaaaaPersonalDetails_PK')
BEGIN
	Print ('PersZusatzDaten create PK_PersonId')
	ALTER TABLE dbo.PersonalDetails DROP CONSTRAINT aaaaaPersonalDetails_PK
	ALTER TABLE dbo.PersonalDetails ADD CONSTRAINT PK_PersonId PRIMARY KEY (PNR) ON [PRIMARY]
END
GO

exec dropcolumn 'TagSparteSort', 'TagSparteSortTS'
exec dropcolumn 'Preise', 'Alt'
exec dropcolumn 'Preise', 'PreiseTS'
exec dropcolumn 'PersonalNotizen', 'UserModified'
exec dropcolumn 'PersonalNotizen', 'PersonalNotizenTS'
exec dropcolumn 'PersonalNotizen', 'Datum'
exec dropcolumn 'VertragRolle', 'ProbVorstAnteilAnz'
--#endregion

--#region TK 20180220 Arbeitszeitmodelle an Vertrag
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ContractId' and o.id = OBJECT_ID(N'dbo.ContractPersoWorkingCycles'))
	BEGIN
		ALTER TABLE dbo.ContractPersoWorkingCycles ADD  ContractId INT NULL
		EXEC ('UPDATE ContractPersoWorkingCycles SET ContractId =   VertragPerso.VertragsNr  FROM ContractPersoWorkingCycles INNER JOIN VertragPerso ON ContractPersoWorkingCycles.ContractPersoId = VertragPerso.ContractPersoId WHERE VertragPerso.IsMainWorkArea = 1')
		EXEC ('DELETE ContractPersoWorkingCycles WHERE ContractId IS NULL')
		IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ContractPersoWorkingCycles_VertragPerso') AND type = 'F') ALTER TABLE dbo.ContractPersoWorkingCycles DROP CONSTRAINT FK_ContractPersoWorkingCycles_VertragPerso
		ALTER TABLE dbo.ContractPersoWorkingCycles ALTER COLUMN  ContractId INT NOT NULL
		ALTER TABLE dbo.ContractPersoWorkingCycles DROP CONSTRAINT PK_ContractPersoWorkingCycleId

		CREATE CLUSTERED INDEX IX_ContractPersoWorkingCycles_Contractd ON ContractPersoWorkingCycles (ContractId ) ON [PRIMARY]
			Print ('PersZusatzDaten create PK_ContractPersoWorkingCycleId')
		ALTER TABLE dbo.ContractPersoWorkingCycles ADD CONSTRAINT PK_ContractPersoWorkingCycleId PRIMARY KEY (ContractPersoWorkingCycleId) ON [PRIMARY]
				Print ('create FK_ContractPersoWorkingCycles_Contract')
		ALTER TABLE dbo.ContractPersoWorkingCycles WITH CHECK ADD  CONSTRAINT FK_ContractPersoWorkingCycles_Contract FOREIGN KEY(ContractId)
			REFERENCES dbo.Vertrag (VertragsNr) ON DELETE CASCADE
		ALTER TABLE dbo.ContractPersoWorkingCycles CHECK CONSTRAINT FK_ContractPersoWorkingCycles_Contract
	ALTER TABLE ContractPersoWorkingCycles DROP COLUMN ContractPersoId


	END
GO
	ALTER VIEW [dbo].[AbContractPersoWorkingCycles_Update]
AS
	SELECT * FROM ContractPersoWorkingCycles WHERE ContractId IN (
		SELECT Vertrag.VertragsNr FROM UserGruppe 
		INNER JOIN	UserPW		 ON UserGruppe.Userid = UserPW.Userid 
		INNER JOIN	Vertrag		 ON Vertrag.ModulGruppeID = UserGruppe.GruppeID 
		WHERE Username = CURRENT_USER  AND BerechtigungsbereichID IN (1,5) AND UserGruppe.Schreiben = 1) 
WITH CHECK OPTION
GO
--#endregion

--#region TK 20180220 Contract SP
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetContractsInternal')) DROP PROCEDURE dbo.GetContractsInternal 
GO
CREATE 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.Vertragsnr, v.ModulGruppeID   '
		END	
	ELSE
		BEGIN
			SET @SQLQuery = 'SELECT *'
		END

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

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

	IF (@joins&2 = 2) 
		SET @SQLQuery = @SQLQuery + 'INNER JOIN Gruppe AS g ON v.ModulGruppeId = g.GruppeId '

	IF (@joins&4 = 4) 
		SET @SQLQuery = @SQLQuery + 'INNER JOIN VertragsVorlagen AS vv ON vv.VorlagenID = v.VorlagenId '

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

	IF (@joins&16 = 16) 
		SET @SQLQuery = @SQLQuery + 'INNER JOIN PersonalDetails pd ON v.PersNr = pd.pnr '


	DECLARE @securetyWhere AS NVARCHAR(MAX)
	SET @securetyWhere = ' EXISTS (SELECT * FROM UserGruppe WHERE UserId = ' + CAST(@userId AS VARCHAR(MAX)) +' AND v.ModulGruppeId = UserGruppe.GruppeId AND BerechtigungsbereichId IN (1, 5))'
	IF (@orContact <> 0)	SET @securetyWhere = '(' + @securetyWhere + ' OR v.PersNr = ' + CAST(@userId 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 Vertrag AS V INNER JOIN #Contract ON v.VertragsNr = #Contract.ContractId 
	END
	ELSE
	BEGIN
		RETURN 
	END

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


	IF (@include&4 = 4) 
	SELECT NULL AS [#4],
		vr.VertragsNr, vr.RolleId, vr.VRId, 
		vr.vrVon, vr.vrBis,
		CASE WHEN u.OptionsFlag&1 <> 1 THEN -1 ELSE vr.ProbBezahltWert END AS ProbBezahltWert,
		CASE WHEN u.OptionsFlag&1 <> 1 THEN -1 ELSE vr.Honorar END AS Honorar,
		CASE WHEN u.OptionsFlag&1 <> 1 THEN -1 ELSE vr.ExtraFee END AS ExtraFee,
		CASE WHEN u.OptionsFlag&1 <> 1 THEN -1 ELSE vr.SalaryLevelId END AS SalaryLevelId,
		CASE WHEN u.OptionsFlag&1 <> 1 THEN -1 ELSE vr.CoverFee  END AS CoverFee,
		CASE WHEN u.OptionsFlag&1 <> 1 THEN NULL ELSE vr.FeeComment END AS FeeComment,
		CASE WHEN u.OptionsFlag&1 <> 1 THEN NULL ELSE vr.RehearsalFeeComment END AS RehearsalFeeComment,
		CASE WHEN u.OptionsFlag&1 <> 1 THEN -1 ELSE vr.DayFee END AS DayFee,
		CASE WHEN u.OptionsFlag&1 <> 1 THEN -1 ELSE vr.TravelExpensesFlat  END AS TravelExpensesFlat,
		CASE WHEN u.OptionsFlag&1 <> 1 THEN -1 ELSE vr.OvernightExpensesFlat END AS OvernightExpensesFlat,
		vr.VorstAnz, vr.AbrechnungVs, vr.VorstAnzMin, vr.VorstAnzVortrag, vr.ProbUnbez, vr.AbrechnungProben, vr.ProbBezahltAnz,
		vr.LM, vr.UM, vr.LC, vr.UC, 
		vr.ProductionId, vr.CostUnitId,
		vr.RehearsalsCompensatedByPerformance
	FROM  
		VertragRolle AS vr 
				INNER JOIN #Contract ON vr.VertragsNr = #Contract.ContractId
				INNER JOIN UserGruppe AS u ON u.UserId = @userId AND #Contract.OwnerGroupId = u.GruppeId AND u.BerechtigungsbereichId = 1

	IF (@include&8 = 8) 
		SELECT NULL AS [#8], VertragDetails.* 
		FROM VertragDetails 
			INNER JOIN #Contract ON VertragDetails.VertragsNr = #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.PersContractId = #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], ContractPersoWorkingCycles.* 
		FROM ContractPersoWorkingCycles
			INNER JOIN #Contract ON ContractPersoWorkingCycles.ContractId = #Contract.ContractId

	DROP TABLE #Contract
END
GO

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetContracts')) DROP PROCEDURE dbo.GetContracts 
GO
CREATE 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 = persNr FROM UserPW 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
GRANT EXECUTE ON GetContracts TO public
GO

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

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'End' and o.id = OBJECT_ID(N'dbo.VertragPerso') and c.xtype = 40)
BEGIN
	PRINT ('VertragPerso Start/end')
	ALTER TABLE VertragPerso ALTER COLUMN [End] DATE  NULL
	ALTER TABLE VertragPerso ALTER COLUMN [Start] DATE  NULL
END
GO

IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.VertragPerso') AND o.Name = 'IX_ContractPerso_ABId_IsMainWorkArea')
	CREATE INDEX IX_ContractPerso_ABId_IsMainWorkArea ON dbo.VertragPerso (IsMainWorkArea,ABId) INCLUDE (VertragsNr)
GO

IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.VertragPerso') AND o.Name = 'IX_ContractPerso_ABId')
	CREATE INDEX IX_ContractPerso_ABId ON dbo.VertragPerso (ABId) INCLUDE (VertragsNr)
GO

IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.Vertrag') AND o.Name = 'IX_Contract_IsCanceled_Start_End')
	CREATE NONCLUSTERED INDEX IX_Contract_IsCanceled_Start_End ON dbo.Vertrag (IsCanceled,vVon,vBis)INCLUDE (VertragsNr,ModulGruppeID)
GO

--#endregion

--#region SH 2018-02-16 Neue Spalte für Pausen im Dienstplaneintrag
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Dienstplan') AND [name] = 'WorkBreakSettings')
BEGIN
	PRINT('Adding column Dienstplan.WorkBreakSettings ...')
	ALTER TABLE dbo.Dienstplan ADD WorkBreakSettings XML SPARSE  NULL
END
GO
--#endregion

--#region SH 2018-02-18 Neue Spalte für Ausbezahlte Arbeitszeit im Dienstplaneintrag
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Dienstplan') AND [name] = 'PaidOffWorkingMinutes')
BEGIN
	PRINT('Adding column Dienstplan.PaidOffWorkingMinutes ...')
	ALTER TABLE dbo.Dienstplan ADD PaidOffWorkingMinutes INT NOT NULL CONSTRAINT DF_DutyRoster_PaidOffWorkingMinutes DEFAULT 0
END
GO
--#endregion

--#region tk 20180319 Category 
IF NOT EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Category' and o.id = OBJECT_ID(N'dbo.AuffTypen'))
BEGIN
	PRINT 'Add Category'
	ALTER TABLE AuffTypen ADD Category SMALLINT NULL
	EXEC ('UPDATE 	 AuffTypen SET Category =

	CASE WHEN KatNr = 0 THEN 
			CASE WHEN tsAuffTypBasisID = 560 THEN 2010 WHEN tsAuffTypBasisID = 550 THEN 2020 ELSE 2000 END 
		WHEN KatNr = 1 THEN
			CASE WHEN Merkmal = 1 THEN 900 --Endprobe
					WHEN Merkmal = 2  THEN 500 -- Sonstige
					WHEN Merkmal = 3  THEN
						CASE WHEN tsAuffTypBasisID = 100 THEN 410 --Bau
							WHEN tsAuffTypBasisID = 115 THEN 810  --End
							WHEN tsAuffTypBasisID = 120 THEN 420  --TE
							WHEN tsAuffTypBasisID = 450 THEN 910  --
							ELSE 400 END 
					 --Technik
					ELSE 800 END	--Normal
		WHEN KatNr = 5 THEN 100 --Soliprobe
		WHEN KatNr = 3 THEN 200 -- technische Aufgabe
		WHEN KatNr = -1 THEN 1420 --Martinee
		WHEN KatNr = -3 THEN 1410 --Einführung
		WHEN KatNr = -4 THEN 1900 --sonstige öffentlicher Typ (kein Vst.)
		WHEN KatNr = -10 THEN 1300 --öffentliche Probe
		ELSE 0		-- 9 Vertragstermin,99 Tagesgebundene Aufgabe (thea.works)
	END	
	FROM AuffTypen')
	ALTER TABLE AuffTypen ALTER COLUMN Category SMALLINT NOT NULL
	CREATE INDEX IX_ActivityTypes_Category ON AuffTypen (Category)
END
GO

IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.AuffTypen') AND o.Name = 'IX_KatNr') DROP INDEX IX_KatNr ON dbo.AuffTypen
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'dbo.DF_Aufftypen_katnr'))	ALTER TABLE AuffTypen DROP CONSTRAINT DF_Aufftypen_katnr
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'dbo.DF__Aufftypen__tsAuf__23550063'))	ALTER TABLE AuffTypen DROP CONSTRAINT DF__Aufftypen__tsAuf__23550063
GO
 
IF EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'KatNr' AND isComputed = 0 AND o.id = OBJECT_ID(N'dbo.AuffTypen'))
BEGIN
	exec dropcolumn 'AuffTypen', 'KatNr'
	exec dropcolumn 'AuffTypen', 'merkmal'
	exec dropcolumn 'AuffTypen', 'tsAuffTypBasisID'

	UPDATE AuffTypen SET NoOverlap = 0 WHERE NoOverlap IS NULL
	ALTER TABLE AuffTypen ALTER COLUMN NoOverlap BIT NOT NULL
	ALTER TABLE AuffTypen ADD CONSTRAINT DF_ActivityCategory_NoOverlap DEFAULT 0 FOR NoOverlap 

	UPDATE AuffTypen SET CountDownTyp = 0 WHERE CountDownTyp IS NULL
	ALTER TABLE AuffTypen ALTER COLUMN CountDownTyp BIT NOT NULL
	
	exec DropDefaultConstraint 'AuffTypen', 'LfdNr'

	UPDATE AuffTypen SET LfdNr = 0 WHERE LfdNr IS NULL
	ALTER TABLE AuffTypen ALTER COLUMN LfdNr BIT NOT NULL
	ALTER TABLE AuffTypen ADD CONSTRAINT DF_ActivityCategory_ShowNumber DEFAULT 0 FOR LfdNr 
END
GO

IF NOT EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'KatNr' AND isComputed = 1 AND o.id = OBJECT_ID(N'dbo.AuffTypen'))
BEGIN
	PRINT 'UPDATE   Category'

	ALTER TABLE AuffTypen ADD KatNr AS    (CASE WHEN Category >= 2000 THEN 0
												WHEN Category >= 400 AND Category < 1000 THEN 1
												WHEN Category = 200  THEN 3
												WHEN Category = 100  THEN 5
												WHEN Category = 1420 THEN -1
												WHEN Category = 1410 THEN -3
												WHEN Category = 1900 THEN -4
												WHEN Category = 1300 THEN -10
												ELSE 99 END)
	--ALTER TABLE AuffTypen ADD Merkmal AS (CASE WHEN Category >= 400 AND Category < 500  THEN 3
	--											WHEN Category =  500 THEN 2
	--											WHEN Category >= 900 AND Category < 1000 THEN 1
	--											 ELSE 0 END)

	--ALTER TABLE AuffTypen ADD  TsAuffTypBasisID  AS (CASE WHEN Category = 410 THEN 100
	--														WHEN Category = 420  THEN 120
	--														WHEN Category = 810 THEN 115
	--														WHEN Category = 910 THEN 450
	--														WHEN Category = 2010 THEN 560
	--														WHEN Category = 2020 THEN 550	
	--														WHEN Category = 2000 THEN 500
	--											 ELSE 0 END)

	UPDATE [plan]  SET Settings.modify('insert <ActivityTypeCategories></ActivityTypeCategories> into (/ProductionPlanSettings)[1]')  
		WHERE planart = 99 AND NOT Settings IS NULL AND [plan].Settings.exist('/ProductionPlanSettings/BaseTypes/tsAuffTypBasis') = 1

	UPDATE [plan]  SET Settings.modify('insert <ActivityTypeCategory>Premiere</ActivityTypeCategory>  into (/ProductionPlanSettings/ActivityTypeCategories)[1]')  
		WHERE planart = 99 AND NOT Settings IS NULL AND [plan].Settings.exist('/ProductionPlanSettings/BaseTypes/tsAuffTypBasis[. = "Premiere"]') = 1
	UPDATE [plan]  SET Settings.modify('insert <ActivityTypeCategory>RevivalPerformance</ActivityTypeCategory>  into (/ProductionPlanSettings/ActivityTypeCategories)[1]')  
		WHERE planart = 99 AND NOT Settings IS NULL  AND [plan].Settings.exist('/ProductionPlanSettings/BaseTypes/tsAuffTypBasis[. = "Wiederaufnahme"]') = 1
	UPDATE [plan]  SET Settings.modify('insert <ActivityTypeCategory>Performance</ActivityTypeCategory>  into (/ProductionPlanSettings/ActivityTypeCategories)[1]')  
		WHERE planart = 99 AND NOT Settings IS NULL AND [plan].Settings.exist('/ProductionPlanSettings/BaseTypes/tsAuffTypBasis[. = "Vorstellung"]') = 1

	UPDATE  PlanSort  SET contentsettings =REPLACE(CONVERT(VARCHAR(MAX), contentsettings) ,'&lt;BaseCategories&gt;Premiere&lt;/BaseCategories&gt;','&lt;ActivityTypeCategories&gt;Premiere&lt;/ActivityTypeCategories&gt;')
		WHERE NOT contentpath IS NULL  AND CONVERT(VARCHAR(MAX), contentsettings) Like '%&lt;BaseCategories&gt;Premiere&lt;/BaseCategories&gt;%'

	UPDATE  PlanSort  SET contentsettings = REPLACE(CONVERT(VARCHAR(MAX), contentsettings) ,'&lt;BaseCategories&gt;RehearseStart&lt;/BaseCategories&gt;','&lt;ActivityTypeCategories&gt;RehearsalStart&lt;/ActivityTypeCategories&gt;')
		WHERE NOT contentpath IS NULL  AND CONVERT(VARCHAR(MAX), contentsettings) Like '%&lt;BaseCategories&gt;RehearseStart&lt;/BaseCategories&gt;%'
	
	UPDATE  PlanSort  SET contentsettings = REPLACE(CONVERT(VARCHAR(MAX), contentsettings) ,'&lt;BaseCategories&gt;Bauprobe&lt;/BaseCategories&gt;','&lt;ActivityTypeCategories&gt;BuildingRehearsal&lt;/ActivityTypeCategories&gt;')
		WHERE NOT contentpath IS NULL  AND CONVERT(VARCHAR(MAX), contentsettings) Like '%&lt;BaseCategories&gt;Bauprobe&lt;/BaseCategories&gt;%'
	
	UPDATE  PlanSort  SET contentsettings = REPLACE(CONVERT(VARCHAR(MAX), contentsettings) ,'&lt;BaseCategories&gt;TE&lt;/BaseCategories&gt;','&lt;ActivityTypeCategories&gt;TechnicalSetup&lt;/ActivityTypeCategories&gt;')
		WHERE NOT contentpath IS NULL  AND CONVERT(VARCHAR(MAX), contentsettings) Like '%&lt;BaseCategories&gt;TE&lt;/BaseCategories&gt;%'
	
	UPDATE  PlanSort  SET contentsettings = REPLACE(CONVERT(VARCHAR(MAX), contentsettings) ,'&lt;BaseCategories&gt;Wiederaufnahme&lt;/BaseCategories&gt;','&lt;ActivityTypeCategories&gt;RevivalPerformance&lt;/ActivityTypeCategories&gt;')
		WHERE NOT contentpath IS NULL  AND CONVERT(VARCHAR(MAX), contentsettings) Like '%&lt;BaseCategories&gt;Wiederaufnahme&lt;/BaseCategories&gt;%'

	UPDATE  PlanSort  SET contentsettings = REPLACE(CONVERT(VARCHAR(MAX), contentsettings) ,'&lt;SubCategories&gt;normal&lt;/SubCategories&gt;','&lt;ActivityTypeCategories&gt;Rehearsal&lt;/ActivityTypeCategories&gt;
 &lt;ActivityTypeCategories&gt;RehearsalStart&lt;/ActivityTypeCategories&gt;') 
		WHERE NOT contentpath IS NULL  AND CONVERT(VARCHAR(MAX), contentsettings) Like '%&lt;SubCategories&gt;normal&lt;/SubCategories&gt;%'

	UPDATE  PlanSort  SET contentsettings = REPLACE(CONVERT(VARCHAR(MAX), contentsettings) ,'&lt;SubCategories&gt;endRehearsal&lt;/SubCategories&gt;','&lt;ActivityTypeCategories&gt;EndRehearsal&lt;/ActivityTypeCategories&gt;
 &lt;ActivityTypeCategories&gt;GeneralRehearsal&lt;/ActivityTypeCategories&gt;') 
		WHERE NOT contentpath IS NULL  AND CONVERT(VARCHAR(MAX), contentsettings) Like '%&lt;SubCategories&gt;endRehearsal&lt;/SubCategories&gt;%'

		
	UPDATE  PlanSort  SET contentsettings = REPLACE(CONVERT(VARCHAR(MAX), contentsettings) ,'&lt;SubCategories&gt;miscRehearsal&lt;/SubCategories&gt;','&lt;ActivityTypeCategories&gt;MiscRehearsal&lt;/ActivityTypeCategories&gt;') 
		WHERE NOT contentpath IS NULL  AND CONVERT(VARCHAR(MAX), contentsettings) Like '%&lt;SubCategories&gt;miscRehearsal&lt;/SubCategories&gt;%'

	UPDATE  PlanSort  SET contentsettings = REPLACE(CONVERT(VARCHAR(MAX), contentsettings) ,'&lt;SubCategories&gt;technical&lt;/SubCategories&gt;','&lt;ActivityTypeCategories&gt;TechnicalRehearsal&lt;/ActivityTypeCategories&gt;
 &lt;ActivityTypeCategories&gt;BuildingRehearsal&lt;/ActivityTypeCategories&gt;
 &lt;ActivityTypeCategories&gt;TechnicalSetup&lt;/ActivityTypeCategories&gt;') 
		WHERE NOT contentpath IS NULL  AND CONVERT(VARCHAR(MAX), contentsettings) Like '%&lt;SubCategories&gt;technical&lt;/SubCategories&gt;%'
END
GO

IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActivityPerformanceNumbers')) DROP Function dbo.GetActivityPerformanceNumbers
GO
CREATE FUNCTION dbo.GetActivityPerformanceNumbers(@start DATE, @end DATE)
		RETURNS TABLE
		AS
			RETURN (SELECT Row_Number() OVER (PARTITION BY a.Snr, CASE WHEN [Status] <= 99 THEN 0 ELSE [Status] END ORDER BY Datum, UhrBeg) AS RowNum, AuffNr, Datum
					FROM AufführgTabelle AS A
						INNER JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art
					WHERE Category >= 2000 AND Datum BETWEEN @start AND @end AND  [Status] > 0)
GO
GRANT SELECT ON dbo.GetActivityPerformanceNumbers TO PUBLIC
GO

IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetActivityPerformanceNumbersAllSeasons'))	DROP Function dbo.GetActivityPerformanceNumbersAllSeasons
GO
CREATE FUNCTION dbo.GetActivityPerformanceNumbersAllSeasons(@start DATE, @end DATE)
		RETURNS TABLE
		AS
			RETURN (SELECT * FROM (SELECT Row_Number() OVER (PARTITION BY a.Snr ORDER BY Datum, UhrBeg)  + ISNULL(pd.AnzahlAuff, 0)  AS RowNum, AuffNr, Datum
					FROM AufführgTabelle AS A
						INNER JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art
						LEFT JOIN StückeDetails AS PD ON Pd.Snr = A.Snr
					WHERE  Category >= 2000 AND Datum <= @end AND  [Status] BETWEEN 0 AND 99 ) AS subA WHERE Datum BETWEEN @start AND @end)
GO
GRANT SELECT ON dbo.GetActivityPerformanceNumbersAllSeasons TO PUBLIC
GO

exec dropcolumn 'AuffTypen', 'MitChor'
exec dropcolumn 'AuffTypen', 'MitOrch'
exec dropcolumn 'AuffTypen', 'mitBallett'

IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.Aufftypen') AND o.Name = 'aaaaaAuffTypen_PK')
BEGIN
	Print ('Aufftypen create PK_ActivityCategory')
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_CountDowns_ActivityTyp') AND type = 'F') ALTER TABLE dbo.CountDown DROP CONSTRAINT FK_CountDowns_ActivityTyp
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ActivityTypeGroup_ActivityType') AND type = 'F') ALTER TABLE dbo.ActivityTypeGroups DROP CONSTRAINT FK_ActivityTypeGroup_ActivityType
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_ActivityTypeResourceTypes_ActivitieTypes') AND type = 'F') ALTER TABLE dbo.ActivityTypeResourceTypes DROP CONSTRAINT FK_ActivityTypeResourceTypes_ActivitieTypes
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_AufführgTabelle_Aufftypen') AND type = 'F') ALTER TABLE dbo.Aufführgtabelle DROP CONSTRAINT FK_AufführgTabelle_Aufftypen
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Aufführg_AuffTypen') AND type = 'F') ALTER TABLE dbo.Aufführgtabelle DROP CONSTRAINT FK_Aufführg_AuffTypen
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_RoleGroups_ActivityTypes_ActivityTypes') AND type = 'F') ALTER TABLE dbo.RoleGroups_ActivityTypes DROP CONSTRAINT FK_RoleGroups_ActivityTypes_ActivityTypes

	ALTER TABLE dbo.Aufftypen DROP CONSTRAINT aaaaaAuffTypen_PK
	ALTER TABLE dbo.Aufftypen ADD CONSTRAINT PK_ActivityType PRIMARY KEY (AufftNr) ON [PRIMARY]

	ALTER TABLE dbo.CountDown ADD CONSTRAINT FK_CountDowns_ActivityTypes FOREIGN KEY (AufftNr) REFERENCES dbo.Aufftypen (AufftNr)
	ALTER TABLE dbo.ActivityTypeGroups ADD CONSTRAINT FK_ActivityTypeGroups_FK_CountDowns_ActivityTypes FOREIGN KEY (ActivityTypeId) REFERENCES dbo.Aufftypen (AufftNr) ON DELETE CASCADE
	ALTER TABLE dbo.ActivityTypeResourceTypes ADD CONSTRAINT FK_ActivityTypeResourceTypes_ActivityTypes FOREIGN KEY (ActivityTypeId) REFERENCES dbo.Aufftypen (AufftNr) ON DELETE CASCADE
	ALTER TABLE dbo.Aufführgtabelle ADD CONSTRAINT FK_Activities_ActivityTypes FOREIGN KEY (Art) REFERENCES dbo.Aufftypen (AufftNr) 
	ALTER TABLE dbo.RoleGroups_ActivityTypes ADD CONSTRAINT FK_RoleGroups_ActivityTypes_ActivityTypes FOREIGN KEY (ActivityTypeId) REFERENCES dbo.Aufftypen (AufftNr) ON DELETE CASCADE
END
GO

--#endregion

--#region 2018-04-04
IF EXISTS (SELECT * FROM PersH WHERE PersNr = 0)
BEGIN
	Print 'Remove Person 0 ...'
	DELETE FROM CastBonus WHERE CastId IN (SELECT Id FROM BesetzungTabelle WHERE Persnr = 0)
	DELETE FROM BesetzungTabelle WHERE Persnr = 0
	DELETE FROM VertragRolle WHERE Vertragsnr IN(SELECT Vertragsnr FROM Vertrag WHERE Persnr = 0)
	DELETE FROM VertragPerso Where VertragsNr in (Select Vertragsnr FROM Vertrag WHERE Persnr = 0)
	DELETE FROM VertragDetails Where VertragsNr in (Select Vertragsnr FROM Vertrag WHERE Persnr = 0)
	DELETE FROM Vertrag WHERE Persnr = 0
	UPDATE Zr SET AdressPersNr = NULL WHERE AdressPersNr = 0
	UPDATE DienstplanArtenTabelle SET HeadOfDepartmentId = NULL WHERE  HeadOfDepartmentId = 0
	DELETE FROM BesRepertoire WHERE PersNr = 0
	DELETE FROM PersonalDetails WHERE Pnr = 0
	DELETE FROM PersAdresse WHERE PersNr = 0
	DELETE FROM PersKom WHERE PersNr = 0
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.PersMasse') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) DELETE FROM PersMasse WHERE PersNr = 0
	DELETE FROM StatusZeitR WHERE PersNr = 0
	DELETE FROM OrderTravelers WHERE TravelerId = 0
	DELETE FROM PersAgentur WHERE PersNr = 0
	DELETE FROM PersAgentur WHERE ChildPersNr = 0
	DELETE FROM PersonalHonorar WHERE Persnr = 0
	UPDATE XHDelBasicCast SET PersonOldId = NULL WHERE PersonOldId = 0
	UPDATE XHDelBasicCast SET PersonNewId = NULL WHERE PersonNewId = 0
	UPDATE BesetzungStdSoliTabelle SET PersNr1 = NULL WHERE PersNr1 = 0
	UPDATE BesetzungStdSoliTabelle SET PersNr2 = NULL WHERE PersNr2 = 0
	UPDATE BesetzungStdSoliTabelle SET PersNr3 = NULL WHERE PersNr3 = 0
	UPDATE BesetzungStdSoliTabelle SET PersNr4 = NULL WHERE PersNr4 = 0
	DELETE FROM PersH WHERE PersNr = 0
END
GO
--#endregion

--#region SH 2018-04-16 Neue Spalten OSInfo und FrameworkVersion in Computer und Aktualiserung von LogLogin
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Computer') AND [name] = 'OSInfo')
BEGIN
	PRINT('Adding column Computer.OSInfo ...')
	ALTER TABLE dbo.Computer ADD OSInfo VARCHAR(100) NULL
END
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Computer') AND [name] = 'FrameworkVersion')
BEGIN
	PRINT('Adding column Computer.FrameworkVersion ...')
	ALTER TABLE dbo.Computer ADD FrameworkVersion VARCHAR(24) NULL

	PRINT('Initializing Computer.FrameworkVersion...')
	EXEC('UPDATE Computer SET FrameworkVersion = ''4.7.0'' WHERE FrameworkVersion IS NULL AND FrameworkInfo LIKE ''%4.7.%''')
	EXEC('UPDATE Computer SET FrameworkVersion = ''4.6.0'' WHERE FrameworkVersion IS NULL AND FrameworkInfo LIKE ''%4.6.%''')
	EXEC('UPDATE Computer SET FrameworkVersion = ''4.5.0'' WHERE FrameworkVersion IS NULL AND FrameworkInfo LIKE ''%4.5.%''')
END
GO

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

CREATE 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 UserPW WHERE  UserName = CURRENT_USER

		IF @UserId = 0 
		BEGIN
			EXEC AddCurrentUser
			SELECT @UserId = UserID FROM UserPW 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 UserPW SET LastLoginDate = GetDate(), LastLoginComputerId = @ComputerId WHERE UserID  = @UserId
	END
GO
GRANT EXECUTE ON dbo.LogLogin TO public
GO

--#endregion
--#region Variants DH 20180430
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Variants]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	PRINT 'Create Table Variants';
	CREATE TABLE Variants(
		VariantId int IDENTITY(1001,1) NOT NULL,
		Code Varchar(5) NOT NULL,
		VariantName Varchar(30) NOT NUll, 
		VariantDescription Varchar(1000) Sparse NULL,
		Sort INT NOT NULL Constraint DF_Variants_Sort Default 0,
		StartDate DateTime NULL,
		EndDate DateTime NULL,
		IsMaster Bit Not Null Constraint DF_Variants_IsMaaster Default 0,		
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_Variants PRIMARY KEY CLUSTERED (VariantID) ON [PRIMARY]);
	CREATE UNIQUE NONCLUSTERED INDEX IX_Variants_Code_StartDate_Enddate ON Variants (Code, StartDate,EndDate) ON [PRIMARY];
	CREATE UNIQUE NONCLUSTERED INDEX IX_Variants_VariantName ON Variants(VariantName) ON [Primary];	
END
GO
	Print 'Granting Permissions to Variants'
GRANT INSERT, UPDATE,DELETE ON Variants TO DispoAdmin
GO
GRANT SELECT ON Variants TO Public
GO
IF((SELECT Count(*) FROM Variants)= 0)
BEGIN
	PRINT 'Inserting Variants to Variant Table'
	SET IDENTITY_INSERT Variants ON;
	DECLARE @country VARCHAR(20);
	SELECT @country= WertText FROM Settings WHERE Form = 'Adresse' AND Control = 'Country';
	WITH myVariants AS (
		SELECT DISTINCT 
		Status,
		Char(64+status/100) AS Code,
		'Variant' + CASE WHEN @country IN('FI','EN','F','BE','NL') THEN '' ELSE 'e' END +' '+Char(64+status/100) as VariantName,
		'' AS VariantDescription,
		Status AS Sort,
		null AS DateStart,
		null AS DateEnd	 
		FROM AufführgTabelle WHERE Status>99)
	INSERT INTO Variants(VariantID,Code,VariantName,VariantDescription,Sort,lm,lc,uc,um)
	SELECT Status,code,VariantName,VariantDescription,Sort,GETDATE(),GETDATE(),0,0 FROM myVariants;
	INSERT INTO Variants(VariantID,Code,VariantName,VariantDescription,Sort,IsMaster,lm,lc,uc,um)
	VALUES(0,'TS_M','Theasoft Master','',0,1,GETDATE(),GETDATE(),0,0);
	SET IDENTITY_INSERT Variants OFF ;
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'VariantId' and o.id = OBJECT_ID(N'dbo.AufführgTabelle'))
	BEGIN
		Print 'Add Column VariantID to AufführTabelle'
		ALTER TABLE dbo.AufführgTabelle ADD VariantId INT Constraint DF_AufführTabelle_VariantId Default 0 NOT NULL
	END
GO

IF(EXISTS (SELECT status FROM AufführgTabelle WHERE Status>=100))
BEGIN
PRINT 'Updating Activities'
UPDATE AufführgTabelle 
	SET VariantID =CASE WHEN [Status]<100 THEN 0 ELSE [status] END;
UPDATE AufführgTabelle 
	SET Status = 10
	WHERE Variantid>=100;
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Activities_Variants') AND type = 'F') 
BEGIN
ALTER TABLE dbo.AufführgTabelle  WITH CHECK ADD  CONSTRAINT FK_Activities_Variants FOREIGN KEY(VariantID)
	REFERENCES dbo.Variants (VariantID) ON DELETE CASCADE
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'VariantId' and o.id = OBJECT_ID(N'dbo.XHDelAufführg'))
	BEGIN
		Print 'Add Column VariantId to XHDelAufführg'
		ALTER TABLE dbo.XHDelAufführg ADD VariantId INT NULL
	END
GO

--#endregion
--#endregion (4.181.x)

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

--#region Bugfix KatNr-Column
IF EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'KatNr' AND isComputed = 1 AND o.id = OBJECT_ID(N'dbo.AuffTypen'))
BEGIN
ALTER TABLE AuffTypen DROP COLUMN KatNr
ALTER TABLE AuffTypen ADD KatNr AS    (CONVERT(SMALLINT, CASE WHEN Category >= 2000 THEN 0
										WHEN Category >= 400 AND Category < 1000 THEN 1
												WHEN Category = 200  THEN 3
												WHEN Category = 100  THEN 5
												WHEN Category = 1420 THEN -1
												WHEN Category = 1410 THEN -3
												WHEN Category = 1900 THEN -4
												WHEN Category = 1300 THEN -10
												ELSE 99 END))
END
GO
--#endregion

--#region Aktivitätshistorie mit Sperrstatus
IF NOT EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsPrivate' AND o.id = OBJECT_ID(N'dbo.XHDelAufführg'))
BEGIN
	ALTER TABLE XHDelAufführg ADD IsPrivate BIT NULL
END
GO
--#endregion

--#region SH 2018-05-23 Drop Tables aus 2016/2017 die ggf. nicht ausgeführt wurden
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ZulagenDispo]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE ZulagenDispo
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[OrchBesetzung]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE OrchBesetzung
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Instrumenbestand]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE Instrumenbestand
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Instrumente]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE Instrumente
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[InstrumentenGruppe]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)	DROP TABLE InstrumentenGruppe
GO
--#endregion

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

--#region ----------- 4.182.x ---------------------------------

--#region TK 2018-04-05 Reparaturen
--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.ResourceObjectRepairs') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
--BEGIN
--Print 'Table ResourceObjectRepairTypes';
--	CREATE TABLE dbo.ResourceObjectRepairTypes(
--		ResourceObjectRepairTypeId INT IDENTITY(1,1) NOT NULL,
--		RepairTypeName INT NOT NULL,
--		Module INT NOT NULL,
--		LM DATETIME NOT NULL,
--		UM INT NOT NULL,
--		LC DATETIME NOT NULL,
--		UC INT NOT NULL,
--		CONSTRAINT PK_ResourceObjectRepairTypes PRIMARY KEY CLUSTERED (ResourceObjectRepairTypeId) ON [PRIMARY],
--	) ON [PRIMARY]

--	CREATE UNIQUE NONCLUSTERED INDEX ResourceObjectRepairTypes_RepairTypeName ON ResourceObjectRepairTypes (RepairTypeName) ON [PRIMARY];
--	GRANT SELECT ON ResourceObjectRepairTypes TO PUBLIC
--	GRANT INSERT, UPDATE, DELETE ON dbo.ResourceObjectRepairTypes TO OrchesterAdmin
	
--	Print 'Table ResourceObjectRepairs';
--	CREATE TABLE dbo.ResourceObjectRepairs(
--		ResourceObjectRepairId INT IDENTITY(1,1) NOT NULL,
--		ResourceObjectId INT NOT NULL,
--		SupplierId INT NULL,
--		RapairDate DATE NOT NULL,
--		RefundedAmount MONEY NULL,
--		IsCostEstimate BIT  NOT NULL CONSTRAINT DF_ResourceObjectRepairs_IsCostEstimate DEFAULT 0,
--		CurrencyId INT NOT NULL,
--		CurrencyRate FLOAT NULL,
--		Note VARCHAR(1000) SPARSE NULL,
--		LM DATETIME NOT NULL,
--		UM INT NOT NULL,
--		LC DATETIME NOT NULL,
--		UC INT NOT NULL,
--		CONSTRAINT PK_ResourceObjectRepairs PRIMARY KEY NONCLUSTERED (ResourceObjectRepairId) ON [PRIMARY],
--		CONSTRAINT FK_ResourceObjectRepairs_ResourceObjects FOREIGN KEY(ResourceObjectId) REFERENCES ResourceObjects (ResourceObjectId) ON DELETE CASCADE,
--		CONSTRAINT FK_ResourceObjectRepairs_Persons FOREIGN KEY(SupplierId) REFERENCES Persh (PersNr) 
--	) ON [PRIMARY]

--	CREATE NONCLUSTERED INDEX IX_ResourceObjectRepair_RapairDate ON ResourceObjectRepairs (RapairDate) ON [PRIMARY];
--	CREATE CLUSTERED INDEX IX_ResourceObjectRepair_ResourceObjectId ON ResourceObjectRepairs (ResourceObjectId) ON [PRIMARY];
		
--	Print 'Table ResourceObjectRepairPositions';
--	CREATE TABLE dbo.ResourceObjectRepairPositions(
--		ResourceObjectRepairPositionId INT IDENTITY(1,1) NOT NULL,
--		ResourceObjectRepairId INT NOT NULL,
--		ResourceObjectRepairTypeId INT NOT NULL,
--		Sort INT NOT NULL,
--		NetRepairCosts MONEY NULL,
--		TaxId INT NULL,
--		Note VARCHAR(1000) SPARSE NULL,
--		LM DATETIME NOT NULL,
--		UM INT NOT NULL,
--		LC DATETIME NOT NULL,
--		UC INT NOT NULL,
--		CONSTRAINT PK_ResourceObjectRepairPositions PRIMARY KEY NONCLUSTERED (ResourceObjectRepairPositionId) ON [PRIMARY],
--		CONSTRAINT FK_ResourceObjectRepairPositions_ResourceObjectRepairs FOREIGN KEY(ResourceObjectRepairId) REFERENCES ResourceObjectRepairs (ResourceObjectRepairId) ON DELETE CASCADE,
--		CONSTRAINT FK_ResourceObjectRepairPositions_ResourceObjectRepairTypes FOREIGN KEY(ResourceObjectRepairTypeId) REFERENCES ResourceObjectRepairTypes (ResourceObjectRepairTypeId) 
--	) ON [PRIMARY]

--	CREATE CLUSTERED INDEX IX_ResourceObjectRepairPositions_ResourceObjectRepairId ON ResourceObjectRepairPositions (ResourceObjectRepairId) ON [PRIMARY]
--END

--GO

--	CREATE TABLE dbo.ResourceObjectRepairAttachments (
--			ResourceObjectRepairAttachmentId INT IDENTITY(1,1) NOT NULL,--ID
--			ResourceObjectRepairId INT NOT NULL,
--			AttachmentId INT NOT NULL,
--			Note VARCHAR (1000) SPARSE NULL,
--			Sort INT NOT NULL CONSTRAINT DF_ResourceObjectRepairAttachmentss_Sort DEFAULT(0),
--			LC DATETIME NOT NULL,
--			UC INT NOT NULL,
--			LM DATETIME NOT NULL,
--			UM INT NOT NULL
--			CONSTRAINT PK_ResourceObjectRepairAttachmentId PRIMARY KEY CLUSTERED (ResourceObjectRepairAttachmentId ASC) ON [PRIMARY]
--			CONSTRAINT FK_ResourceObjectRepairAttachments_ResourceObjectRepairs FOREIGN KEY (ResourceObjectRepairId) REFERENCES dbo.ResourceObjectRepairs (ResourceObjectRepairId) ON DELETE CASCADE,
--			CONSTRAINT FK_ResourceObjectRepairAttachments_Attachments FOREIGN KEY (AttachmentId) REFERENCES dbo.[Attachments] (AttachmentId)
--	) ON [PRIMARY]
	


--IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbResourceObjectRepairs')) DROP VIEW dbo.AbResourceObjectRepairs
--GO
--CREATE VIEW dbo.AbResourceObjectRepairs
--AS 
--SELECT ROR.* FROM ResourceObjectRepairs AS ROR WHERE ROR.ResourceObjectId IN (
--		SELECT ro.ResourceObjectId FROM ResourceObjects AS ro
--			INNER JOIN dbo.Resources AS r ON ro.ResourceId = r.ResourceId
--			INNER JOIN UserGruppe AS ug ON r.OwnerId = ug.GruppeId
--			INNER JOIN UserPw AS pw ON ug.UserId = pw.UserId
--		WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 16)
--GO
--GRANT SELECT ON AbResourceObjectRepairs TO PUBLIC

--IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbResourceObjectRepairs_Update')) DROP VIEW dbo.AbResourceObjectRepairs_Update
--GO
--CREATE VIEW dbo.AbResourceObjectRepairs_Update
--AS 
--SELECT ROR.* FROM ResourceObjectRepairs AS ROR WHERE ROR.ResourceObjectId IN (
--		SELECT ro.ResourceObjectId FROM dbo.ResourceObjects AS ro
--			INNER JOIN Resources r ON r.ResourceId = ro.ResourceId
--			INNER JOIN UserGruppe AS ug ON r.OwnerId = ug.GruppeId
--			INNER JOIN UserPw AS pw ON ug.UserId = pw.UserId
--		WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 16 AND Ug.OptionsFlag &1=1)
--		WITH CHECK OPTION
--GO
--GRANT INSERT, UPDATE, DELETE ON dbo.AbResourceObjectRepairs_Update TO PUBLIC
--GO

--IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbResourceObjectRepairPositions')) DROP VIEW dbo.AbResourceObjectRepairPositions
--GO
--CREATE VIEW dbo.AbResourceObjectRepairPositions
--AS 
--SELECT RORP.* FROM ResourceObjectRepairPositions AS RORP WHERE RORP.ResourceObjectRepairId IN (
--		SELECT ROR.ResourceObjectRepairId FROM 
--			ResourceObjectRepairs AS ROR 
--			INNER JOIN ResourceObjects AS ro ON ro.ResourceObjectId =ROR.ResourceObjectId
--			INNER JOIN dbo.Resources AS r ON ro.ResourceId = r.ResourceId
--			INNER JOIN UserGruppe AS ug ON r.OwnerId = ug.GruppeId
--			INNER JOIN UserPw AS pw ON ug.UserId = pw.UserId
--		WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 16)
--GO
--GRANT SELECT ON AbResourceObjectRepairPositions TO PUBLIC
--GO
--IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbResourceObjectRepairPositions_Update')) DROP VIEW dbo.AbResourceObjectRepairPositions_Update
--GO
--CREATE VIEW dbo.AbResourceObjectRepairPositions_Update
--AS 
--SELECT RORP.* FROM ResourceObjectRepairPositions AS RORP WHERE RORP.ResourceObjectRepairId IN (
--		SELECT ROR.ResourceObjectRepairId FROM 
--			ResourceObjectRepairs AS ROR 
--			INNER JOIN ResourceObjects AS ro ON ro.ResourceObjectId =ROR.ResourceObjectId
--			INNER JOIN dbo.Resources AS r ON ro.ResourceId = r.ResourceId
--			INNER JOIN UserGruppe AS ug ON r.OwnerId = ug.GruppeId
--			INNER JOIN UserPw AS pw ON ug.UserId = pw.UserId
--		WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 16 AND Ug.OptionsFlag &1=1)
--		WITH CHECK OPTION
--GO
--GRANT INSERT, UPDATE, DELETE ON dbo.AbResourceObjectRepairPositions_Update TO PUBLIC
--GO



--IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbResourceObjectRepairAttachments')) DROP VIEW dbo.AbResourceObjectRepairAttachments
--GO
--CREATE VIEW dbo.AbResourceObjectRepairAttachments
--AS 
--SELECT RORP.* FROM ResourceObjectRepairAttachments AS RORP WHERE RORP.ResourceObjectRepairId IN (
--		SELECT ROR.ResourceObjectRepairId FROM 
--			ResourceObjectRepairs AS ROR 
--			INNER JOIN ResourceObjects AS ro ON ro.ResourceObjectId =ROR.ResourceObjectId
--			INNER JOIN dbo.Resources AS r ON ro.ResourceId = r.ResourceId
--			INNER JOIN UserGruppe AS ug ON r.OwnerId = ug.GruppeId
--			INNER JOIN UserPw AS pw ON ug.UserId = pw.UserId
--		WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 16)
--GO
--GRANT SELECT ON AbResourceObjectRepairAttachments TO PUBLIC
--GO
--IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbResourceObjectRepairAttachments_Update')) DROP VIEW dbo.AbResourceObjectRepairAttachments_Update
--GO
--CREATE VIEW dbo.AbResourceObjectRepairAttachments_Update
--AS 
--SELECT RORP.* FROM ResourceObjectRepairAttachments AS RORP WHERE RORP.ResourceObjectRepairId IN (
--		SELECT ROR.ResourceObjectRepairId FROM 
--			ResourceObjectRepairs AS ROR 
--			INNER JOIN ResourceObjects AS ro ON ro.ResourceObjectId =ROR.ResourceObjectId
--			INNER JOIN dbo.Resources AS r ON ro.ResourceId = r.ResourceId
--			INNER JOIN UserGruppe AS ug ON r.OwnerId = ug.GruppeId
--			INNER JOIN UserPw AS pw ON ug.UserId = pw.UserId
--		WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 16 AND Ug.OptionsFlag &1=1)
--		WITH CHECK OPTION
--GO
--GRANT INSERT, UPDATE, DELETE ON dbo.AbResourceObjectRepairAttachments_Update TO PUBLIC
--GO
--#endregion

--#region TK 2018-04-20 StartOffset / Endoffset

IF NOT EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = object_id('Besetzungtabelle') and c.name = 'StartOffset')
BEGIN
	PRINT 'Cast StartOffset'
		ALTER TABLE dbo.Besetzungtabelle ADD StartOffset SMALLINT NOT NULL CONSTRAINT DF_Cast_StartOffset DEFAULT 0
		ALTER TABLE dbo.Besetzungtabelle ADD EndOffset SMALLINT NOT NULL CONSTRAINT DF_Cast_EndOffset DEFAULT 0
		EXEC ('UPDATE Besetzungtabelle SET  StartOffset = Round(CASE WHEN DiffVon <= -24 OR Diffvon >= 24 THEN 0 ELSE Diffvon END * 60,0) WHERE DiffVon <> 0')
		EXEC ('UPDATE Besetzungtabelle SET  EndOffset = Round(CASE WHEN DiffBis <= -24 OR DiffBis >= 24 THEN 0 ELSE DiffBis END * 60,0) WHERE DiffBis <> 0')

		ALTER TABLE dbo.BesetzungStd ADD StartMasktime SMALLINT NULL
		ALTER TABLE dbo.BesetzungStd ADD EndMasktime SMALLINT NULL
		EXEC ('UPDATE BesetzungStd SET  StartMasktime = Round(CASE WHEN StartOffset <= -24 OR StartOffset >= 24 THEN 0 ELSE StartOffset END * 60,0) WHERE StartOffset <> 0')
		EXEC ('UPDATE BesetzungStd SET  EndMasktime = Round(CASE WHEN EndOffset <= -24 OR EndOffset >= 24 THEN 0 ELSE EndOffset END * 60,0) WHERE EndOffset <> 0')

		UPDATE BesetzungTabelle SET IsCover = 1 , gesperrt = 1 FROM BesetzungTabelle AS c INNER JOIN BesetzungStd AS r ON c.Rolleid = r.ID WHERE r.Cover = 1
END
GO
DropColumn 'BesetzungStd', 'StartOffset'
GO
DropColumn 'BesetzungStd', 'EndOffset'
GO
DropColumn 'Besetzungtabelle', 'DiffVon'
GO
DropColumn 'Besetzungtabelle', 'DiffBis'
GO
--#endregion

--#region TK 2018-04-20
DropColumn 'BesetzungStd', 'nameDrucken'
GO
DropColumn 'BesetzungStd', 'StdPro'
GO

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

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

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


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

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

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

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

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

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

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

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

		EXECUTE sp_Executesql @SQLQuery 

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

			EXECUTE sp_Executesql  @SQLQuery
		END

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		EXECUTE sp_Executesql @SQLQuery 

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

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

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

		--abfrage über tabelle mit join auf die ids mit berechtigungen
		SELECT NULL AS [#2], cd.*, rcd_temp.ContractDateId AS ReplacedContractDateId 
		FROM ContractDates AS cd
		INNER JOIN #ContractDates cd_temp ON cd.ContractDateId = cd_temp.ContractDateId
		LEFT JOIN #ContractDates rcd_temp ON cd.ContractDateId = rcd_temp.ReplacementContractDateId
		INNER JOIN #Cast ON cd.CastId = #Cast.CastId
		WHERE #Cast.NoPermission = 0
	END
END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetCastByCastIdInternal'))DROP PROCEDURE dbo.GetCastByCastIdInternal 
GO
CREATE 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.Id, B.RolleId, B.PersNr, B.AuffNr, B.StartOffset, B.EndOffset, B.BesBem, B.Druck, B.LM, B.UM, B.LC, B.UC, B.Gesperrt, B.BesSort, B.CastStatusId, 
					B.AgencyId, B.IsCover, B.IsCanceled, B.Creditable, B.BackColorArgb, B.IsReplacement, B.ContractId '

	--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  BesetzungTabelle AS B '
			
		IF (@joins&1 = 1) 
			SET @SQLQuery = @SQLQuery + 'INNER JOIN (SELECT * FROM ContractDates WHERE IsCanceled = 0) AS cd ON b.ID = cd.CastID  '

		SET @SQLQuery = @SQLQuery + ' WHERE b.Id 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 BesetzungTabelle AS b 
														INNER JOIN  #Cast ON b.id = #cast.CastId'

			EXECUTE sp_Executesql  @SQLQuery

		END

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

		INSERT INTO #ContractDates (ContractDateId, ReplacementContractDateId)
		SELECT cd.ContractDateId, cd.ReplacementContractDateId FROM ContractDates cd
		INNER JOIN VertragRolle vr ON cd.ContractRoleId = vr.VRID
		INNER JOIN Vertrag v ON vr.VertragsNr = v.VertragsNr
		INNER JOIN UserGruppe ug ON ug.GruppeID = v.ModulGruppeID AND ug.BerechtigungsbereichID = 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
IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetCastByActivityId2')) DROP PROCEDURE dbo.GetCastByActivityId2
IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetCastByActivityIdInternal2')) DROP PROCEDURE dbo.GetCastByActivityIdInternal2
IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.GetCastByPeriodInternal2')) DROP PROCEDURE dbo.GetCastByPeriodInternal2
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Cast_Contract') AND type = 'F') 
BEGIN
	Print ('check Cast_Contract')
	UPDATE Besetzungtabelle SET ContractID = NULL WHERE NOT ContractID IS NULL AND ContractID NOT IN (SELECT VertragsNr FROM Vertrag)
	Print ('create FK_Cast_Contract')

	ALTER TABLE dbo.BesetzungTabelle  WITH CHECK ADD  CONSTRAINT FK_Cast_Contract FOREIGN KEY(ContractId)
		REFERENCES dbo.Vertrag (VertragsNr) ON DELETE SET NULL

	ALTER TABLE dbo.BesetzungTabelle CHECK CONSTRAINT FK_Cast_Contract
END
GO

UPDATE PersKomTyp SET KTyp = 0, IsCommercial = 1 WHERE KTyp = 1
GO
--#endregion

--#region TK 2018-04-20 ContractSalaryRules
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.ContractSalaryRules') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
Print 'Table ContractSalaryRules'
	CREATE TABLE dbo.ContractSalaryRules (
		ContractSalaryRuleId INT IDENTITY(1,1) NOT NULL,
		ContractId INT NOT NULL,
		ContractRoleId INT NULL,
		AccountId INT NOT NULL,
		StartDate DATE NULL,
		EndDate DATE NULL,
		FromPerformanceNumber TINYINT NOT NULL CONSTRAINT DF_ContractSalaryRules_Limit DEFAULT 0, --"Limit"
		SalaryRuleSetting XML NULL,
		SalaryPro SMALLINT NULL,
		SalaryValue MONEY NULL,
		IsDefaultValue BIT NOT NULL CONSTRAINT DF_ContractSalaryRules_IsDefaultValue DEFAULT 0, --"Spielzeitgage"
		IsCalculatory BIT NOT NULL CONSTRAINT DF_ContractSalaryRules_IsCalculatory DEFAULT 0,
		--oder
		SalaryLevelId INT NULL,

		Note VARCHAR(1000) SPARSE NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_ContractSalaryRules PRIMARY KEY NONCLUSTERED (ContractSalaryRuleId) ON [PRIMARY],
		CONSTRAINT FK_ContractSalaryRules_Contracts FOREIGN KEY(ContractId) REFERENCES Vertrag (VertragsNr) ON DELETE CASCADE,
		CONSTRAINT FK_ContractSalaryRules_ContractRoles FOREIGN KEY(ContractRoleId) REFERENCES VertragRolle (VrId) ON DELETE CASCADE,
		CONSTRAINT FK_ContractSalaryRules_SalaryLevel FOREIGN KEY(SalaryLevelId) REFERENCES SalaryLevel (SalaryLevelId),
		CONSTRAINT FK_ContractSalaryRules_Account FOREIGN KEY(AccountId) REFERENCES Zeitkonten (ZeitKtoNr),
	) ON [PRIMARY]

	CREATE CLUSTERED INDEX IX_ContractSalaryRules_Contract ON ContractSalaryRules (ContractId) ON [PRIMARY]
	CREATE INDEX IX_ContractSalaryRules_ContractRoles ON ContractSalaryRules (ContractRoleId) ON [PRIMARY]

	ALTER TABLE dbo.Vertrag ADD CostUnitId INT NULL

	ALTER TABLE dbo.Vertrag  WITH CHECK ADD  CONSTRAINT FK_Contract_CostUnit FOREIGN KEY(CostUnitId)
		REFERENCES dbo.CostUnit (CostUnitId) ON DELETE CASCADE
	ALTER TABLE dbo.Vertrag CHECK CONSTRAINT FK_Contract_CostUnit
END
GO
IF NOT EXISTS (SELECT * FROM ContractSalaryRules)
BEGIN

	DECLARE @country VARCHAR(20)
	SELECT @country = 'D'
	SELECT @country = WertText FROM Settings WHERE Form = 'Adresse' AND Control = 'Country'
	DECLARE @name AS VARCHAR(50)
	
	--Gehälter / Abrechnungsregelen
		SELECT @name = 'Bezug'
		IF @country = 'EN' SELECT @name = 'Salaries'
		IF @country = 'FR' OR @country = 'BE'SELECT @name = 'Salaires'

		IF NOT EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%>Salary<%')
			INSERT INTO Zeitkonten (Formel, Bez, Module, Settings, YearCloseTypeId) 
			VALUES (4020, @name, 0, '<FeeAndSalarySettings><MaturityCostType>Salary</MaturityCostType></FeeAndSalarySettings>',(SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))
		DECLARE @normalAccount int 
		SELECT TOP 1 @normalAccount = ZeitKtoNr FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%>Salary<%' ORDER BY Module
	
		--Abrechnungsregel übernehmen - mit Rollenvertrag Zuordnugn
		INSERT INTO ContractSalaryRules (ContractId, ContractRoleId, SalaryLevelId, AccountId,lm,um,lc,uc)
		SELECT VertragsNr, VRID, SalaryLevelId, @normalAccount,ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1) 
		FROM VertragRolle
		WHERE NOT SalaryLevelId IS NULL AND  ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL )

		--Abrechnungsregel übernehmen - mit Vetragszuordnung und Laufzeit
		INSERT INTO ContractSalaryRules (ContractId, StartDate, EndDate, SalaryLevelId, AccountId, lm,um,lc,uc)
		SELECT VertragsNr, vrVon, vrBis, SalaryLevelId, @normalAccount,ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1)
		FROM VertragRolle
		WHERE NOT SalaryLevelId IS NULL AND NOT ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL)

		--Tagesgagen
		INSERT INTO ContractSalaryRules (ContractId, StartDate,EndDate, SalaryValue, AccountId, SalaryPro, lm,um,lc,uc )
		SELECT VertragsNr, vrVon, vrBis, DayFee*30, @normalAccount, 4, ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1) FROM VertragRolle WHERE NOT DayFee IS NULL AND DayFee <> 0 AND NOT ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL )

		--Vst Honorar
		SELECT @name = 'Vorstellungshonorar'
		IF @country = 'EN' SELECT @name = 'Performance Fee'
		IF @country = 'FR' OR @country = 'BE'SELECT @name = 'Performance Salaries'
		IF NOT EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%PerformanceFee%')
		INSERT INTO Zeitkonten (Formel, Bez, Module, Settings, YearCloseTypeId)
		VALUES (4020, @name, 307, '<FeeAndSalarySettings><MaturityCostType>PerformanceFee</MaturityCostType></FeeAndSalarySettings>',(SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))
		DECLARE @performanceAccount int 
		SELECT TOP 1 @performanceAccount = ZeitKtoNr FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%PerformanceFee%' ORDER BY Module

		--Vst Honorar- mit Rollenvertrag Zuordnugn
		INSERT INTO ContractSalaryRules  (ContractId, ContractRoleId, SalaryValue, SalaryPro, AccountId, Note, lm,um,lc,uc)
		SELECT VertragsNr, VRID, Honorar, AbrechnungVs, @performanceAccount, FeeComment, ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1) FROM VertragRolle WHERE NOT Honorar IS NULL AND Honorar <> 0 AND ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL )
		--, 
		--Vst Honorar - mit Vetragszuordnung und Laufzeit
		INSERT INTO ContractSalaryRules  (ContractId, StartDate, EndDate, SalaryValue,SalaryPro, AccountId,IsDefaultValue,Note, lm,um,lc,uc)
		SELECT VertragsNr, vrVon, vrBis, Honorar, AbrechnungVs, @performanceAccount, CASE WHEN (SELECT COUNT(*) FROM VertragRolle as vr WHERE vr.VertragsNr = VertragRolle.Vertragsnr and AbrechnungVs<> 4 ANd RolleId>0)>0 THEN 1 ELSE 0 END,FeeComment ,ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1) FROM VertragRolle WHERE NOT Honorar IS NULL AND Honorar <> 0 AND NOT ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL ) 
	
	--Proben Honorar
		SELECT @name = 'Probenhonorare'
		IF @country = 'EN' SELECT @name = 'rehearsal Fee'
		IF @country = 'FR' OR @country = 'BE'SELECT @name = 'Répétition Salaries'
		IF NOT EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%RehearsalFee%')
		INSERT INTO Zeitkonten (Formel, Bez, Module, Settings, YearCloseTypeId)
		VALUES (4020, 'Probenhonorare', 307, '<FeeAndSalarySettings><MaturityCostType>RehearsalFee</MaturityCostType></FeeAndSalarySettings>',(SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))
		DECLARE	@rehearsalAccount INT
		SELECT @rehearsalAccount = ZeitKtoNr FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%RehearsalFee%' ORDER BY Module

		--Proben Honorar - mit Rollenvertrag Zuordnugn
		INSERT INTO ContractSalaryRules  (ContractId, ContractRoleId, SalaryValue, SalaryPro, AccountId, Note,lm,um,lc,uc )
		SELECT VertragsNr, VRID, ProbBezahltWert, AbrechnungProben, @rehearsalAccount, RehearsalFeeComment, ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1) FROM VertragRolle WHERE NOT ProbBezahltWert IS NULL AND ProbBezahltWert <> 0 AND ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL )

		--Proben Honorar- mit Vetragszuordnung und Laufzeit
		INSERT INTO ContractSalaryRules  (ContractId, StartDate,EndDate, SalaryValue, SalaryPro, AccountId, Note, lm,um,lc,uc )
		SELECT VertragsNr, vrVon, vrBis, ProbBezahltWert, AbrechnungProben, @rehearsalAccount, RehearsalFeeComment, ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1) FROM VertragRolle WHERE NOT ProbBezahltWert IS NULL AND ProbBezahltWert <> 0 AND NOT ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL )

	--Übernachtungskosten 
		SELECT @name = 'Übernachtungskosten'
		IF @country = 'EN' SELECT @name = 'accommodation costs'
		IF @country = 'FR' OR @country = 'BE'SELECT @name = 'frais de logement '
		IF NOT EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%AccommodationCosts%')
			INSERT INTO Zeitkonten (Formel, Bez, Module, Settings, YearCloseTypeId) 
			VALUES (4020, @name, 51, '<FeeAndSalarySettings><MaturityCostType>AccommodationCosts</MaturityCostType></FeeAndSalarySettings>',(SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))
		DECLARE	@accommodationCosts INT
		SELECT @accommodationCosts = ZeitKtoNr FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%AccommodationCosts%'

		--Übernachtungskosten - mit Rollenvertrag Zuordnugn
		INSERT INTO ContractSalaryRules  (ContractId, ContractRoleId, SalaryValue, SalaryPro, AccountId,lm,um,lc,uc )
		SELECT VertragsNr, VRID, OvernightExpensesFlat, 3, @accommodationCosts, ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1) FROM VertragRolle WHERE NOT OvernightExpensesFlat IS NULL AND OvernightExpensesFlat <> 0 AND ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL )

		--Übernachtungskosten- mit Vetragszuordnung und Laufzeit
		INSERT INTO ContractSalaryRules  (ContractId, StartDate,EndDate, SalaryValue, SalaryPro, AccountId, lm,um,lc,uc )
		SELECT VertragsNr, vrVon, vrBis, OvernightExpensesFlat, 3, @accommodationCosts, ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1) FROM VertragRolle WHERE NOT OvernightExpensesFlat IS NULL AND OvernightExpensesFlat <> 0 AND NOT ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL )

		INSERT INTO ContractSalaryRules (IsCalculatory, ContractId, ContractRoleId, SalaryValue, SalaryPro, AccountId,lm,um,lc,uc )
		SELECT 1, vd.VertragsNr, VRID, UnterkunftVs, 0, @accommodationCosts, ISNULL(vd.lm,'19000101'),ISNULL(vd.um,-1),ISNULL(vd.lc,'19000101'),ISNULL(vd.uc,-1) FROM VertragDetails as vd INNER JOIN VertragRolle on vd.VertragsNr =VertragRolle.VertragsNr   WHERE NOT UnterkunftVs IS NULL AND UnterkunftVs <> 0 AND ((NOT RolleId IS NULL AND RolleId > 0) )

	--Reisekosten--
		SELECT @name = 'Reisekosten'
		IF @country = 'EN' SELECT @name = 'travel costs'
		IF @country = 'FR' OR @country = 'BE'SELECT @name = 'frais de voyage '
		IF NOT EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%TravelCosts%')
			INSERT INTO Zeitkonten (Formel, Bez, Module, Settings, YearCloseTypeId) 
			VALUES (4020, @name, 51, '<FeeAndSalarySettings><MaturityCostType>TravelCosts</MaturityCostType></FeeAndSalarySettings>',(SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))
		DECLARE	@travelCosts INT
		SELECT @travelCosts = ZeitKtoNr FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%TravelCosts%'

		--Reisekosten - mit Rollenvertrag Zuordnugn
		INSERT INTO ContractSalaryRules (ContractId, ContractRoleId, SalaryValue, SalaryPro, AccountId,lm,um,lc,uc )
		SELECT VertragsNr, VRID, TravelExpensesFlat, 3, @travelCosts, ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1) FROM VertragRolle WHERE NOT TravelExpensesFlat IS NULL AND TravelExpensesFlat <> 0 AND ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL )

		--Reisekosten- mit Vetragszuordnung und Laufzeit
		INSERT INTO ContractSalaryRules  (ContractId, StartDate,EndDate, SalaryValue, SalaryPro, AccountId, lm,um,lc,uc )
		SELECT VertragsNr, vrVon, vrBis, TravelExpensesFlat, 3, @travelCosts, ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1) FROM VertragRolle WHERE NOT TravelExpensesFlat IS NULL AND TravelExpensesFlat <> 0 AND NOT ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL )

		INSERT INTO ContractSalaryRules (IsCalculatory, ContractId, ContractRoleId, SalaryValue, SalaryPro, AccountId,lm,um,lc,uc )
		SELECT 1, vd.VertragsNr, VRID, Reisekosten, 0, @travelCosts, ISNULL(vd.lm,'19000101'),ISNULL(vd.um,-1),ISNULL(vd.lc,'19000101'),ISNULL(vd.uc,-1) FROM VertragDetails as vd INNER JOIN VertragRolle on vd.VertragsNr =VertragRolle.VertragsNr   WHERE NOT Reisekosten IS NULL AND Reisekosten <> 0 AND ((NOT RolleId IS NULL AND RolleId > 0) )

	--Überspielhonorar
		IF NOT EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%ExtraFee%')
		INSERT INTO Zeitkonten (Formel, Bez, Module, Settings, YearCloseTypeId)
		VALUES (4020, 'Überspielhonorar', 33, '<FeeAndSalarySettings><MaturityCostType>ExtraFee</MaturityCostType></FeeAndSalarySettings>',(SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))

		DECLARE	@extraFeeAccount INT
		SELECT @extraFeeAccount= ZeitKtoNr FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%ExtraFee%' ORDER BY Module

		INSERT INTO ContractSalaryRules  (ContractId, StartDate, EndDate, SalaryValue, FromPerformanceNumber, AccountId, SalaryPro, lm,um,lc,uc )
		SELECT VertragsNr, vrVon, vrBis, ExtraFee, VorstAnz, @extraFeeAccount, 0, ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1) FROM VertragRolle WHERE NOT ExtraFee IS NULL AND ExtraFee <> 0 AND NOT ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL )

	--Cover Fee  - nur wenn CoverFee verwendet wird
	IF EXISTS (SELECT * FROM VertragRolle WHERE CoverFee > 0)
	BEGIN
		SELECT @name = 'Vst-Cover-Honorar'
		IF @country = 'EN' SELECT @name = 'Performance Cover-Fee'
		IF @country = 'FR' OR @country = 'BE'SELECT @name = 'Performance Cover Salaries'
		IF NOT EXISTS(SELECT * FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%CoverFee%') 
		INSERT INTO Zeitkonten (Formel, Bez, Module, Settings, YearCloseTypeId)
		VALUES (4020, @name, 33, '<FeeAndSalarySettings><MaturityCostType>CoverFee</MaturityCostType></FeeAndSalarySettings>',(SELECT MAX(YearCloseTypeId) FROM YearCloseTypes))
		DECLARE	@coverFeeAccount INT
		SELECT @coverFeeAccount = ZeitKtoNr FROM Zeitkonten WHERE Formel = 4020 AND CONVERT(varchar(max), Settings) like '%CoverFee%' ORDER BY Module
	
		INSERT INTO ContractSalaryRules  (ContractId, ContractRoleId, SalaryValue, SalaryPro, AccountId, lm,um,lc,uc )
		SELECT VertragsNr, VRID, CoverFee, 0 ,@coverFeeAccount, ISNULL(lm,'19000101'),ISNULL(um,-1),ISNULL(lc,'19000101'),ISNULL(uc,-1) FROM VertragRolle WHERE NOT CoverFee IS NULL AND CoverFee <> 0 AND ((NOT RolleId IS NULL AND RolleId > 0) OR NOT ProductionId IS NULL )
	END

	UPDATE Vertrag SET CostUnitId = vr.CostUnitId FROM Vertrag AS V INNER JOIN VertragRolle AS vr ON v.VertragsNr = vr.VertragsNr WHERE NOT vr.CostUnitId IS NULL

	UPDATE Vertrag SET CostUnitId = (SELECT TOP 1 CostUnitProduction.CostUnitId FROM CostUnitProduction WHERE CostUnitProduction.ProductionId = vr.ProductionId )
		FROM Vertrag INNER JOIN Gruppe AS G on Vertrag.ModulGruppeID = g.GruppeID
			INNER JOIN VertragRolle AS vr on Vertrag.VertragsNr = vr.VertragsNr
			INNER JOIN stücke AS pr on vr.ProductionId = pr.snr
		WHERE g.Modul = 4 AND  vr.CostUnitId IS NULL AND Vertrag.CostUnitId IS NULL
			AND (SELECT COUNT (*) FROM CostUnitProduction WHERE CostUnitProduction.ProductionId = vr.ProductionId ) > 0

	DELETE FROM ContractDateConfirmations WHERE ContractDateId IN (SELECT ContractDateId FROM ContractDates WHERE ContractDates.ContractRoleId IN (select VertragRolle.vrid FROM VertragRolle WHERE VertragRolle.ProductionId IS NULL AND ISNULL(RolleId, 0) = 0 AND CostUnitId IS NULL))
	DELETE FROM ContractDates WHERE ContractDates.ContractRoleId IN (select VertragRolle.vrid FROM VertragRolle WHERE VertragRolle.ProductionId IS NULL AND ISNULL(RolleId, 0) = 0 AND CostUnitId IS NULL)
	DELETE FROM VertragRolle WHERE VertragRolle.ProductionId IS NULL AND ISNULL(RolleId, 0) = 0 AND CostUnitId IS NULL
	
	UPDATE ContractSalaryRules SET SalaryValue = SalaryValue / 12, SalaryPro = 4 FROM ContractSalaryRules WHERE SalaryPro = 5  AND SalaryValue <> 0
	UPDATE ContractSalaryRules SET SalaryPro = 4 FROM ContractSalaryRules WHERE SalaryPro = 5 
END
GO
	--Bei Persoverträgen Vertrag Rolle löschen wenn costunit da
	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)
GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.AbContractSalaryRules')) DROP VIEW dbo.AbContractSalaryRules
GO
CREATE VIEW dbo.AbContractSalaryRules
AS 
SELECT csr.*
FROM ContractSalaryRules AS csr 
WHERE csr.ContractId IN (
		SELECT  c.VertragsNr FROM Vertrag AS C 
			INNER JOIN UserGruppe AS ug ON c.ModulGruppeID = ug.GruppeId
			INNER JOIN UserPw AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER AND ug.BerechtigungsbereichId = 1 AND ug.OptionsFlag&1 = 1)
GO
GRANT SELECT ON AbContractSalaryRules TO PUBLIC
GO

IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.AbContractSalaryRules_Update')) DROP VIEW dbo.AbContractSalaryRules_Update
GO
CREATE VIEW dbo.AbContractSalaryRules_Update
AS 
SELECT csr.*
FROM ContractSalaryRules AS csr 
WHERE csr.ContractId IN (
		SELECT  c.VertragsNr FROM Vertrag AS C 
			INNER JOIN UserGruppe AS ug ON c.ModulGruppeID = ug.GruppeId
			INNER JOIN UserPw AS pw ON ug.UserId = pw.UserId
		WHERE Username = CURRENT_USER AND ug.Schreiben = 1 AND ug.BerechtigungsbereichId = 1 AND ug.OptionsFlag&1 = 1)
		WITH CHECK OPTION
GO
GRANT SELECT, DELETE, UPDATE, INSERT ON AbContractSalaryRules_Update TO PUBLIC
GO

UPDATE VertragRolle SET Rolleid = NULL WHERE Rolleid = 0
GO
DropColumn 'VertragDetails', 'AgentBetrag'
GO
DropColumn 'VertragDetails', 'Reisekostenpro'
GO
DropColumn 'VertragDetails', 'Unterkunftpro'
GO
DropColumn 'Vertrag', 'BJBAusgabe'
GO

ALTER VIEW [dbo].[AbVertragRolle]
AS 
SELECT	vr.VertragsNr, vr.RolleId, vr.VRId, vr.ProductionId, vr.vrVon, vr.vrBis, vr.ProbUnbez, vr.RehearsalsCompensatedByPerformance, vr.ProbBezahltAnz, vr.VorstAnz, vr.VorstAnzMin, vr.LM, vr.UM, vr.LC, vr.UC 
FROM 	VertragRolle AS vr 
		INNER JOIN Vertrag AS v ON VR.VertragsNr = v.VertragsNr  
		INNER JOIN	 UserGruppe as ug ON v.ModulGruppeID = UG.GruppeId
		INNER JOIN	UserPW	ON ug.Userid = UserPW.Userid 
	WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 1

GO
ALTER VIEW [dbo].[AbVertragRolle_Update]
AS 
SELECT vr.VertragsNr, vr.RolleId, vr.VRId, vr.ProductionId, vr.vrVon, vr.vrBis, vr.ProbUnbez, vr.RehearsalsCompensatedByPerformance, vr.ProbBezahltAnz, vr.VorstAnz, vr.VorstAnzMin, vr.LM, vr.UM, vr.LC, vr.UC 
	FROM 	VertragRolle AS vr 
	WHERE vr.VertragsNr IN (
		SELECT v.VertragsNr 
			FROM Vertrag   as v
			INNER JOIN	(SELECT DISTINCT GruppeID, Schreiben 
							FROM			UserGruppe 
							INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
							WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 1 AND (OptionsFlag&1) = 1) AS UG
					ON v.ModulGruppeID = UG.GruppeID
			WHERE UG.Schreiben = 1)
GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.GetContractsInternal')) DROP PROCEDURE dbo.GetContractsInternal 
GO
CREATE 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.Vertragsnr, v.ModulGruppeID   '
		END	
	ELSE
		BEGIN
			SET @SQLQuery = 'SELECT *'
		END

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

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

	IF (@joins&2 = 2)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN Gruppe AS g ON v.ModulGruppeId = g.GruppeId '

	IF (@joins&4 = 4)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN VertragsVorlagen AS vv ON vv.VorlagenID = v.VorlagenId '

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

	IF (@joins&16 = 16)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN PersonalDetails pd ON v.PersNr = pd.pnr '

	DECLARE @securetyWhere AS NVARCHAR(MAX)
	SET @securetyWhere = ' EXISTS (SELECT * FROM UserGruppe WHERE UserId = ' + CAST(@userId AS VARCHAR(MAX)) +' AND v.ModulGruppeId = UserGruppe.GruppeId AND BerechtigungsbereichId IN (1, 5))'
	IF (@orContact <> 0)	SET @securetyWhere = '(' + @securetyWhere + ' OR v.PersNr = ' + 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 Vertrag AS V INNER JOIN #Contract ON v.VertragsNr = #Contract.ContractId 
	END
	ELSE
	BEGIN
		RETURN 
	END

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

	IF (@include&4 = 4)
	SELECT NULL AS [#4],
		vr.VertragsNr, vr.RolleId, vr.VRId, vr.ProductionId, vr.vrVon, vr.vrBis, vr.ProbUnbez, vr.RehearsalsCompensatedByPerformance, vr.ProbBezahltAnz, vr.VorstAnz, vr.VorstAnzMin, vr.LM, vr.UM, vr.LC, vr.UC 
	FROM  
		VertragRolle AS vr 
				INNER JOIN #Contract ON vr.VertragsNr = #Contract.ContractId
				INNER JOIN UserGruppe AS u ON u.UserId = @userId AND #Contract.OwnerGroupId = u.GruppeId AND u.BerechtigungsbereichId = 1

	IF (@include&8 = 8) 
		SELECT NULL AS [#8], VertragDetails.*
		FROM VertragDetails
			INNER JOIN #Contract ON VertragDetails.VertragsNr = #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.PersContractId = #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], ContractPersoWorkingCycles.*
		FROM ContractPersoWorkingCycles
			INNER JOIN #Contract ON ContractPersoWorkingCycles.ContractId = #Contract.ContractId

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

	DROP TABLE #Contract
END
GO

--#endregion

--#region DH20180427 Repertoire
IF EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = object_id('BesRepertoire') and c.name = 'Level' and c.max_length = 3)
BEGIN
	PRINT 'Settings size of BesRepertoire.Level to 60...'
	ALTER TABLE BesRepertoire ALTER COLUMN Level varchar(60) null;
END
GO
IF EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = object_id('BesRepertoire') and c.name = 'Sprache' and c.max_length = 3)
BEGIN
	PRINT 'Settings size of BesRepertoire.Sprache to 20...'
	ALTER TABLE BesRepertoire ALTER COLUMN Sprache varchar(20) null;
END
GO
IF EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = object_id('RepArt') and c.name = 'Bez' and c.max_length = 8)
BEGIN
	PRINT 'Settings size of RepArt.Bez to 20...'
	ALTER TABLE RepArt ALTER COLUMN Bez varchar(20) null;
END
GO

--#endregion

--#region Variants DH 20180430
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Variants]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	PRINT 'Create Table Variants';
	CREATE TABLE Variants(
		VariantID int IDENTITY(1001,1) NOT NULL,
		Code Varchar(5) NOT NULL,
		VariantName Varchar(30) NOT NUll, 
		VariantDescription Varchar(1000) Sparse NULL,
		Sort INT NOT NULL Constraint DF_Variants_Sort Default 0,
		StartDate DateTime NULL,
		EndDate DateTime NULL,
		IsMaster Bit Not Null Constraint DF_Variants_IsMaaster Default 0,		
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_Variants PRIMARY KEY CLUSTERED (VariantID) ON [PRIMARY]);
	CREATE UNIQUE NONCLUSTERED INDEX IX_Variants_Code_StartDate_Enddate ON Variants (Code, StartDate,EndDate) ON [PRIMARY];
	CREATE UNIQUE NONCLUSTERED INDEX IX_Variants_VariantName ON Variants(VariantName) ON [Primary];	
END
GO
	Print 'Granting Permissions to Variants'
GRANT INSERT, UPDATE,DELETE ON Variants TO DispoAdmin
GO
GRANT SELECT ON Variants TO Public
GO
IF((select Count(*) from Variants)=0)
BEGIN
	Print 'Inserting Variants to Variant Table'
	Set Identity_Insert Variants on;
	DECLARE @country VARCHAR(20);
	SELECT @country= WertText FROM Settings WHERE Form = 'Adresse' AND Control = 'Country';
	with myVariants as (
		select distinct 
		Status,
		Char(64+status/100) as Code,
		'Variant'+case when @country in('FI','EN','F','BE','NL') then '' else 'e' end +' '+Char(64+status/100) as VariantName,
		'' as VariantDescription,
		Status as Sort,
		null as DateStart,
		null as DateEnd	 
		from AufführgTabelle where Status>99)
	Insert into Variants(VariantID,Code,VariantName,VariantDescription,Sort,lm,lc,uc,um)
	select Status,code,VariantName,VariantDescription,Sort,GETDATE(),GETDATE(),0,0 from myVariants;
	Insert into Variants(VariantID,Code,VariantName,VariantDescription,Sort,IsMaster,lm,lc,uc,um)
	Values(0,'#','Master','',0,1,GETDATE(),GETDATE(),0,0);
	Set Identity_Insert Variants off ;
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'VariantId' and o.id = OBJECT_ID(N'dbo.AufführgTabelle'))
	BEGIN
		Print 'Add Column VariantID to AufführTabelle'
		ALTER TABLE dbo.AufführgTabelle ADD VariantId INT Constraint DF_AufführTabelle_VariantID Default 0 NOT NULL
	END
GO

if(exists (select status from AufführgTabelle where Status>=100))
Begin
Print 'Updating Activities'
Update AufführgTabelle 
	set VariantID =case when [Status]<100 then 0 else [status] end;
Update AufführgTabelle 
	set Status = 10
	where Variantid>=100;
END
Go
 IF EXISTS (SELECT * FROM dbo.sysobjects so LEFT JOIN dbo.syscomments sm ON sm.id = so.id
			WHERE so.id = OBJECT_ID(N'dbo.FK_Activities_Variants') )
			BEGIN
				ALTER TABLE dbo.AufführgTabelle DROP CONSTRAINT FK_Activities_Variants
			END
GO
ALTER TABLE dbo.AufführgTabelle  WITH CHECK ADD  CONSTRAINT FK_Activities_Variants FOREIGN KEY(VariantID)
	REFERENCES dbo.Variants (VariantID) 
GO
IF NOT EXISTS (select * from sys.objects where type = 'TR' and name = 'TR_Variants_Delete')
EXEC dbo.sp_executesql @statement = N'
CREATE TRIGGER TR_Variants_Delete ON Variants
INSTEAD OF DELETE
AS
BEGIN

    SET NOCOUNT ON;

    DELETE v
    FROM Variants AS v
    INNER JOIN deleted AS d
        ON v.VariantID = d.VariantID
    WHERE v.VariantID <> 0;

END; 
'
GO
IF NOT EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = object_id('XHDelAufführg') and c.name = 'VariantId' )
BEGIN
	ALTER TABLE XHDelAufführg ADD VariantId Int null
END
GO
--#endregion DH 20180430


--#region 20180511 DH
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsSingle' and o.id = OBJECT_ID(N'dbo.Personalnotizentyp'))
	BEGIN
		Print 'Add Column IsSingle to Personalnotizentyp'	
		ALTER TABLE Personalnotizentyp Add IsSingle bit not null constraint df_personalnotizentyp_IsSingle Default 0;
END
GO
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 182 OR (Minor=182 AND Build < 3)))))
BEGIN
	Update PersonalNotizenTyp
	set IsSingle=1 where NotizTypID < 6;

	Update PersonalNotizenTyp
	set NotizenArt= case
		when NotizenArt in (11,111) then 11 
		when NotizenArt in (12,112) then 12 
		when NotizenArt in (13,113) then 13 
		when NotizenArt in (14,114)then 14 
		else 0 end;
END
GO
--#endregion

--#region SH 2018-05-11 Anpassungen an AbBuehnenProbenNr bzgl. Merkmal und KatNr
PRINT('Updating Procedure AbBuenenProbenNr...')
GO
ALTER PROCEDURE [dbo].[AbBuenenProbenNr]
@lSnr int,
@DDatum  Datetime, 
@dVon  Datetime, 
@dspzStart  Datetime, 
@lZrNr As int
As

SELECT
	Count(*) AS [Anz]
FROM
	AufführgTabelle a
	INNER JOIN AuffTypen at ON a.Art = at.AuffTNr
WHERE
	a.Snr= @lSnr
	AND a.[Status] >= 0
	AND a.[VariantId] = 0
	AND a.ZrNr= @lZrNr
	AND at.Category = 800 --Proben
	AND (
		(a.Datum < @DDatum  and a.Datum>= @dspzStart)
		OR (a.Datum= @DDatum AND  CONVERT(varchar(5), a.uhrbeg, 8)<= CONVERT(varchar(5), @dvon, 8))
	)
GO
--#endregion

--#region SH 2018-05-11 Anpassungen an CopyRole, da Spalten entfernt und hinzugefügt wurden
PRINT('Updating Procedure CopyRole...')
GO
--view aktualisieren da sonst eine fehlermeldung kommt
EXEC sys.sp_refreshview BesetzungStd_Update
GO
ALTER PROCEDURE [dbo].[CopyRole]
	@productionId int,
	@roleId  int
As
BEGIN
	DECLARE @userId INT

	SELECT @userId = UserId FROM UserPW WHERE UserName  = CURRENT_USER
INSERT INTO BesetzungStd_Update (
	[Rolle],[Pos],[Leporello],[PresseSort],[StdVs],[RollenLtgID],[GruppeID],[DruckSteuerung]
      ,[DruckStd],[Cover],[Besitzer],[ABGruppeID] ,[Anzahl],[Exklusiv],[RolleKurz]
      ,[CountDownId],[RollePresse],[StarRole],[IsInactive],[RoleCode],[Note],[RoleCategoryId],[WorkVersionRoleId]
	  ,[AutoCast],[StartMasktime],[EndMasktime]
	  ,[SNr] 
      ,[LM]
      ,[UM]
      ,[LC]
      ,[UC]) 
SELECT 
	[Rolle],[Pos],[Leporello],[PresseSort],[StdVs],[RollenLtgID],[GruppeID],[DruckSteuerung]
      ,[DruckStd],[Cover],[Besitzer],[ABGruppeID] ,[Anzahl],[Exklusiv],[RolleKurz]
      ,[CountDownId],[RollePresse],[StarRole],[IsInactive],[RoleCode],[Note],[RoleCategoryId],[WorkVersionRoleId]
	  ,[AutoCast],[StartMasktime],[EndMasktime]
	  ,@productionId, 
	  GETDATE(),
	  @userId,
	  GETDATE(),
	  @userId
FROM BesetzungStd AS RoleSource WHERE RoleSource.ID = @roleId
SELECT CAST(@@IDENTITY as INT)
END
GO
--#endregion

--#region 20180515 DH Ansprechpartner bei Agentur zuordnen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ContactPersonConnectionID' and o.id = OBJECT_ID(N'dbo.Persagentur'))
	BEGIN
		ALTER TABLE Persagentur ADD ContactPersonConnectionID INT NULL;
		ALTER TABLE dbo.Persagentur WITH CHECK ADD  CONSTRAINT FK_PersonAgency_PersonAgency FOREIGN KEY(contactpersonconnectionid)
		REFERENCES dbo.PersAgentur (PersAgnr) ON DELETE no Action
	END
IF NOT EXISTS (SELECT * FROM sys.objects s WHERE s.type='Tr' and s.[name]='delete_Orderspos')
BEGIN
	EXEC ('
		CREATE Trigger delete_ContactpersonConnectionIds ON dbo.Persagentur INSTEAD OF DELETE 
		AS 
		BEGIN
		 UPDATE Persagentur
			SET ContactPersonConnectionID = null
			WHERe ContactPersonConnectionID in (Select persAgNR from deleted);
		DELETE FROM Persagentur
		WHERE persAgNR IN (SELECT persAgNR FROM DELETED)
		END')
	Print 'Trigger delete_ContactpersonConnectionIds created'
END
GO
--#endregion

--#region 20180515 DH
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ContactPersonConnectionID' and o.id = OBJECT_ID(N'dbo.Perskom'))
	BEGIN
		ALTER TABLE Perskom ADD ContactPersonConnectionID INT NULL;
		ALTER TABLE dbo.Perskom WITH CHECK ADD  CONSTRAINT FK_Perskom_PersonAgency FOREIGN KEY(ContactPersonConnectionID)
		REFERENCES dbo.PersAgentur (PersAgnr) ON DELETE CASCADE
	END
GO

print 'Updating View AbPersKom'
exec ('
ALTER VIEW [dbo].[ABPersKom]
AS
SELECT  
	pk.PersKomID, 
	pk.PersKTypID, 
	pk.PersNr, 
	pk.Sort, 
	pk.IsSecret,
	CASE WHEN IsSecret = 1 AND SecretPermission=0 THEN ''**********'' ELSE  pk.Wert	   END AS Wert,
	CASE WHEN IsSecret = 1 AND SecretPermission=0 THEN ''**********'' ELSE  pk.Bemerkung END AS Bemerkung,
	pk.ContactPersonConnectionID,
	pk.LM, pk.UM, pk.LC, pk.UC
FROM PersKom AS pk INNER JOIN (
	SELECT  pp.PersonId, MAX(CASE WHEN (OptionsFlag & 1 <> 1 OR PP.HasAccessToSecretContactData = 0) THEN 0 ELSE 1 END) AS SecretPermission 
	FROM PersonModulGroupPermission AS PP
		INNER JOIN UserGruppe AS UG ON pp.ModulGroupId =  UG.GruppeID 
		INNER JOIN UserPW ON Ug.Userid = UserPW.Userid 
		WHERE BerechtigungsbereichID = 0 AND pp.PermissionType = 0  AND Username = CURRENT_USER 
		GROUP BY pp.PersonId) AS sub ON pk.PersNr = sub.PersonId') 
GO
/****** Object:  View [dbo].[ABPersKom_Update]    Script Date: 15.05.2018 17:32:10 ******/
print 'Updating View AbPersKom_Update'
exec ('
ALTER VIEW [dbo].[ABPersKom_Update]
AS
	SELECT 
	pk.PersKomID, pk.PersKTypID, pk.PersNr, pk.Sort, pk.Wert, pk.Bemerkung, pk.LM, pk.UM, pk.LC, pk.UC,pk.IsSecret,pk.ContactPersonConnectionID

	FROM perskom  as pk

	WHERE PersNr IN (SELECT  pp.PersonId
	FROM PersonModulGroupPermission AS PP
		INNER JOIN UserGruppe AS UG ON pp.ModulGroupId =  UG.GruppeID 
		INNER JOIN UserPW ON Ug.Userid = UserPW.Userid 
	WHERE ug.schreiben=1 AND (OptionsFlag&1 = 1 OR IsSecret = 0) AND BerechtigungsbereichID = 0 AND pp.PermissionType=0 AND pp.HasWritePermission = 1 AND Username = CURRENT_USER )')

GO
--#endregion

--#region DH20180516
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PreparationDuration' and o.id = OBJECT_ID(N'dbo.RollenLtg'))
	BEGIN
		ALTER TABLE RollenLtg ADD PreparationDuration INT NOT NULL Constraint DF_RoleGroup_PreparationDuration Default 0;
		print'Added Column PreparationDuration to RollenLtg'		
	END
GO
--#endregion

--#region DH20180518 Anpassungen VariantenID

ALTER VIEW [dbo].[AbTechnicalPersonalRequirements]
AS 

	SELECT auff.Datum, auff.UhrBeg, auff.UhrEnde, aufgabe.ArbeiterAnzahl AS SollZahl, aufgabe.ABGruppeId, Count(cuwt.ActivityJobId) as IstZahl, aufgabe.Pos

		FROM AuffTechAufgabe as aufgabe
		INNER JOIN AufführgTabelle AS auff ON auff.AuffNr = aufgabe.AuffNr
		LEFT JOIN CostUnitWorkingTime AS cuwt ON cuwt.ActivityJobId = aufgabe.AuffTechAufgabeID and cuwt.ActivityID = auff.AuffNr

	WHERE auff.[Status] BETWEEN 0 AND 99 AND auff.VariantId = 0 -- Invalid column name 'Status'.
	GROUP BY auff.Auffnr, aufgabe.AuffTechAufgabeID,  auff.Datum, auff.UhrBeg, auff.UhrEnde, aufgabe.ArbeiterAnzahl, aufgabe.ABGruppeId, aufgabe.Pos
GO

ALTER FUNCTION dbo.GetActivityTypeRehearsalNumbers(@start DATE, @end DATE)
		RETURNS TABLE
		AS
			RETURN (SELECT Row_Number() OVER (PARTITION BY Art, Snr, VariantId ORDER BY Datum, UhrBeg) AS RowNum, AuffNr, Datum 
					FROM AufführgTabelle AS A
						INNER JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art 
				WHERE AT.LfdNr = 1 AND Datum BETWEEN @start AND @end AND [Status] > 0)
GO

ALTER PROCEDURE dbo.GetActivityPerformanceNumber
	@productionId INT,
	@seasonStart DATE,
	@date DATE,
	@startTime SMALLDATETIME,
	@variantId INT
AS
		SELECT COUNT(*) AS Anz
		FROM AufführgTabelle AS a
			INNER JOIN AuffTypen AS At ON a.Art = At.AuffTNr
		WHERE a.Snr = @productionId 
		AND At.KatNr = 0
		AND a.VariantId = @variantId
		AND a.Status>0
		AND ((a.Datum < @date AND a.Datum >= @seasonStart) OR (a.Datum = @date AND UhrBeg <= @startTime))
GO

ALTER FUNCTION dbo.GetActivityPerformanceNumbers(@start DATE, @end DATE)
		RETURNS TABLE
		AS
			RETURN (SELECT Row_Number() OVER (PARTITION BY a.Snr,VariantId ORDER BY Datum, UhrBeg) AS RowNum, AuffNr, Datum 
					FROM AufführgTabelle AS A
						INNER JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art
					WHERE Category >= 2000 AND Datum BETWEEN @start AND @end AND  [Status] > 0)
GO

ALTER FUNCTION dbo.GetActivityPerformanceNumbersAllSeasons(@start DATE, @end DATE)
		RETURNS TABLE
		AS
			RETURN (SELECT * FROM (SELECT Row_Number() OVER (PARTITION BY a.Snr ORDER BY Datum, UhrBeg)  + ISNULL(pd.AnzahlAuff, 0)  AS RowNum, AuffNr, Datum
					FROM AufführgTabelle AS A
						INNER JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art
						LEFT JOIN StückeDetails AS PD ON Pd.Snr = A.Snr
					WHERE  Category >= 2000 AND Datum <= @end AND  [Status] BETWEEN 0 AND 99 AND VariantId = 0) AS subA WHERE Datum BETWEEN @start AND @end) 
GO

ALTER VIEW [dbo].[Aufführg]
AS
SELECT a.*
FROM  AufführgTabelle a
	INNER JOIN  Spielzeittabelle AS s ON a.Datum <= s.SpzEnde AND a.Datum >= s.SpzStart
	INNER JOIN  UserForAccess AS us ON s.spznr=us.spznr
	INNER JOIN  UserPW AS pw ON us.userid=pw.userid
	INNER JOIN  AuffTypen AS at ON a.Art=at.AuffTNr
WHERE	UserName = CURRENT_USER 
	AND at.KatNr NOT IN (3, 99)
	AND  (a.VariantId = 0)  
	AND  (Gesperrt = 0 
		OR (SELECT IS_MEMBER('Spielplan alles lesen'))=1
		OR (SELECT PERMISSIONS(OBJECT_ID('Aufführg'))&2)=2 
) 
WITH CHECK OPTION
GO

ALTER PROCEDURE [dbo].[AbProbenNr]
	@lSnr int,
	@DDatum  Datetime, 
	@dVon  Datetime, 
	@dspzStart  Datetime, 
	@lArt As int
As
	SELECT Count(*) AS [Anz] 
	FROM Aufführgtabelle  
	WHERE Snr = @lSnr  
	  AND VariantId = 0
	  AND Art = @lArt 
	  AND ((Datum < @DDatum  AND Datum>= @dspzStart) 
		  OR  (Datum = @DDatum AND CONVERT(varchar(5), uhrbeg, 8)<= CONVERT(varchar(5), @dvon, 8)))
GO

ALTER PROCEDURE [dbo].sp_SubscriptionActivityCount
	@subscriptionId int,
	@date  Datetime, 
	@seasonStart  Datetime
As
	SELECT COUNT(*)
	FROM AufR as AR
		INNER JOIN Aufführgtabelle AS A ON AR.AuffNr = A.AuffNr 
	WHERE AboNr = @subscriptionId AND Datum <= @date AND Datum >= @seasonStart AND VariantId = 0
GO

ALTER VIEW [dbo].[CastActiveties] 
AS
	SELECT	ac.Datum, ac.UhrBeg, ac.UhrEnde, ac.SNr, ac.ZrNr, ac.Art, ac.Bem, at.KatNr, ac.Status,ac.VariantId, ca.*,st.alt
	FROM	AufführgTabelle				AS ac
			INNER JOIN AuffTypen		AS at	ON ac.art = at.AuffTNr
			INNER JOIN Spielzeittabelle AS s	ON ac.Datum <= s.SpzEnde AND ac.Datum >= s.SpzStart
			INNER JOIN UserForAccess	AS us	ON s.spznr = us.spznr
			INNER JOIN UserPW			AS ua	ON us.UserId = ua.UserID
			INNER JOIN Stücke			AS p	ON ac.snr = p.snr
			LEFT JOIN UserGruppe		AS uga	ON p.ModuleGroupId = uga.GruppeID AND ua.UserID = uga.UserID AND uga.BerechtigungsbereichID = 2
			INNER JOIN Besetzungtabelle	AS ca	ON ac.Auffnr = ca.AuffNr
			LEFT  JOIN BesetzungStd		AS ro	ON ca.RolleID = ro.ID
			INNER  JOIN Gruppe			AS g	ON g.GruppeID = ro.Besitzer	
			INNER  JOIN UserGruppe		AS ugc	ON G.GruppeID = ugc.GruppeID AND ugc.UserID = ua.UserID AND ugc.BerechtigungsbereichID = 4
			LEFT JOIN Stücke			AS st	ON ac.SNr=st.SNr 
	WHERE
			ua.UserName = CURRENT_USER
			AND  (ac.Gesperrt = 0 OR uga.OptionsFlag IS NULL OR uga.OptionsFlag & 1 = 1)
			AND ((ca.Gesperrt = 0 OR (Ugc.OptionsFlag & 1 = 1)))
GO
--#endregion

--#region SH 2018-06-07 AbCastActiveties erweitern um VariantID
IF EXISTS(SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID('[dbo].[AbCastActiveties]'))
BEGIN
	DROP VIEW [dbo].[AbCastActiveties]
END
GO

CREATE VIEW [dbo].[AbCastActiveties]
AS
	SELECT	ac.Datum, ac.UhrBeg, ac.UhrEnde, ac.SNr, ac.ZrNr, ac.Art, ac.Bem, ac.[Status], ca.*,
	        ro.id AS Role_RoleId, ro.RollenLtgId AS Role_TaskAreaId,
	        ro.RoleCategoryId AS Role_RoleCategoryId, ro.Besitzer AS Role_OwnerId, ro.PresseSort AS Role_PressSort, p.Alt AS alt, ac.VariantId
	FROM	AufführgTabelle				AS ac
			INNER JOIN Spielzeittabelle AS s	ON ac.Datum <= s.SpzEnde AND ac.Datum >= s.SpzStart
			INNER JOIN UserForAccess	AS us	ON s.spznr = us.spznr
			INNER JOIN UserPW			AS ua	ON us.UserId = ua.UserID
			INNER JOIN Stücke			AS p	ON ac.snr = p.snr
			INNER JOIN UserGruppe		AS uga	ON p.ModuleGroupId = uga.GruppeID AND ua.UserID = uga.UserID AND uga.BerechtigungsbereichID = 2
			INNER JOIN Besetzungtabelle	AS ca	ON ac.Auffnr = ca.AuffNr
			INNER JOIN BesetzungStd		AS ro	ON ca.RolleID = ro.ID
			INNER JOIN UserGruppe		AS ugc	ON ro.Besitzer = ugc.GruppeID AND ugc.UserID = ua.UserID AND ugc.BerechtigungsbereichID = 4
	WHERE
			ua.UserName = CURRENT_USER
			AND  (ac.Gesperrt = 0 OR uga.OptionsFlag IS NULL OR uga.OptionsFlag & 1 = 1)
			AND ((ca.Gesperrt = 0 OR (Ugc.OptionsFlag & 1 = 1)))
GO

GRANT SELECT ON [AbCastActiveties] TO PUBLIC
GO
--#endregion

--#region bm 20180803 Bugfix DatefromParts in SQL-Server 2008
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].tsDateFromParts'))
BEGIN
	DROP FUNCTION dbo.tsDateFromParts
END
GO

CREATE FUNCTION tsDateFromParts
(
@year AS INTEGER,
@month AS INTEGER,
@day AS INTEGER
)
RETURNS [DATE]
AS
BEGIN
RETURN cast(Convert(datetime,convert(varchar(10),@year)+'-'+
            convert(varchar(10),@month)+'-'+
            convert(varchar(10),@day), 101) as date);
END
GO
--#endregion

--#region DH20180531 Stored Procedures für die Datenbereinigung
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'DataCleaningAdmin')
BEGIN
	EXEC sp_addrole @rolename = N'DataCleaningAdmin'
End
GO

IF type_id('[dbo].[tsIntList]') IS NULL
     begin   
	CREATE TYPE [dbo].[tsIntList] AS TABLE
		(
			[Intvalue] INT        
		);
	END
GO

--#region Dienstplan
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].ClearOldDutyRosterData'))
BEGIN
	DROP PROCEDURE dbo.ClearOldDutyRosterData
END
GO

CREATE PROCEDURE ClearOldDutyRosterData
		@enddate datetime,
		@monthclosedfor int,
		@YearClosed bit, 
		@infoOnly bit
		AS
		BEGIN
		--TEMPORÄRE TABELLE MIT DEN DIENSTPLANEINTRÄGEN, DIE GELÖSCHT WERDEN SOLLEN.
		SELECT DISTINCT d.dienstplanid,d.Datum 
		INTO #TempDutyRosterEntrys 
		FROM Dienstplan d 
				INNER JOIN  VertragPerso as vp ON d.VertragsNr = vp.VertragsNr
				INNER JOIN  ab ON vp.ABID=ab.ABID 
				INNER JOIN DienstplanArtenTabelle da ON ab.DienstplanArtenID = da.DienstplanArtenID
				LEFT JOIN Jahresabschluss j on j.DienstplanArtenID=da.DienstplanArtenID 
					AND d.Datum 
					BETWEEN  dbo.tsDateFromParts(coalesce(j.VonJahrMonat /100,1900),coalesce(j.VonJahrMonat%100,01),1) and dbo.tsDateFromParts(coalesce(j.BisJahrMonat /100,2100),coalesce(j.BisJahrMonat%100,12),30) 
		WHERE      d.Datum < Coalesce(@endDate,getdate()) 
				AND 
				d.Datum<  dateadd(month,@monthClosedFor,dbo.tsDateFromParts(coalesce(da.MAbschluss /100,1900),coalesce(da.MAbschluss%100,01),1))
				AND ((j.Abgeschlossen=1 and @YearClosed=1) OR @YearClosed=0)

		IF(@infoOnly=0)
		BEGIN
			SELECT COUNT(*) FROM #TempDutyRosterEntrys
			DELETE FROM CostUnitWorkingTime where ShiftDayId in (select DienstplanID from #TempDutyRosterEntrys)
			DELETE FROM ZulagenDienstplan where DienstplanID in (select DienstplanID from #TempDutyRosterEntrys)
			DELETE FROM Dienstplan  where dienstplanid in (select DienstplanID from #TempDutyRosterEntrys)
			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempDutyRosterEntrys
		END
		DROP TABLE #TempDutyRosterEntrys
END
GO

GRANT EXECUTE ON dbo.ClearOldDutyRosterData to DataCleaningAdmin
GO
--#endregion

--#region Zeitkonten Monat
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].ClearOldTimeAccountMonth'))
BEGIN
	DROP PROCEDURE dbo.ClearOldTimeAccountMonth
END
GO

CREATE 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 Zeitkonten Monat, DIE GELÖSCHT WERDEN SOLLEN.
		SELECT DISTINCT d.zmID,d.JahrMonat 
		INTO #TempTimeAccountMonths 
		FROM zeitkontenmonat d 
				INNER JOIN  VertragPerso as vp ON d.VertragsNr = vp.VertragsNr
				INNER JOIN  ab ON vp.ABID=ab.ABID 
				INNER JOIN DienstplanArtenTabelle da ON ab.DienstplanArtenID = da.DienstplanArtenID
				INNER JOIN Zeitkonten z on d.ZeitKtoNr=z.ZeitKtoNr
				LEFT JOIN Jahresabschluss j on j.DienstplanArtenID=da.DienstplanArtenID 
					AND d.JahrMonat 
					BETWEEN  COALESCE(j.VonJahrMonat,190001) AND COALESCE(j.BisJahrMonat,210001) AND z.YearCloseTypeId=j.YearCloseTypeId
		WHERE      d.JahrMonat < COALESCE(@endYearMonth,@currentYearmonth) 
								
				AND ((j.Abgeschlossen=1 AND @YearClosed=1) OR @YearClosed=0)

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

GRANT EXECUTE ON dbo.ClearOldTimeAccountMonth to DataCleaningAdmin
go
--#endregion

--#region An/Abwesenheiten
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].ClearOldAbsences'))
BEGIN
	DROP PROCEDURE dbo.ClearOldAbsences
END
GO

CREATE PROCEDURE ClearOldAbsences
		@enddate datetime,
		@AbsenceTypes [tsIntList] READONLY,
		@infoOnly bit
		AS
		BEGIN
		declare @nocount bit
		select @nocount=count(intvalue) from @AbsenceTypes;			
		--TEMPORÄRE TABELLE MIT DEN DIENSTPLANEINTRÄGEN, DIE GELÖSCHT WERDEN SOLLEN.
		SELECT DISTINCT s.StatusZeitRNr,s.Bis 
		INTO #TempAbsences 
		FROM StatusZeitR s 
		 left join @AbsenceTypes a on s.statusid=a.Intvalue		
		WHERE      s.Bis < @enddate								
				   AND (a.Intvalue IS NOT NULL OR @noCount=0)

		IF(@infoOnly=0)
		BEGIN
			SELECT COUNT(*) FROM #TempAbsences
			DELETE FROM StatusZeitR  where StatusZeitRNr in (select StatusZeitRNr from #TempAbsences)
			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempAbsences
		END
		DROP TABLE #TempAbsences
END
GO

GRANT EXECUTE ON dbo.ClearOldAbsences to DataCleaningAdmin
go
--#endregion

--#region Besetzungen
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].ClearOldCasts'))
BEGIN
	DROP PROCEDURE dbo.ClearOldCasts
END
GO

CREATE PROCEDURE ClearOldCasts
		@enddate datetime,
		@activityTypes [tsIntList] READONLY,
		@infoOnly bit
		AS
		BEGIN
		declare @nocount bit
		select @nocount=count(intvalue) from @activityTypes;			
		--TEMPORÄRE TABELLE MIT DEN DIENSTPLANEINTRÄGEN, DIE GELÖSCHT WERDEN SOLLEN.
		SELECT DISTINCT s.ID 
		INTO #TempCasts
		FROM BesetzungTabelle s 
		inner join AufführgTabelle a on s.AuffNr=a.AuffNr
		left join @activityTypes act on act.Intvalue=a.Art		
		WHERE      a.Datum < @enddate								
				AND (act.Intvalue is not null OR @nocount=0)

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

GRANT EXECUTE ON dbo.ClearOldCasts to DataCleaningAdmin
go
--#endregion

--#region Kassenanordnungen
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].ClearOldCashCommands'))
BEGIN
	DROP PROCEDURE dbo.ClearOldCashCommands
END
GO

CREATE PROCEDURE ClearOldCashCommands
@cashdatebefore DateTime,
@hasPayDate bit,
@billingDateBefore DateTime,
@infoOnly bit
AS
BEGIN
		SELECT DISTINCT c.CashCommandId 
		INTO #TempCashCommands
		FROM CashCommand c 
		WHERE      c.CashDate < @cashdatebefore	
			AND @billingDateBefore> c.BillingPeriodEnd							
				AND ((@hasPayDate=1 and PayDate is not null) OR @hasPayDate=0)

		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 CashCommand  where CashCommandId in (select CashCommandId from #TempCashCommands);
			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempCashCommands
		END
		DROP TABLE #TempCashCommands	
END
GO

GRANT EXECUTE ON dbo.ClearOldCashCommands to DataCleaningAdmin
go
--#endregion

--#region Vertragsdaten
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].ClearOldContracts'))
BEGIN
	DROP PROCEDURE dbo.ClearOldContracts
END
GO

CREATE PROCEDURE ClearOldContracts
@contractEndBefore DateTime,
@infoOnly bit
as
Begin
		SELECT DISTINCT v.VertragsNr 
		INTO #TempContracts
		FROM Vertrag v 
		WHERE      v.vBis < @contractEndBefore	

		IF(@infoOnly=0)
		BEGIN
		
			SELECT DISTINCT d.dienstplanid,d.Datum 
			INTO #TempDutyRosterEntrys 
			FROM Dienstplan d 
				INNER JOIN  VertragPerso as vp ON d.VertragsNr = vp.VertragsNr where vp.VertragsNr in  (select VertragsNr from #TempContracts);
			DELETE FROM CostUnitWorkingTime where ShiftDayId in (select DienstplanID from #TempDutyRosterEntrys)
			DELETE FROM ZulagenDienstplan where DienstplanID in (select DienstplanID from #TempDutyRosterEntrys)
			DELETE FROM Dienstplan  where dienstplanid in (select DienstplanID from #TempDutyRosterEntrys)
			SELECT COUNT(*) FROM #TempContracts
			DELETE FROM CastCredits where ContractId in (select VertragsNr from #TempContracts);
			DELETE FROM  Contract_Qualification_Person where ContractId in (select VertragsNr from #TempContracts);
			DELETE FROM  ContractBonus where ContractId in (select VertragsNr from #TempContracts);
			DELETE FROM ContractDateConfirmations where ContractConfirmationId in (select ContractConfirmationId FROM ContractConfirmations WHERE ContractId in (select VertragsNr from #TempContracts));
			DELETE FROM ContractDocumentAttachments where ContractDocumentId in ((select ContractConfirmationId FROM ContractConfirmations WHERE ContractId in (select VertragsNr from #TempContracts)));
			DELETE FROM ContractConfirmations WHERE ContractId in (select VertragsNr from #TempContracts);
			DELETE FROM ContractFields WHERE PersContractId in (select VertragsNr from #TempContracts);
			DELETE FROM ContractPartTimePeriods WHERE ContractId in (select VertragsNr from #TempContracts);
			DELETE FROM ContractSeasonInformation WHERE ContractId in (select VertragsNr from #TempContracts);
			DELETE FROM TimeAccountUsage WHERE ContractId in (select VertragsNr from #TempContracts);			
			DELETE FROM Tours_Contracts WHERE ContractId in (select VertragsNr from #TempContracts);
			DELETE FROM Tours_InventoryItems WHERE ContractId in (select VertragsNr from #TempContracts);	
			DELETE FROM Travels WHERE ContractId in (select VertragsNr from #TempContracts);
			DELETE FROM VertragDetails WHERE VertragsNr in (select VertragsNr from #TempContracts);
			DELETE FROM ContractPersoWorkingCycles where ContractId in (select VertragsNr from #TempContracts);
			DELETE FROM VertragPerso WHERE VertragsNr in (select VertragsNr from #TempContracts);
			DELETE FROM ContractDateMaturities Where ContractDateId in (select ContractDateId FROM ContractDates WHERE ContractRoleId in (select ContractRoleId FROM VertragRolle WHERE VertragsNr in (select VertragsNr from #TempContracts)));
			DELETE FROM ContractDateConfirmations where ContractDateId in (select ContractDateId FROM ContractDates WHERE ContractRoleId in (select ContractRoleId FROM VertragRolle WHERE VertragsNr in (select VertragsNr from #TempContracts)));
			DELETE FROM ContractDates WHERE ContractRoleId in (select ContractRoleId FROM VertragRolle WHERE VertragsNr in (select VertragsNr from #TempContracts));	
			DELETE FROM VertragRolle WHERE VertragsNr in (select VertragsNr from #TempContracts);			
			DELETE FROM Vertrag  where VertragsNr in (select VertragsNr from #TempContracts);
			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempContracts
		END
		DROP TABLE #TempContracts	
End
GO

GRANT EXECUTE ON dbo.ClearOldContracts to DataCleaningAdmin
go
--#endregion

--#region Personaldaten
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].ClearOldContacts'))
BEGIN
	DROP PROCEDURE dbo.ClearOldContacts
END
GO

CREATE PROCEDURE ClearOldContacts
@lastModifiedBefore DateTime,
@infoOnly bit
as
Begin
		SELECT DISTINCT p.PersNr 
		INTO #TempContacts
		FROM PersH p 
		WHERE     p.LM <@lastModifiedBefore and p.alt=1	
		and not exists (select PersNr from vertrag where PersNr=p.PersNr) 
		and not exists (select persnr from BesetzungTabelle b where b.PersNr=p.PersNr )
		and not exists (select persnr from StatusZeitR s where s.persnr= p.persnr);


		IF(@infoOnly=0)
		BEGIN
			SELECT COUNT(*) FROM #TempContacts
			Delete from personaldetails where PNr in (select persnr from #tempcontacts);	
			Delete from PersEmployee where PersonId in (select persnr from #TempContacts);
			DELETE FROM BankAccount where PersID in (select persnr from #TempContacts);
			Delete from BesRepertoire where PersNr in (select persnr from #TempContacts);
			delete from BodyMeasurementData where BodyMeasurementId in (select BodyMeasurementId from BodyMeasurements v where  v.PersonId in (select persnr from #TempContacts));
			delete from BodyMeasurements  where  PersonId in (select persnr from #TempContacts);
			update CheckListItem set PersonId= null where personid in (select persnr from #tempcontacts);
			update CheckListItemTemplate set PersonId = null where personid in (select persnr from #tempcontacts);
			delete from MailingListEntries where PersonId in (select persnr from #tempcontacts);
			delete from PersKom where persnr in (select persnr from #tempcontacts);
			delete from PersAdresse where persnr in (select persnr from #tempcontacts);
			delete from PersAgentur where PersNr in (select persnr from #tempcontacts) or ChildPersNr in (select persnr from #tempcontacts);
			delete from PersDataCategoryData where PersonId in (select persnr from #tempcontacts);
			delete from PersEmployee where personid in (select persnr from #tempcontacts);
			delete from PersonalDetails where PNr in (select persnr from #tempcontacts);
			delete from PersZusatzDaten where PersNr in (select persnr from #tempcontacts);
			delete from PersonAttachments where PersonId in (select persnr from #tempcontacts);
			delete from PersonalNotizen where PersNr in (select persnr from #tempcontacts);
			Delete from PersonalHonorar where Persnr in (select persnr from #tempcontacts);
			delete from Qualification_Person where PersonId in (select persnr from #tempcontacts);
			delete from ResourceObjects where PersonId in (select persnr from #tempcontacts);
			delete from PersonModulGroupPermission where PersonId in (select persnr from #tempcontacts);
			delete from XHDelBasicCast where PersonOldId in(select persnr from #tempcontacts) or PersonNewId in (select persnr from #tempcontacts);
			delete from persh where persnr in (select persnr from #tempcontacts);

			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempContacts
		END
		DROP TABLE #TempContacts	
End
GO

GRANT EXECUTE ON dbo.ClearOldContacts to DataCleaningAdmin
go
--#endregion Personaldaten

--#endregion

--#region DH 20180625 Optimierung PersonalNotizenTyp
DropColumn 'PersonalNotizenTyp', 'PersonalnotizenTypts'

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.UQ_PersonalNotizenTyp_Bezeichnung') AND type = 'K') 
BEGIN
	ALTER TABLE PersonalNotizenTyp 
	ADD CONSTRAINT UQ_PersonalNotizenTyp_Bezeichnung UNIQUE (Bezeichnung);   
END
GO
--#endregion Optmierung Personalnotizentyp

--#region DH 20180709 Bugfix Vorstellungszählung
ALTER PROCEDURE dbo.GetActivityPerformanceNumber
	@productionId INT,
	@seasonStart DATE,
	@date DATE,
	@startTime SMALLDATETIME,
	@variantId INT
AS
		SELECT COUNT(*) AS Anz
		FROM AufführgTabelle AS a
			INNER JOIN AuffTypen AS At ON a.Art = At.AuffTNr
		WHERE a.Snr = @productionId 
		AND At.KatNr = 0
		AND a.VariantId = @variantId
		AND a.Status>0
		AND ((a.Datum < @date AND a.Datum >= @seasonStart) OR (a.Datum = @date AND UhrBeg <= @startTime))
GO
--#endregion Bugfix Vorstellungszählung

--#endregion (4.182.x)

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

--#region SH 2018-07-23 DF_VertragRolle_VertragsNr und DF_VertragRolle_RolleId entfernen und RolleId auf NULL setzen
IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_VertragRolle_VertragsNr')
BEGIN
	PRINT('Dropping constraint DF_VertragRolle_VertragsNr...')
	ALTER TABLE [dbo].[VertragRolle] DROP CONSTRAINT [DF_VertragRolle_VertragsNr]
END
GO

IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_VertragRolle_RolleId')
BEGIN
	PRINT('Dropping constraint DF_VertragRolle_RolleId...')
	ALTER TABLE [dbo].[VertragRolle] DROP CONSTRAINT [DF_VertragRolle_RolleId]
END
GO

PRINT('Updating role contracts using role id 0 with a regular production to use NULL instead...')
UPDATE VertragRolle SET RolleId = NULL
WHERE
	RolleId = 0
	AND ProductionId IS NOT NULL
	AND RolleId NOT IN (SELECT bs.ID FROM BesetzungStd bs WHERE bs.SNr = ProductionId)
GO

UPDATE AuffTypen SET Category = 50 WHERE Category = 0 AND AufftKurz = 'TAufg'
--#endregion

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

--#region ----------- 4.183.x ---------------------------------

--#region bm 180625 Rapportspalte Sichtbarkeit jetzt enum

IF EXISTS (SELECT o.id FROM dbo.sysobjects o  INNER JOIN syscolumns c ON c.id = o.id WHERE o.id = OBJECT_ID('[dbo].[RapportSpalte]') AND c.name = 'NoPrintIfEmpty')
BEGIN
	--Default-Constraint löschen
	declare @DefaultName varchar(400)
	declare @sql varchar(400)
	SET @sql	=	'Alter Table RapportSpalte drop constraint '
    Print 'SQL Set'
	set @DefaultName =(
	select object_name(cdefault) as 'DefaultName' from syscolumns
	where [id] = object_id('RapportSpalte')
	and [name] = 'NoPrintIfEmpty');
	
	SET @sql	=	@sql + @DefaultName
	exec(@sql)
	Print 'Constraint '+@DefaultName + ' Dropped';
	EXEC ('UPDATE RapportSpalte SET NoPrintIfEmpty = 0 WHERE NoPrintIfEmpty IS NULL')
	ALTER TABLE rapportspalte ALTER COLUMN NoPrintIfEmpty TINYINT NOT NULL
	EXEC sp_rename 'RapportSpalte.NoPrintIfEmpty', 'Visibility', 'COLUMN'
	Print 'column  NoPrintIfEmpty renamed to Visibility '
END
GO
--#endregion

--#region DH20180627 Unique Index für CostCenter
--Index wird nur angelegt, wenn keine 


IF NOT EXISTS (select * from sys.indexes i where i.[name]=N'UQ_CostCenter_CostCenterNo') 
BEGIN
	IF NOT EXISTS (select count(c.CostCenterNo) from dbo.CostCenter c group by CostCenterno having count(CostCenterNo)>1) 
		BEGIN
			CREATE UNIQUE NONCLUSTERED INDEX [UQ_CostCenter_CostCenterNo] ON [dbo].[CostCenter] (CostCenterNo)
			Print 'Index [UQ_CostCenter_CostCenterNo] erstellt.'
		END
	ELSE
		BEGIN
			Print '#### Die Kostenstellennummer ist nicht eindeutig! #### '
		END
END

--#endregion DH20180627 Unique Index für Costcenter

--#region DH20180627 Unique Trigger für Costunits
IF NOT EXISTS (SELECT * FROM sys.objects s WHERE s.type='Tr' and s.[name]='TR_Insert_costunitno')
BEGIN
	EXEC ('
		CREATE TRIGGER TR_Insert_costunitno ON dbo.Costunit AFTER INSERT,UPDATE 
		AS 
		BEGIN
			DECLARE @UniqueInfo smallint
			SELECT @UniqueInfo = CONVERT(smallint,Werttext) FROM Settings WHERE form = ''CostUnitSettings'' AND Control = ''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 Costunit 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 Costunit c inner join inserted i ON c.costunitno=i.costunitno  GROUP BY c.costunitno HAVING COUNT(c.costunitno)>1)
					ROLLBACK TRANSACTION
				END
			
		END')
	Print 'Trigger TR_Insert_costunitno Created'
	Declare @default varchar(1)
	select @default= case 
		when 
			exists (SELECT Count(c.costunitno) FROM Costunit c GROUP BY c.costunitno,c.BookableFrom HAVING COUNT(c.costunitno)>1) 
			then '0'
		when
			exists (SELECT Count(c.costunitno) FROM Costunit c GROUP BY c.costunitno HAVING COUNT(c.costunitno)>1)
			then '1'
		else
			'2' end

	insert into Settings(Form,Control,WertText,IsGlobalSetting) Values('CostUnitSettings','KeepCostUnitNoUnique',@default,1 )
	print case when @default='0' then 'allow all duplicates' when @default='1' then 'allows duplicates in period' else 'All no duplicates' end
END
GO
--#endregion DH20180627 Unique Index für Costunits

--#region SH 2018-06-25 BudgetHypothesis Spalten in Budgets
--neue spalten anlegen
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Budgets') AND [name] = 'BudgetHypotheses1')
BEGIN
	PRINT('Adding columns Budgets.BudgetHypotheses1 - 5 ...')
	ALTER TABLE dbo.Budgets ADD BudgetHypotheses1 DECIMAL(9,2) SPARSE
	ALTER TABLE dbo.Budgets ADD BudgetHypotheses2 DECIMAL(9,2) SPARSE
	ALTER TABLE dbo.Budgets ADD BudgetHypotheses3 DECIMAL(9,2) SPARSE
	ALTER TABLE dbo.Budgets ADD BudgetHypotheses4 DECIMAL(9,2) SPARSE
	ALTER TABLE dbo.Budgets ADD BudgetHypotheses5 DECIMAL(9,2) SPARSE
END
GO
--werte aus BudgetReference übertragen
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Budgets') AND [name] = 'BudgetReference')
BEGIN
	PRINT('Moving values from Budgets.BudgetReference to Budgets.BudgetHypotheses1 ...')
	EXEC ('UPDATE Budgets SET BudgetHypotheses1 = CONVERT(DECIMAL(9,2),REPLACE(b.BudgetReference, '','',''.'')) FROM Budgets b '+
	'WHERE b.BudgetReference IS NOT NULL AND b.BudgetReference <> '''' AND b.BudgetReference <> ''0''')

	PRINT('Renaming column Budgets.BudgetReference ...')
	EXEC sp_rename 'dbo.Budgets.BudgetReference', 'BudgetReferenceX', 'COLUMN'
END
GO

--werte aus Prevision übertragen
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Budgets') AND [name] = 'Prevision')
BEGIN
	PRINT('Moving values from Budgets.Prevision to Budgets.BudgetHypotheses2 ...')
	EXEC ('UPDATE Budgets SET BudgetHypotheses2 = CONVERT(DECIMAL(9,2),REPLACE(b.Prevision, '','',''.'')) FROM Budgets b
	WHERE b.Prevision IS NOT NULL AND b.Prevision <> '''' AND b.Prevision <> ''0''')

	PRINT('Renaming column Budgets.Prevision ...')
	EXEC sp_rename 'dbo.Budgets.Prevision', 'PrevisionX', 'COLUMN'
END
GO
--#endregion

--#region SH 2018-06-25 neue Spalte Description_EN in BudgetItems
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('BudgetItem') AND [name] = 'BudgetItemDescription_EN')
BEGIN
	PRINT('Adding column BudgetItem.BudgetItemDescription_EN ...')
	ALTER TABLE dbo.BudgetItem ADD BudgetItemDescription_EN VARCHAR(50) SPARSE NULL
END
GO
--#endregion

--#region BM 20180725 Neue Tabelle für Dienst-Kassenanordnungspositionen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DutyCashCommandPos]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	PRINT 'Create Table DutyCashCommandPos';
	CREATE TABLE DutyCashCommandPos(
		DutyCashCommandPosId int IDENTITY(1,1) NOT NULL,
		CashCommandId int NOT NULL,
		WageTypeId int NOT NULL,
		DutyMark varchar(5) NOT NULL,
		StartDate DATE NOT NULL,
		EndDate DATE NOT NULL,
		DutyValue float NOT NULL CONSTRAINT DF_DutyCashCommandPos_DutyValue DEFAULT 0,
		[Description] varchar(1000) SPARSE NULL,
		Remarks varchar(100) SPARSE NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_DutyCashCommandPos PRIMARY KEY CLUSTERED (DutyCashCommandPosID) ON [PRIMARY],
		CONSTRAINT FK_CashCommand_DutyCashCommandPos FOREIGN KEY(CashCommandID) REFERENCES CashCommand (CashCommandId) ON DELETE CASCADE,
		CONSTRAINT FK_WageType_DutyCashCommandPos FOREIGN KEY(WageTypeID) REFERENCES Wagetype (WageTypeId) ON DELETE NO ACTION
	)
END
GO

IF EXISTS(SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID('[dbo].[AbDutyCashCommandPos]'))
BEGIN
	DROP VIEW [dbo].[AbDutyCashCommandPos]
END
GO

CREATE VIEW [dbo].[AbDutyCashCommandPos]
AS
	SELECT  ccp.*  FROM  DutyCashCommandPos  AS ccp WHERE ccp.CashCommandId IN
	   (SELECT cc.CashCommandId
		FROM CashCommand AS cc INNER JOIN UserGruppe ON cc.ModulGroupId = UserGruppe.GruppeID 
		INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 7)
GO

GRANT SELECT ON [AbDutyCashCommandPos] TO [public]
GO

IF EXISTS(SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID('[dbo].[AbDutyCashCommandPos_Update]'))
BEGIN
	DROP VIEW [dbo].[AbDutyCashCommandPos_Update]
END
GO

CREATE VIEW [dbo].[AbDutyCashCommandPos_Update]
AS
	SELECT  ccp.*  FROM  DutyCashCommandPos  AS ccp WHERE ccp.CashCommandId IN
	   (SELECT cc.CashCommandId
		FROM CashCommand AS cc INNER JOIN UserGruppe ON cc.ModulGroupId = UserGruppe.GruppeID 
		INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 7
		AND UserGruppe.Schreiben = 1)
	WITH CHECK OPTION
GO

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

--#endregion

--#region 20180809
IF NOT EXISTS (SELECT * FROM sys.columns AS c WHERE c.object_id = object_id('Zyklen') and c.name = 'DepartmentId')
BEGIN
	Print 'Create WorkingTimeModel DepartmentId'
	ALTER TABLE Zyklen ADD DepartmentId INT NULL
	ALTER TABLE dbo.Zyklen WITH CHECK ADD CONSTRAINT FK_WorkingTimeModel_Department FOREIGN KEY(DepartmentId)
		REFERENCES dbo.DienstplanArtenTabelle (DienstplanArtenId)
	ALTER TABLE dbo.Zyklen CHECK CONSTRAINT FK_WorkingTimeModel_Department
END
GO

--Ungezählter Urlaub wird "Abwesend"
UPDATE [Status] SET StatusArt = 15 WHERE StatusArt = 9
GO

IF NOT EXISTS (SELECT * FROM sys.columns AS c WHERE c.object_id = object_id('DienstplanArtenTabelle') AND c.name = 'HeaderPrintSettings')
BEGIN
	Print 'Create DienstplanArtenTabelle HeaderSettings'
	ALTER TABLE DienstplanArtenTabelle ADD HeaderPrintSettings XML NULL
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_DemandModell_TimeAccount') AND type = 'F')
BEGIN
	Print ('create FK_DemandModell_TimeAccount')
	UPDATE VertragsVorlagen SET UrlaubsberechnungsModellID = NULL WHERE UrlaubsberechnungsModellID IN (SELECT UrlaubsberechnungsModellID FROM UrlaubsberechnungsModell WHERE TimeAccountId NOT IN (SELECT ZeitKtoNr FROM Zeitkonten))
	UPDATE VertragsVorlagen SET JubileeModellId = NULL WHERE JubileeModellId IN (SELECT UrlaubsberechnungsModellID FROM UrlaubsberechnungsModell WHERE TimeAccountId NOT IN (SELECT ZeitKtoNr FROM Zeitkonten))

	DELETE FROM UrlaubsberechnungsModell WHERE TimeAccountId NOT IN (SELECT ZeitKtoNr FROM Zeitkonten)
	
	ALTER TABLE dbo.UrlaubsberechnungsModell WITH CHECK ADD CONSTRAINT FK_DemandModell_TimeAccount FOREIGN KEY(TimeAccountId)
		REFERENCES dbo.Zeitkonten (ZeitKtoNr) 
	ALTER TABLE dbo.UrlaubsberechnungsModell CHECK CONSTRAINT FK_DemandModell_TimeAccount
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.ACC_USER_ZR') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) DROP TABLE ACC_USER_ZR

IF NOT EXISTS (SELECT * FROM sys.sysobjects dc WHERE dc.name = 'CK_SecondaryPersons_SelfReferencingCheck')
BEGIN
	Print 'Create CK_SecondaryPersons_SelfReferencingCheck'
	DELETE FROM PersAgentur WHERE ChildPersNr = PersNr
	ALTER TABLE PersAgentur WITH CHECK ADD  CONSTRAINT CK_SecondaryPersons_SelfReferencingCheck CHECK  (([ChildPersNr]<>[PersNr]))
	ALTER TABLE PersAgentur CHECK CONSTRAINT CK_SecondaryPersons_SelfReferencingCheck
END
GO
IF EXISTS (SELECT * FROM sys.sysobjects dc WHERE dc.name = 'CK_StatusZeitR_Period')
	ALTER TABLE StatusZeitR DROP CONSTRAINT CK_StatusZeitR_Period
GO

IF NOT EXISTS (SELECT * FROM sys.sysobjects dc WHERE dc.name = 'CK_PersonStatus_PeriodCheck')
BEGIN
	Print 'Create CK_PersonStatus_PeriodCheck'
	DELETE FROM StatusZeitR WHERE Von >'30000101' or bis > '30000101' Or Von <'19000101' or bis < '19000101'
	UPDATE StatusZeitR SET Von = Bis, UhrBeginn = UhrEnde WHERE CONVERT(DATETIME, [Von]) + ISNULL([UhrBeginn], 0) > CONVERT(DATETIME, [Bis]) + ISNULL([UhrEnde], 1)
	ALTER TABLE StatusZeitR WITH CHECK ADD  CONSTRAINT CK_PersonStatus_PeriodCheck CHECK ((CONVERT(DATETIME, [Von]) + ISNULL([UhrBeginn], 0) <= CONVERT(DATETIME, [Bis]) + ISNULL([UhrEnde] ,1)))
	ALTER TABLE StatusZeitR CHECK CONSTRAINT CK_PersonStatus_PeriodCheck
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Person_Contract') AND type = 'F')
BEGIN
	Print ('create FK_Person_Contract')
	UPDATE StatusZeitR SET ContractId = NULL WHERE ContractId NOT IN (SELECT VertragsNr FROM Vertrag)
	
	ALTER TABLE dbo.StatusZeitR WITH CHECK ADD CONSTRAINT FK_Person_Contract FOREIGN KEY(ContractId)
		REFERENCES dbo.Vertrag (VertragsNr) ON DELETE SET NULL
	ALTER TABLE dbo.StatusZeitR CHECK CONSTRAINT FK_Person_Contract

END
IF EXISTS (SELECT * FROM sys.sysobjects dc WHERE dc.name = 'DF_StatusZeitR_PersNr')
	ALTER TABLE StatusZeitR DROP CONSTRAINT DF_StatusZeitR_PersNr

IF EXISTS (SELECT * FROM sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersAgentur') AND o.Name = 'IX_PersNr') 
BEGIN
	Print ('create IX_SecondaryPersons_PersonId')
	DROP INDEX PersAgentur.IX_PersNr
	ALTER TABLE PersAgentur ALTER COLUMN PersNr INT NOT NULL
	CREATE INDEX IX_SecondaryPersons_PersonId ON PersAgentur (PersNr)
END
GO
IF NOT EXISTS (SELECT * FROM sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersAgentur') AND o.Name = 'IX_SecondaryPersons_ChildPersonId') 
BEGIN
	Print ('create IX_SecondaryPersons_ChildPersonId')
	IF EXISTS (SELECT * FROM sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersAgentur') AND o.Name = 'IX_ChildPersNr')  DROP INDEX PersAgentur.IX_ChildPersNr
	ALTER TABLE PersAgentur ALTER COLUMN ChildPersNr INT NOT NULL
	CREATE INDEX IX_SecondaryPersons_ChildPersonId ON PersAgentur (ChildPersNr)

	UPDATE PersAgentur SET Schreiben = 0 WHERE Schreiben IS NULL
	ALTER TABLE PersAgentur ALTER COLUMN Schreiben BIT NOT NULL
	ALTER TABLE PersAgentur ADD CONSTRAINT DF_SecondaryPerson_WriteLetter DEFAULT 0 FOR Schreiben

	UPDATE PersAgentur SET Sort = 0 WHERE Sort IS NULL
	ALTER TABLE PersAgentur ALTER COLUMN Sort SMALLINT NOT NULL
	ALTER TABLE PersAgentur ADD CONSTRAINT DF_SecondaryPerson_Sort DEFAULT 0 FOR Sort

	UPDATE PersAgentur SET Ansprechpartner = 0 WHERE Ansprechpartner IS NULL
	ALTER TABLE PersAgentur ALTER COLUMN Ansprechpartner SMALLINT NOT NULL
	ALTER TABLE PersAgentur ADD CONSTRAINT DF_SecondaryPerson_RelationType DEFAULT 0 FOR Ansprechpartner
END
GO

--#endregion

--#region DH 180820 Kategorien für Personenattachments in Tabelle ausgelagert
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PersonAttachmentCategories]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	PRINT 'Create Table PersonAttachmentCategories';
	CREATE TABLE PersonAttachmentCategories(
		PersonAttachmentCategoryId int IDENTITY(1,1) NOT NULL,
		Code Varchar(15) NOT NULL,
		Name Varchar(30) NOT NULL, 
		Description Varchar(1000) Sparse NULL,
		Sort INT NOT NULL Constraint DF_PersonAttachmentCategories_Sort Default 0,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_AttachmentCategories PRIMARY KEY CLUSTERED (PersonAttachmentCategoryId) ON [PRIMARY]);
	    CREATE UNIQUE NONCLUSTERED INDEX IX_PersonAttachmentCategories_Name ON PersonAttachmentCategories(Name) ON [Primary];
		 CREATE UNIQUE NONCLUSTERED INDEX IX_PersonAttachmentCategories_Code ON PersonAttachmentCategories(Code) ON [Primary];		
END
GO

PRINT 'Granting Permissions to PersonAttachmentCategories'
GRANT INSERT, UPDATE,DELETE ON PersonAttachmentCategories TO MasterAdmin
GO

GRANT SELECT ON PersonAttachmentCategories TO Public
go

IF EXISTS(SELECT p.Category FROM PersonAttachments p LEFT JOIN PersonAttachmentCategories pac ON p.Category=pac.PersonAttachmentCategoryId WHERE p.Category=1 AND pac.PersonAttachmentCategoryId is NULL)
BEGIN
	SET IDENTITY_INSERT PersonAttachmentCategories ON
	INSERT INTO PersonAttachmentCategories(PersonAttachmentCategoryId,Code,Name,Description,Sort,LM,UM,LC,UC)
	VALUES(1,'ProfilePicture','ProfilePicture','',1,getdate(),0,getdate(),0);
	SET IDENTITY_INSERT PersonAttachmentCategories OFF;
END
GO

IF EXISTS(SELECT p.Category FROM PersonAttachments p Left join PersonAttachmentCategories pac on p.Category=pac.PersonAttachmentCategoryId WHERE p.Category=2 AND pac.PersonAttachmentCategoryId is NULL)
BEGIN
	PRINT 'creating old categories'
	SET IDENTITY_INSERT PersonAttachmentCategories ON;
	INSERT INTO PersonAttachmentCategories(PersonAttachmentCategoryId,Code,Name,Description,Sort,LM,UM,LC,UC)
	VALUES(2,'Portrait','Portrait','',1,getdate(),0,getdate(),0);
	SET IDENTITY_INSERT PersonAttachmentCategories OFF;
END
GO

IF EXISTS(SELECT p.Category FROM PersonAttachments p Left join PersonAttachmentCategories pac on p.Category=pac.PersonAttachmentCategoryId WHERE p.Category=3 AND pac.PersonAttachmentCategoryId is NULL)
BEGIN
	SET IDENTITY_INSERT PersonAttachmentCategories ON;
	INSERT INTO PersonAttachmentCategories(PersonAttachmentCategoryId,Code,Name,Description,Sort,LM,UM,LC,UC)
	VALUES(3,'MeasurePicture','MeasurePicture','',1,getdate(),0,getdate(),0);
	SET IDENTITY_INSERT PersonAttachmentCategories OFF;
END
GO

IF EXISTS(SELECT p.Category FROM PersonAttachments p Left join PersonAttachmentCategories pac on p.Category=pac.PersonAttachmentCategoryId WHERE p.Category=4 AND pac.PersonAttachmentCategoryId is NULL)
BEGIN
	SET IDENTITY_INSERT PersonAttachmentCategories ON;
	INSERT INTO PersonAttachmentCategories(PersonAttachmentCategoryId,Code,Name,Description,Sort,LM,UM,LC,UC)
	VALUES(4,'Signature','Signature','',1,getdate(),0,getdate(),0);
	SET IDENTITY_INSERT PersonAttachmentCategories OFF;
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PersonAttachmentCategoryId' and o.id = OBJECT_ID(N'dbo.PersonAttachments'))
Begin
ALTER TABLE PersonAttachments ADD PersonAttachmentCategoryId int NULL
PRINT 'PersonAttachmentCategoryId created'
END
GO

IF EXISTS (SELECT AttachmentId FROM PersonAttachments WHERE PersonAttachmentCategoryId is NULL and Category is NOT NULL)
BEGIN
UPDATE PersonAttachments 
	SET PersonAttachmentCategoryId=Category;
PRINT 'PersonAttachmentCategories Set'
END
GO

IF EXISTS(SELECT personid,category, count(attachmentid) FROM personattachments WHERE Category is NOT NULL group by personid,Category having count(attachmentid)>1)
BEGIN
	UPDATE p
	SET Category = NULL  FROM personattachments p WHERE p.PersonAttachmentsId NOT in (select min(a.PersonAttachmentsId) FROM personattachments a group by a.category,a.PersonId ) or p.Category in (2,3)
PRINT 'Categories Set'
END 
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonAttachments_PersonAttachmentCategories') AND type = 'F') 
Begin
Alter Table PersonAttachments
	Add Constraint FK_PersonAttachments_PersonAttachmentCategories
	Foreign Key (PersonAttachmentCategoryId) References PersonAttachmentCategories(PersonAttachmentCategoryId);
END
GO

IF NOT EXISTS (select * from sys.objects where type = 'TR' and name = 'TR_PersonAttachments_UpdateCategory')
EXEC dbo.sp_executesql @statement = N'

CREATE TRIGGER [dbo].[TR_PersonAttachments_UpdateCategory]
   ON [dbo].[PersonAttachments]
   AFTER UPDATE
AS BEGIN
    SET NOCOUNT ON;
    IF UPDATE (Category) 
    BEGIN
        UPDATE P
        SET Category = Null          
        FROM PersonAttachments P INNER JOIN inserted I 
        ON P.PersonId=i.PersonId And p.Category=I.Category
        WHERE p.PersonAttachmentsId <> I.PersonAttachmentsId
    END 
END;
'
GO

--#endregion Personattachmentcategories

--#region SH 2018-08-01 WebCalendarProfiles in eigene Tabelle auslagern
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.WebCalendarProfiles') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	PRINT('Creating table WebCalendarProfiles...')
	CREATE TABLE dbo.WebCalendarProfiles (
		[WebCalendarProfileId] INT IDENTITY(1,1) NOT NULL,
		[PublicProfileId] CHAR(36) NOT NULL, --GUID ALS String
		[Name] VARCHAR(50) NOT NULL,
		[Description] VARCHAR(255) NULL,
		[WebCalendarDataProvider] VARCHAR(80) NOT NULL,
		[WebCalendarDataProviderSettings] XML NULL,
		[OwningUserId] INT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		CONSTRAINT PK_WebCalendarProfiles PRIMARY KEY NONCLUSTERED ([WebCalendarProfileId]) ON [PRIMARY],
		CONSTRAINT UQ_WebCalendarProfiles_PublicProfileId UNIQUE ([PublicProfileId]) ON [PRIMARY],
		CONSTRAINT FK_WebCalendarProfiles_Users FOREIGN KEY([OwningUserId]) REFERENCES [UserPw] ([UserID]) ON DELETE CASCADE,
	) ON [PRIMARY]	
END
GO

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

IF EXISTS (SELECT * FROM Settings s WHERE s.Form = 'WebCalendarProfiles')
AND NOT EXISTS(SELECT * FROM WebCalendarProfiles w WHERE w.[WebCalendarDataProvider] = 'PublicActivityWebCalendarDataProvider')
BEGIN

	PRINT('Moving web calendar profile settings from Settings to WebCalendarProfiles...')

	DECLARE @WebCalendars TABLE (
		OriginalProfileData XML,
		NewProfileData XML,
		[Name] VARCHAR(50),
		[Description] VARCHAR(255),
		[PublicProfileId] CHAR(36),
		ActivityFilter VARCHAR(MAX),
		CollectiveNodeNames VARCHAR(MAX),
		BodyContentSettingPlanId VARCHAR(MAX)
	)

	--settings als xml in @WebCalendars einfuegen
	INSERT INTO @WebCalendars (OriginalProfileData, NewProfileData)
	SELECT CAST([WertText] AS XML), CAST('<PublicActivityWebCalendarSettings />' AS XML) FROM settings WHERE [Form] = 'WebCalendarProfiles'
	

	--xml werte in die anderen spalten auflösen
	UPDATE @WebCalendars 
	SET Name = OriginalProfileData.value('(/WebCalendarProfile/@Name)[1]', 'varchar(50)')
	   ,Description = OriginalProfileData.value('(/WebCalendarProfile/Description)[1]', 'varchar(255)')
	   ,PublicProfileId = OriginalProfileData.value('(/WebCalendarProfile/@Id)[1]', 'char(36)')
	   ,ActivityFilter = CAST(OriginalProfileData.query('/WebCalendarProfile/ActivityFilter') AS VARCHAR(MAX))
	   ,CollectiveNodeNames = CAST(OriginalProfileData.query('/WebCalendarProfile/CollectiveNodeNames') AS VARCHAR(MAX))
	   ,BodyContentSettingPlanId = CAST(OriginalProfileData.query('/WebCalendarProfile/BodyContentSettingPlanId') AS VARCHAR(MAX))
	WHERE OriginalProfileData IS NOT NULL


	--neuen xml werte aktualisieren
	UPDATE @WebCalendars SET [NewProfileData]
	= CAST('<PublicActivityWebCalendarSettings>'
	 + ISNULL(ActivityFilter, '')
	 + ISNULL(CollectiveNodeNames, '')
	 + ISNULL(BodyContentSettingPlanId, '')
	 +'</PublicActivityWebCalendarSettings >' AS XML) WHERE OriginalProfileData IS NOT NULL

	 --daten in neue tabelle einfuegen
	INSERT INTO WebCalendarProfiles (PublicProfileId, Name, Description, WebCalendarDataProvider, WebCalendarDataProviderSettings, LM, UM, LC, UC)
	SELECT PublicProfileId, Name, Description, 'PublicActivityWebCalendarDataProvider', NewProfileData, GETDATE(), -1, GETDATE(), -1 FROM @WebCalendars

	--alten einstellungen umbenennen
	UPDATE Settings SET Form = 'WebCalendarProfiles_X' WHERE Form = 'WebCalendarProfiles'
END
GO

--#endregion (SH 2018-08-01 WebCalendarProfiles in eigene Tabelle auslagern)

--#region TK 2018-09-03
IF NOT EXISTS (SELECT * FROM sys.indexes i WHERE i.[name] = N'UQ_BudgetItem_BudgetItemNo') 
	BEGIN
	IF NOT EXISTS (SELECT COUNT(c.BudgetItemNo) FROM dbo.BudgetItem c GROUP BY BudgetItemNo HAVING COUNT(BudgetItemNo)>1)  
		BEGIN
			CREATE UNIQUE NONCLUSTERED INDEX UQ_BudgetItem_BudgetItemNo ON BudgetItem (BudgetItemNo)
			Print 'Index [UQ_BudgetItem_BudgetItemNo] erstellt.'
		END
	ELSE
		BEGIN
			Print '#### Die Haushaltstitelnummer ist nicht eindeutig! / The budget item number is not unique! #### '
		END
END
--#endregion

--#region DH 2018-09.07 Reformationstag ab 2018 für Niedersachsen, Bremen, Schleswig Holstein und Hamburg nachtragen.

IF EXISTS (SELECT * FROM Settings s WHERE s.Form = 'Adresse' AND s.Control = 'Bundesland' AND s.WertText in ('<Land>Niedersachsen</Land>','<Land>Hamburg</Land>','<Land>Bremen</Land>','<Land>Schleswig_Holstein</Land>'))
BEGIN
	INSERT INTO Feiertage (FDatum, FtBez, LM, UM, LC, UC, Ftart)
	SELECT DATEADD(day,31-3,f_old.FDatum), 'Reformationstag', GETDATE(), 0, GETDATE(), 0, 3 
	FROM Feiertage f_old 
	WHERE DATEPART(YEAR,f_old.FDatum)>2017 AND DATEPART(month,f_old.fdatum)=10 AND Datepart(day,f_old.FDatum)=3 
	AND NOT EXISTS (SELECT f.FeiertagID FROM Feiertage f WHERE FDatum = DATEADD(day,31-3,f_old.FDatum));
END
GO
--#endregion DH 2018-09-07

--#endregion (4.183.x)

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

--#region 2018-10-01
IF EXISTS (SELECT * FROM  sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersKat') AND o.Name = 'Sort')
	DROP INDEX PersKat.Sort
GO
IF NOT EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Sort' and o.id = OBJECT_ID(N'PersKat') AND c.isnullable = 0)
BEGIN
	PRINT('PersKat.Sort NOT NULL...')
	UPDATE PersKat Set Sort = 0 WHERE Sort IS NULL 
	ALTER TABLE PersKat ALTER COLUMN Sort SMALLINT NOT NULL
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects so WHERE so.id = OBJECT_ID(N'dbo.DF_PersKat_Sort'))
BEGIN
	ALTER TABLE PersKat ADD CONSTRAINT DF_PersKat_Sort DEFAULT 0 FOR Sort
END
GO
--#endregion 


IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 183 OR (Minor = 183 AND Build < 101)))))
BEGIN
	DELETE FROM Settings where form = 'rapportprint' and [control] = 'RapportPrintSettings'
END
GO

--#region 2018-10-22 Feldtyp von Standardbesetzung an Abendbesetzung angeglichen
IF EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'BesSort' and o.id = OBJECT_ID(N'BesetzungStdSoliTabelle') AND c.xtype = 56)
BEGIN
	Print 'BasicCast -BesSort SMALLINT'
	IF EXISTS (SELECT * FROM sys.default_constraints dc WHERE dc.name = 'DF_BesetzungStdSoliTabelle_Bessort') ALTER TABLE BesetzungStdSoliTabelle DROP CONSTRAINT DF_BesetzungStdSoliTabelle_Bessort
	UPDATE BesetzungStdSoliTabelle SET BesSort = 0 WHERE BesSort IS NULL
	ALTER TABLE BesetzungStdSoliTabelle ALTER COLUMN BesSort SMALLINT NOT NULL
	ALTER TABLE BesetzungStdSoliTabelle ADD CONSTRAINT DF_BasicCast_Sort DEFAULT 0 FOR BesSort
END
GO
--#endregion 

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

--#region ----------- 4.184.x ---------------------------------

--#region TK 2018-08-30 UserGruppe und Not null

IF NOT EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.UserGruppe') AND o.Name = 'IX_Group_GroupIdUserIdPermissionArea')
BEGIN
	Print 'create IX_Group_GroupIdUserIdPermissionArea'
	DELETE FROM UserGruppe WHERE UserId IS NULL OR GruppeId IS NULL
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.UserGruppe') AND o.Name = 'PK_GruppeID') DROP INDEX UserGruppe.PK_GruppeId
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.UserGruppe') AND o.Name = 'PK_UserID') DROP INDEX UserGruppe.PK_UserId
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.UserGruppe') AND o.Name = 'iGruppeIDUserIDBerechtigungsbereichID') DROP INDEX UserGruppe.iGruppeIDUserIDBerechtigungsbereichId
	
	ALTER TABLE UserGruppe ALTER COLUMN UserId INT NOT NULL
	ALTER TABLE UserGruppe ALTER COLUMN GruppeId INT NOT NULL

	CREATE NONCLUSTERED INDEX IX_Group_GroupId ON UserGruppe	(GruppeId)
	CREATE NONCLUSTERED INDEX IX_Group_UserId ON UserGruppe	(UserId)
	CREATE UNIQUE NONCLUSTERED INDEX IX_Group_GroupIdUserIdPermissionArea ON UserGruppe	(GruppeId ,UserId, BerechtigungsbereichId)
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.DF_UserGruppe_WritePermission') AND type = 'D') 
BEGIN
	Print 'create DF_UserGruppe_WritePermission'
	UPDATE UserGruppe SET Schreiben = 0 WHERE Schreiben IS NULL
	ALTER TABLE UserGruppe ALTER COLUMN Schreiben BIT NOT NULL
	ALTER TABLE UserGruppe ADD CONSTRAINT DF_UserGruppe_WritePermission DEFAULT 0 FOR Schreiben
END
GO
IF NOT EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.ZR') AND o.Name = 'IX_Stages_Name')
BEGIN
	Print 'create IX_Stages_Name'
	UPDATE UserGruppe SET IsInherited = 0 WHERE IsInherited IS NULL
	ALTER TABLE UserGruppe ALTER COLUMN IsInherited BIT NOT NULL
	
	UPDATE UserForAccess SET IsInherited = 0 WHERE IsInherited IS NULL
	ALTER TABLE UserForAccess ALTER COLUMN IsInherited BIT NOT NULL
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Zr') AND o.Name = 'ZRBez') DROP INDEX zr.ZRBez
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Zr') AND o.Name = 'PK_ZRBez') DROP INDEX zr.PK_ZRBez
	UPDATE Zr SET ZRBez = ZRkurz WHERE ZRBez IS NULL
	ALTER TABLE Zr ALTER COLUMN ZRBez VARCHAR(60) NOT NULL
	EXECUTE PrepareUniqueColumnIndex N'Zr',N'ZrBez',N'Zrnr',N'VARCHAR(60)';
	CREATE UNIQUE NONCLUSTERED INDEX IX_Stages_Name ON ZR (ZRBez)
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.DF_Stages_Sort') AND type = 'D') 
BEGIN
	Print 'create DF_Stages_Sort'
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Zr') AND o.Name = 'Sort') DROP INDEX zr.Sort
	EXEC DropDefaultConstraint 'zr', 'Sort'
	UPDATE Zr SET Sort = 0 WHERE Sort IS NULL
	ALTER TABLE Zr ALTER COLUMN Sort INT NOT NULL
	CREATE NONCLUSTERED INDEX IX_Stages_Sort ON ZR (Sort)
	ALTER TABLE zr ADD CONSTRAINT DF_Stages_Sort DEFAULT 0 FOR Sort
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.DF_Stages_Gastspiel') AND type = 'D') 
BEGIN
	Print 'create DF_Stages_Gastspiel'
	UPDATE Zr SET Gastspiel = 0 WHERE Gastspiel IS NULL
	ALTER TABLE Zr ALTER COLUMN Gastspiel TINYINT NOT NULL
	ALTER TABLE zr ADD CONSTRAINT DF_Stages_Gastspiel DEFAULT 0 FOR Gastspiel
END
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'UserGruppeTS' and o.id = OBJECT_ID(N'dbo.UserGruppe'))
BEGIN
	ALTER TABLE UserGruppe DROP COLUMN UserGruppeTS
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PremDat' and o.id = OBJECT_ID(N'dbo.Stücke') and c.xtype = 40)
BEGIN
	Print 'create alter PremDat'
	EXEC DropDefaultConstraint 'Stücke', 'Dauer'
	EXEC DropDefaultConstraint 'Stücke', 'Begin'
	
	UPDATE Stücke SET [Begin] = '00:00' WHERE [Begin] IS NULL
	UPDATE Stücke SET Dauer = '00:00' WHERE Dauer IS NULL
	UPDATE Stücke SET dauer = CONVERT(CHAR(5), dauer, 108)
	UPDATE Stücke SET [Begin] = CONVERT(CHAR(5), [Begin], 108)

	ALTER TABLE Stücke ALTER COLUMN [Begin] SMALLDATETIME NOT NULL
	ALTER TABLE Stücke ALTER COLUMN Dauer SMALLDATETIME NOT NULL
	ALTER TABLE Stücke ADD CONSTRAINT DF_Productions_DefaultPerformaceStartTime DEFAULT '00:00' FOR Dauer 
	ALTER TABLE Stücke ADD CONSTRAINT DF_Productions_DefaultPerformaceDuration DEFAULT '00:00' FOR [Begin] 

	ALTER TABLE Stücke ALTER COLUMN PremDat DATE  NULL
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.DF_ProductionsDetails_PublishCastProductionInWeb') AND type = 'D') 
BEGIN
	Print 'create DF_ProductionsDetails_PublishCastProductionInWeb'
	EXEC DropDefaultConstraint 'StückeDetails', 'VonDru'
	EXEC DropDefaultConstraint 'StückeDetails', 'BisZeit'
	EXEC DropDefaultConstraint 'StückeDetails', 'AnzahlAuff'
	EXEC DropDefaultConstraint 'StückeDetails', 'wwwBes'
	EXEC DropDefaultConstraint 'StückeDetails', 'WebPublish'

	UPDATE StückeDetails SET VonDru = 0 WHERE VonDru IS NULL
	UPDATE StückeDetails SET BisZeit = 0 WHERE BisZeit IS NULL
	UPDATE StückeDetails SET AnzahlAuff = 0 WHERE AnzahlAuff IS NULL
	UPDATE StückeDetails SET wwwBes = 0 WHERE wwwBes IS NULL
	UPDATE StückeDetails SET WebPublish = 0 WHERE WebPublish IS NULL

	ALTER TABLE StückeDetails ALTER COLUMN VonDru BIT NOT NULL
	ALTER TABLE StückeDetails ALTER COLUMN BisZeit BIT NOT NULL
	ALTER TABLE StückeDetails ALTER COLUMN AnzahlAuff SMALLINT NOT NULL
	ALTER TABLE StückeDetails ALTER COLUMN wwwBes BIT NOT NULL
	ALTER TABLE StückeDetails ALTER COLUMN WebPublish BIT NOT NULL

	ALTER TABLE StückeDetails ADD CONSTRAINT DF_ProductionsDetails_PrintPerformanceStartTime DEFAULT 0 FOR VonDru 
	ALTER TABLE StückeDetails ADD CONSTRAINT DF_ProductionsDetails_PrintPerformanceEndTime DEFAULT 0 FOR BisZeit 
	ALTER TABLE StückeDetails ADD CONSTRAINT DF_ProductionsDetails_PerformancesBefore DEFAULT 0 FOR AnzahlAuff 
	ALTER TABLE StückeDetails ADD CONSTRAINT DF_ProductionsDetails_PublishCastInWeb DEFAULT 0 FOR wwwBes 
	ALTER TABLE StückeDetails ADD CONSTRAINT DF_ProductionsDetails_PublishCastProductionInWeb DEFAULT 0 FOR WebPublish
	ALTER TABLE StückeDetails ALTER COLUMN VonDru BIT NOT NULL
	ALTER TABLE StückeDetails ALTER COLUMN BisZeit  BIT NOT NULL
	ALTER TABLE StückeDetails ALTER COLUMN AnzahlAuff SMALLINT NOT NULL
	ALTER TABLE StückeDetails ALTER COLUMN wwwBes  BIT NOT NULL
	ALTER TABLE StückeDetails ALTER COLUMN WebPublish  BIT NOT NULL
END
GO
DropDefaultConstraint 'StückeDetails', 'Snr'
GO
DropColumn 'StückeDetails', 'DispoColorVst'
GO
DropColumn 'StückeDetails', 'DispoColorPro'
GO
DropColumn 'StückeSPZ', 'Budget_Werk'
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.DF_ActivityPressText_DoNotPublish') AND type = 'D') 
BEGIN
	Print ('create DF_ActivityPressText_DoNotPublish')
	EXEC DropDefaultConstraint 'PresseText', 'VonDru'
	EXEC DropDefaultConstraint 'PresseText', 'BisZeit'
	EXEC DropDefaultConstraint 'PresseText', 'KeinDruck'

	UPDATE PresseText SET VonDru = 0 WHERE VonDru IS NULL
	UPDATE PresseText SET BisZeit = 0 WHERE BisZeit IS NULL
	UPDATE PresseText SET KeinDruck = 0 WHERE KeinDruck IS NULL

	ALTER TABLE PresseText ALTER COLUMN KeinDruck BIT NOT NULL
	ALTER TABLE PresseText ADD CONSTRAINT DF_ActivityPressText_DoNotPublish DEFAULT 0 FOR KeinDruck 
END
GO
IF NOT EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Ring') AND o.Name = 'IX_SubscriptionInSeason_Season')
BEGIN
	Print ('create IX_SubscriptionInSeason_Season')
	EXEC DropDefaultConstraint 'Ring', 'MAfR'
	ALTER TABLE Ring DROP COLUMN PreisNr
	ALTER TABLE Ring DROP COLUMN MAfR

	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Ring') AND o.Name = 'IX_SpZNr') DROP INDEX Ring.IX_SpZNr
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Ring') AND o.Name = 'IX_ZuAbo_spzNr') DROP INDEX Ring.IX_ZuAbo_spzNr
	ALTER TABLE Ring ALTER COLUMN SpZNr INT NOT NULL
	CREATE UNIQUE NONCLUSTERED INDEX IX_SubscriptionInSeason_SubscriptionSeason ON Ring (ZuAbo, SpZNr)
	CREATE CLUSTERED INDEX IX_SubscriptionInSeason_Season ON Ring (SpzNr)
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'dbo.SchoolHolidays') and c.xtype = 40)
BEGIN
	Print ('SchoolHolidays StartDate,EndDate')
	ALTER TABLE SchoolHolidays ALTER COLUMN StartDate DATE NOT NULL
	ALTER TABLE SchoolHolidays ALTER COLUMN EndDate DATE NOT NULL
END
GO
IF NOT EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.StückeTeil') AND o.Name = 'IX_ProductionParts_ChildProductionId')
BEGIN
	DELETE FROM StückeTeil WHERE SnrTeil IS NULL OR SNr IS NULL
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.StückeTeil') AND o.Name = 'IX_Snr') DROP INDEX StückeTeil.IX_Snr
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.StückeTeil') AND o.Name = 'IX_SnrTeil') DROP INDEX StückeTeil.IX_SnrTeil
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.StückeTeil') AND o.Name = 'IX_Snr_SnrTeil') DROP INDEX StückeTeil.IX_Snr_SnrTeil
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.StückeTeil') AND o.Name = 'StückeTeil_ParentChild') DROP INDEX StückeTeil.StückeTeil_ParentChild
	ALTER TABLE StückeTeil ALTER COLUMN Snr INT NOT NULL
	ALTER TABLE StückeTeil ALTER COLUMN SnrTeil INT NOT NULL
	UPDATE StückeTeil SET Sort = 0 WHERE Sort IS NULL
	ALTER TABLE StückeTeil ADD CONSTRAINT DF_ProductionParts_Sort DEFAULT 0 FOR Sort
	ALTER TABLE StückeTeil ALTER COLUMN Sort SMALLINT NOT NULL
	CREATE UNIQUE NONCLUSTERED INDEX IX_ProductionParts_ParentProductionIdChildProductionId ON StückeTeil (Snr, SnrTeil)
	CREATE NONCLUSTERED INDEX IX_ProductionParts_ParentProductionId ON StückeTeil (Snr)
	CREATE NONCLUSTERED INDEX IX_ProductionParts_ChildProductionId ON StückeTeil (SnrTeil)
END
GO
IF NOT EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.PersAdresse') AND o.Name = 'IX_PersonAddresses_PersonId')
BEGIN
	DELETE  FROM PersAdresse WHERE PersNr IS NULL
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.PersAdresse') AND o.Name = 'PK_PersNr') DROP INDEX PersAdresse.PK_PersNr
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_CashCommand_PersAdresse') AND type = 'F') ALTER TABLE dbo.CashCommand DROP CONSTRAINT FK_CashCommand_PersAdresse
	IF EXISTS (SELECT * FROM sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersAdresse') AND o.Name = 'IX_PersNr_Sort') DROP INDEX PersAdresse.IX_PersNr_Sort
	IF EXISTS (SELECT * FROM sysindexes o WHERE  o.id = OBJECT_ID(N'dbo.PersAdresse') AND o.Name = 'PersNr_Sort') DROP INDEX PersAdresse.PersNr_Sort
	ALTER TABLE dbo.PersAdresse	DROP CONSTRAINT PRIMARYKEY_PersAdresse
	ALTER TABLE PersAdresse ALTER COLUMN PersNr INT NOT NULL
	CREATE CLUSTERED INDEX IX_PersonAddresses_PersonId ON PersAdresse (Persnr)
	ALTER TABLE dbo.PersAdresse ADD CONSTRAINT PK_PersonAddresses PRIMARY KEY  (AdressID) ON [PRIMARY]
	ALTER TABLE dbo.CashCommand ADD CONSTRAINT FK_CashCommand_PersonAddress FOREIGN KEY (AddressId) 
		REFERENCES dbo.PersAdresse (AdressID) ON UPDATE  NO ACTION  ON DELETE  NO ACTION
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PersonNotesPersons') AND type = 'F')
BEGIN
	DELETE  FROM PersonalNotizen WHERE PersNr IS NULL
	DELETE FROM PersonalNotizen  WHERE PersNr NOT IN (SELECT PersNr FROM Persh)

	Print ('create FK_PersonNotesPersons')

	ALTER TABLE dbo.PersonalNotizen WITH CHECK ADD CONSTRAINT FK_PersonNotesPersons FOREIGN KEY(Persnr)
		REFERENCES dbo.PersH (Persnr) ON DELETE CASCADE
	ALTER TABLE dbo.PersonalNotizen CHECK CONSTRAINT FK_PersonNotesPersons
END
GO
DropColumn 'StückeTeil', 'PresseTextTs'
GO
DropColumn 'StückeTeil', 'StückeTeilTS'
GO

IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Zulagen') AND o.Name = 'ZulagenArtBez') DROP INDEX Zulagen.ZulagenArtBez
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'Mandant' and o.id = OBJECT_ID(N'dbo.zr')) ALTER TABLE zr DROP COLUMN Mandant
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'Exid' and o.id = OBJECT_ID(N'dbo.zr')) ALTER TABLE zr DROP COLUMN Exid
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'StdWert' and o.id = OBJECT_ID(N'dbo.Zulagen')) ALTER TABLE Zulagen DROP COLUMN StdWert
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'DruckDP' and o.id = OBJECT_ID(N'dbo.Zulagen')) ALTER TABLE Zulagen DROP COLUMN DruckDP
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'Art' and o.id = OBJECT_ID(N'dbo.Zulagen')) ALTER TABLE Zulagen DROP COLUMN Art
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'Betrag' and o.id = OBJECT_ID(N'dbo.Zulagen')) ALTER TABLE Zulagen DROP COLUMN Betrag
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'DienstplanArtenId' and o.id = OBJECT_ID(N'dbo.ZulagenDienstplan')) ALTER TABLE ZulagenDienstplan DROP COLUMN DienstplanArtenId
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'Arbeitszeit' and o.id = OBJECT_ID(N'dbo.Zeitkonten')) ALTER TABLE Zeitkonten DROP COLUMN Arbeitszeit
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'GruppeID' and o.id = OBJECT_ID(N'dbo.XHDelBesetzung')) ALTER TABLE XHDelBesetzung DROP COLUMN GruppeID
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'XHCount' and o.id = OBJECT_ID(N'dbo.XHDelBesetzung')) ALTER TABLE XHDelBesetzung DROP COLUMN XHCount
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'Druck' and o.id = OBJECT_ID(N'dbo.XHDelBesetzung')) ALTER TABLE XHDelBesetzung DROP COLUMN Druck
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'XHUeberspiel' and o.id = OBJECT_ID(N'dbo.XHDelBesetzung')) ALTER TABLE XHDelBesetzung DROP COLUMN XHUeberspiel
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'PresenterID' and o.id = OBJECT_ID(N'dbo.AufführgDetails')) ALTER TABLE AufführgDetails DROP COLUMN PresenterID
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id WHERE c.name = 'CostUnitId' and o.id = OBJECT_ID(N'dbo.AufführgDetails')) ALTER TABLE AufführgDetails DROP COLUMN CostUnitId

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'ProductionFieldTypes') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	PRINT 'Create Table ProductionFieldTypes';
	CREATE TABLE ProductionFieldTypes(
		ProductionFieldTypeId INT IDENTITY(1,1) NOT NULL,
		Name VARCHAR(100) NOT NULL,
		Code VARCHAR(20) NOT NULL,
		GroupName VARCHAR(100) NULL,
		SectionName VARCHAR(100) NULL,
		SortInSection SMALLINT NOT NULL CONSTRAINT DF_ProductionFieldTypes_SortInSection DEFAULT 0,
		IsVisibleIn TINYINT NOT NULL CONSTRAINT DF_ProductionFieldTypes_IsVisibleIn DEFAULT 0,
		KnownField SMALLINT NULL,
		DataType SMALLINT NOT NULL,
		Settings XML NULL,
		Note VARCHAR(1024) NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_ProductionFieldType PRIMARY KEY CLUSTERED (ProductionFieldTypeId) ON [PRIMARY])
	CREATE UNIQUE NONCLUSTERED INDEX IX_ProductionFieldTypes_FieldCode ON ProductionFieldTypes (Code) ON [PRIMARY]
END
GO

Print 'Granting Permissions to ProductionFieldTypes'
GRANT INSERT, UPDATE,DELETE ON ProductionFieldTypes TO DispoAdmin
GRANT SELECT ON ProductionFieldTypes TO Public
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'ProductionFieldData') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	PRINT 'Create Table ProductionFieldData'
	CREATE TABLE ProductionFieldData(
		ProductionFieldDataId INT IDENTITY(1,1) NOT NULL,
		ProductionId INT NOT NULL,
		ProductionFieldTypeId INT NOT NULL,
		TextValue NVARCHAR(MAX) NOT NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_ProductionFieldData PRIMARY KEY NONCLUSTERED (ProductionFieldDataId) ON [PRIMARY],
		CONSTRAINT FK_ProductionFieldTypes_ProductionFieldData FOREIGN KEY(ProductionFieldTypeId) REFERENCES ProductionFieldTypes (ProductionFieldTypeId),
		CONSTRAINT FK_ProductionFieldTypes_Productions FOREIGN KEY(ProductionId) REFERENCES Stücke (Snr) ON DELETE CASCADE)

	CREATE CLUSTERED INDEX IX_ProductionFieldData_Production ON ProductionFieldData (ProductionId) ON [PRIMARY]
	CREATE UNIQUE NONCLUSTERED INDEX IX_ProductionFieldData_ProductionProductionFieldType ON ProductionFieldData (ProductionId, ProductionFieldTypeId) ON [Primary]
END
GO

GRANT SELECT ON ProductionFieldData TO Public
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'ActivityProductionFieldData') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	PRINT 'Create Table ActivityProductionFieldData';
	CREATE TABLE ActivityProductionFieldData(
		ActivityProductionFieldDataId INT IDENTITY(1,1) NOT NULL,
		ActivityId INT NOT NULL,
		ProductionFieldTypeId INT NOT NULL,
		TextValue NVARCHAR(MAX) NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_ActivityProductionFieldData PRIMARY KEY NONCLUSTERED (ActivityProductionFieldDataId) ON [PRIMARY],
		CONSTRAINT FK_ActivityProductionFieldData_ProductionFieldData FOREIGN KEY(ProductionFieldTypeId) REFERENCES ProductionFieldTypes (ProductionFieldTypeId),
		CONSTRAINT FK_ActivityProductionFieldData_Activities FOREIGN KEY(ActivityId) REFERENCES AufführgTabelle (AuffNr) ON DELETE CASCADE)

	CREATE CLUSTERED INDEX IX_ActivityProductionFieldDataa_Activity ON ActivityProductionFieldData (ActivityId) ON [PRIMARY]
	CREATE UNIQUE NONCLUSTERED INDEX IX_ActivityProductionFieldData_ActivityIdProductionFieldTypeId ON ActivityProductionFieldData (ActivityId, ProductionFieldTypeId) ON [Primary]
END
GO

GRANT SELECT ON ActivityProductionFieldData TO Public
GO

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

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

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

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

CREATE VIEW [dbo].AbActivityProductionFieldData_Update
AS
	SELECT p.* FROM ActivityProductionFieldData AS p
	WHERE p.ActivityId IN (
		SELECT act.AuffNr FROM AufführgTabelle AS act
			INNER JOIN Stücke AS st ON act.SNr = st.SNr
			INNER JOIN Gruppe AS gr ON st.ModuleGroupId = gr.GruppeID
			INNER JOIN UserGruppe AS ug ON gr.GruppeID = ug.GruppeID   
			INNER JOIN UserPW ON Ug.Userid  = UserPW.Userid 
		WHERE ug.BerechtigungsbereichID = 2 AND ug.OptionsFlag & 2 = 2 AND UserPW.Username = CURRENT_USER
	)
	WITH CHECK OPTION
GO

GRANT  SELECT, INSERT, UPDATE,DELETE ON AbActivityProductionFieldData_Update TO Public
GO
	BEGIN TRY

		BEGIN TRANSACTION;
	IF NOT EXISTS (SELECT * FROM ProductionFieldTypes) 
	BEGIN
	
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm) 
			VALUES (1,ISNULL((SELECT TOP 1 Werttext FROM settings WHERE Form ='frmWerk'AND Control = 'txtCaption1' AND NOT Werttext IS NULL),'L1'), 'L1','Lang',1,0,3,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm) 
			SELECT 1, Snr, L10, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT L10 IS NULL AND L10 <> ''
			INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm) 
			SELECT 1, AuffNr, L10, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT L10 IS NULL AND L10 <> ''
		
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (2,ISNULL((SELECT TOP 1 Werttext FROM settings WHERE Form ='frmWerk'AND Control = 'txtCaption2' AND NOT Werttext IS NULL),'L2'), 'L2','Lang',2,0,3,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 2, Snr, L20, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT L20 IS NULL AND L20 <> ''
			INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm)
			SELECT 2, AuffNr, L20, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT L20 IS NULL AND L20 <> ''


			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (3,ISNULL((SELECT TOP 1 Werttext FROM settings WHERE Form ='frmWerk'AND Control = 'txtCaption3' AND NOT Werttext IS NULL),'L3'), 'L3','Lang',3,0,3,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 3, Snr, L30, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT L30 IS NULL AND L30 <> ''
			INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm)
			SELECT 3, AuffNr, L30, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT L30 IS NULL AND L30 <> ''


			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (4,ISNULL((SELECT TOP 1 Werttext FROM settings WHERE Form ='frmWerk'AND Control = 'txtCaption4' AND NOT Werttext IS NULL),'L4'), 'L4','Lang',4,0,3,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 4, Snr, L40, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT L40 IS NULL AND L40 <> ''
			INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm)
			SELECT 4, AuffNr, L40, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT L40 IS NULL AND L40 <> ''


			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (5,ISNULL((SELECT TOP 1 Werttext FROM settings WHERE Form ='frmWerk'AND Control = 'txtCaption5' AND NOT Werttext IS NULL),'L5'), 'L5','Lang',5,0,3,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 5, Snr, L50, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT L50 IS NULL AND L50 <> ''
			INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm)
			SELECT 5, AuffNr, L50, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT L50 IS NULL AND L50 <> ''

		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT L60 IS NULL AND L60 <> '') 
			OR EXISTS (SELECT * FROM PresseText WHERE NOT L60 IS NULL AND L60 <> '') 
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (6,ISNULL((SELECT TOP 1 Werttext FROM settings WHERE Form ='frmWerk'AND Control = 'txtCaption6' AND NOT Werttext IS NULL),'L6'), 'L6','Lang',6,0,3,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 6, Snr, L60, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT L60 IS NULL AND L60 <> ''
			INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm)
			SELECT 6, AuffNr, L60, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT L60 IS NULL AND L60 <> ''
		END
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT LRechts IS NULL AND LRechts <> '') 
			OR EXISTS (SELECT * FROM PresseText WHERE NOT LRechts IS NULL AND LRechts <> '') 
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (7,ISNULL((SELECT TOP 1 Werttext FROM settings WHERE Form ='frmWerk'AND Control = 'txtCaption11' AND NOT Werttext IS NULL),'L7'), 'L7','Lang',7,0,3,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 7, Snr, LRechts, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT LRechts IS NULL AND LRechts <> ''
			INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm)
			SELECT 7, AuffNr, LRechts, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT LRechts IS NULL AND LRechts <> ''
		END
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT K10 IS NULL AND K10 <> '') 
			OR EXISTS (SELECT * FROM PresseText WHERE NOT K10 IS NULL AND K10 <> '') 
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (8,ISNULL((SELECT TOP 1 Werttext FROM settings WHERE Form ='frmWerk'AND Control = 'txtCaption7' AND NOT Werttext IS NULL),'K1'), 'K1','Kurz',101,0,3,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 8, Snr, K10, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT K10 IS NULL AND K10 <> ''
			INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm)
			SELECT 8, AuffNr, K10, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT K10 IS NULL AND K10 <> ''
		END
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT K20 IS NULL AND K20 <> '')
			OR EXISTS (SELECT * FROM PresseText WHERE NOT K20 IS NULL AND K20 <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (9,ISNULL((SELECT TOP 1 Werttext FROM settings WHERE Form ='frmWerk'AND Control = 'txtCaption8' AND NOT Werttext IS NULL),'K2'), 'K2','Kurz',102,0,3,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 9, Snr, K20, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT K20 IS NULL AND K20 <> ''
			INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm)
			SELECT 9, AuffNr, K20, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT K20 IS NULL AND K20 <> ''
		END
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT K30 IS NULL AND K30 <> '')
			OR EXISTS (SELECT * FROM PresseText WHERE NOT K30 IS NULL AND K30 <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (10,ISNULL((SELECT TOP 1  Werttext FROM settings WHERE Form ='frmWerk'AND Control = 'txtCaption9'  AND NOT Werttext IS NULL),'K3'), 'K3','Kurz',103,0,3,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 10, Snr, K30, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT K30 IS NULL AND K30 <> ''
			INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm)
			SELECT 10, AuffNr, K30, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT K30 IS NULL AND K30 <> ''
		END
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT K40 IS NULL AND K40 <> '')
			OR EXISTS (SELECT * FROM PresseText WHERE NOT K40 IS NULL AND K40 <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (11,ISNULL((SELECT  TOP 1 Werttext FROM settings WHERE Form ='frmWerk'AND Control = 'txtCaption10' AND NOT Werttext IS NULL),'K4'), 'K4','Kurz',104,0,3,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 11, Snr, K40, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT K40 IS NULL AND K40 <> ''
			INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm)
			SELECT 11, AuffNr, K40, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT K40 IS NULL AND K40 <> ''
		END
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT kRechts IS NULL AND kRechts <> '')
			OR EXISTS (SELECT * FROM PresseText WHERE NOT kRechts IS NULL AND kRechts <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (12,ISNULL((SELECT TOP 1 Werttext FROM settings WHERE Form ='frmWerk'AND Control = 'txtCaption12' AND NOT Werttext IS NULL),'K5'), 'K5','Kurz',105,0,3,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 12, Snr, kRechts, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT kRechts IS NULL AND kRechts <> ''
			INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm)
			SELECT 12, AuffNr, kRechts, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT kRechts IS NULL AND kRechts <> ''
		END


		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT T10 IS NULL AND T10 <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,GroupName,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (13,'Kopf 1', 'L8','Lang',8,'Besetzungszettel',0,1,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 13, Snr, T10, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT T10 IS NULL AND T10 <> ''
		END

		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT T20 IS NULL AND T20 <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,GroupName,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (14,'Kopf 2', 'L9','Lang',9,'Besetzungszettel',0,1,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 14, Snr, T20, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT T20 IS NULL AND T20 <> ''
		END
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT T30 IS NULL AND T30 <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,GroupName,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (15,'Kopf 3', 'L10','Lang',10,'Besetzungszettel',0,1,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 15, Snr, T30, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT T30 IS NULL AND T30 <> ''
		END
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT T40 IS NULL AND T40 <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,GroupName,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (16,'Kopf 4', 'L11','Lang',11,'Besetzungszettel',0,1,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 16, Snr, T40, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT T40 IS NULL AND T40 <> ''
		END
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT F10 IS NULL AND F10 <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,GroupName,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (17,'Fuss 1', 'L12','Lang',12,'Besetzungszettel',0,1,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 17, Snr, F10, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT F10 IS NULL AND F10 <> ''
		END
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT F20 IS NULL AND F20 <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,GroupName,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (18,'Fuss 2', 'L13','Lang',13,'Besetzungszettel',0,1,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 18, Snr, F20, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT F20 IS NULL AND F20 <> ''
		END
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT F30 IS NULL AND F30 <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,GroupName,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (19,'Fuss 3', 'L14','Lang',14,'Besetzungszettel',0,1,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 19, Snr, F30, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT F30 IS NULL AND F30 <> ''
		END
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT F40 IS NULL AND F40 <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,GroupName,DataType,IsVisibleIn,uc,lc,um,lm)
			VALUES (20,'Fuss 4', 'L15','Lang',15,'Besetzungszettel',0,1,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm)
			SELECT 20, Snr, F40, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT F40 IS NULL AND F40 <> ''
		END
	
		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT InternetLink IS NULL AND InternetLink <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm) 
			VALUES (21,'InternetLink', 'InternetLink','Kurz',110,0,1,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm) 
			SELECT 21, Snr, InternetLink, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT InternetLink IS NULL AND InternetLink <> '' 
		END
	
		SET IDENTITY_INSERT ProductionFieldTypes ON
		INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,KnownField,uc,lc,um,lm) 
		VALUES (22,'Komponist', 'composer',NULL,1,0,2,2,-1,GetDate(),-1,GetDate())
		SET IDENTITY_INSERT ProductionFieldTypes OFF
		INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm) 
		SELECT 22, AuffNr, PKomponist, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT PKomponist IS NULL AND PKomponist <> '' 
	
		INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm) 
		SELECT 22, Snr, Komponist, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT Komponist IS NULL AND Komponist <> '' 

		SET IDENTITY_INSERT ProductionFieldTypes ON
		INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,KnownField,uc,lc,um,lm) 
		VALUES (23,'OriginalTitle', 'originalTitle',NULL,1,0,2,1,-1,GetDate(),-1,GetDate())
		SET IDENTITY_INSERT ProductionFieldTypes OFF
		INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm) 
		SELECT 23, AuffNr, POriginaltitel , ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT POriginaltitel  IS NULL AND POriginaltitel  <> '' 

		SET IDENTITY_INSERT ProductionFieldTypes ON
		INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,KnownField,uc,lc,um,lm) 
		VALUES (24,'Not In Press', 'NoPress',NULL,1,4,2,3,-1,GetDate(),-1,GetDate())
		SET IDENTITY_INSERT ProductionFieldTypes OFF
		INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm) 
		SELECT 24, AuffNr, '1', ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT KeinDruck IS NULL AND KeinDruck = 1

		SET IDENTITY_INSERT ProductionFieldTypes ON
		INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,KnownField,uc,lc,um,lm) 
		VALUES (25,'PrintStart', 'PrintStart',NULL,1,4,2,4,-1,GetDate(),-1,GetDate())
		SET IDENTITY_INSERT ProductionFieldTypes OFF
		INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm) 
		SELECT 25, AuffNr, '1', ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT VonDru IS NULL AND VonDru = 1

		SET IDENTITY_INSERT ProductionFieldTypes ON
		INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,KnownField,uc,lc,um,lm) 
		VALUES (26,'PrintEnd', 'PrintEnd',NULL,1,4,2,5,-1,GetDate(),-1,GetDate())
		SET IDENTITY_INSERT ProductionFieldTypes OFF
		INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm) 
		SELECT 26, AuffNr, '1', ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT BisZeit IS NULL AND BisZeit = 1

		SET IDENTITY_INSERT ProductionFieldTypes ON
		INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,KnownField,uc,lc,um,lm) 
		VALUES (27,'AlternativeEndText', 'AlternativeEndText',NULL,1,0,2,6,-1,GetDate(),-1,GetDate())
		SET IDENTITY_INSERT ProductionFieldTypes OFF
		INSERT INTO ActivityProductionFieldData (ProductionFieldTypeId,ActivityId,TextValue,uc,lc,um,lm) 
		SELECT 27, AuffNr, '1', ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM PresseText WHERE NOT BisZeit IS NULL AND BisZeit = 1

		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT Memo IS NULL AND Memo <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm) 
			VALUES (28,'Beschreibung', 'Description','Lang',8,1,1,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm) 
			SELECT 28, Snr, Memo, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT Memo IS NULL AND Memo <> '' 
		END

		IF EXISTS (SELECT * FROM StückeDetails WHERE NOT Memo_en IS NULL AND Memo_en <> '')
		BEGIN
			SET IDENTITY_INSERT ProductionFieldTypes ON
			INSERT INTO ProductionFieldTypes (ProductionFieldTypeId, Name,Code,SectionName,SortInSection,DataType,IsVisibleIn,uc,lc,um,lm) 
			VALUES (29,'BeschreibungEN', 'DescriptionEN','Lang',9,1,1,-1,GetDate(),-1,GetDate())
			SET IDENTITY_INSERT ProductionFieldTypes OFF

			INSERT INTO ProductionFieldData (ProductionFieldTypeId,ProductionId,TextValue,uc,lc,um,lm) 
			SELECT 29, Snr, Memo_en, ISNULL(UM,-1),ISNULL(LC,'19000101'),ISNULL(UM,-1),ISNULL(LM,'19000101') FROM StückeDetails WHERE NOT Memo_en IS NULL AND Memo_en <> '' 
		END

	END

	COMMIT TRANSACTION;
	Print  'ProductionFieldTypes '
END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION;
		Print 'Error ProductionFieldTypes'
		DECLARE @severity INT, @state INT, @message nvarchar(4000);
		select @severity = ERROR_SEVERITY(), @state = ERROR_STATE(), @message = ERROR_MESSAGE();			
		RAISERROR(@message, @severity, @state)
	END CATCH;
GO

ALTER FUNCTION dbo.GetActivityPerformanceNumbersAllSeasons(
		@start DATE,
		@end DATE)
	RETURNS TABLE
	AS
		RETURN (SELECT * FROM (SELECT Row_Number() OVER (PARTITION BY a.Snr ORDER BY Datum, UhrBeg)  + ISNULL(pd.AnzahlAuff, 0)  AS RowNum, AuffNr, Datum
				FROM AufführgTabelle AS A
					INNER JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art
					LEFT JOIN StückeDetails AS PD ON Pd.Snr = A.Snr
				WHERE Category >= 2000
					AND Datum <= @end
					AND [Status] >= 3
					AND VariantId = 0
				) AS subA WHERE Datum BETWEEN @start AND @end)
GO
ALTER FUNCTION dbo.GetActivityPerformanceNumbers(
		@start DATE,
		@end DATE)
	RETURNS TABLE
	AS
		RETURN (SELECT Row_Number() OVER (PARTITION BY a.Snr ORDER BY Datum, UhrBeg) AS RowNum, AuffNr, Datum 
				FROM AufführgTabelle AS A
					INNER JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art
				WHERE Category >= 2000 
					AND Datum BETWEEN @start AND @end 
					AND [Status] >= 3
					AND VariantId = 0)
GO
ALTER PROCEDURE dbo.GetActivityPerformanceNumber(
		@productionId INT,
		@seasonStart DATE,
		@date DATE,
		@startTime SMALLDATETIME)
	AS
		SELECT COUNT(*) AS Anz
		FROM AufführgTabelle AS a
			INNER JOIN AuffTypen AS At ON a.Art = At.AuffTNr
		WHERE a.Snr = @productionId 
			AND Category >= 2000
			AND ((a.Datum < @date AND a.Datum >= @seasonStart) OR (a.Datum = @date AND UhrBeg <= @startTime))
			AND a.[Status] >= 3
			AND VariantId = 0
GO
ALTER FUNCTION dbo.GetActivityTypeRehearsalNumbers(
		@start DATE,
		@end DATE)
	RETURNS TABLE
	AS
		RETURN (SELECT Row_Number() OVER (PARTITION BY Art, Snr ORDER BY Datum, UhrBeg) AS RowNum, AuffNr, Datum 
				FROM AufführgTabelle AS A
					INNER JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art 
			WHERE AT.LfdNr = 1 AND Datum BETWEEN @start AND @end AND [Status] >= 3 AND VariantId = 0)
GO

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

CREATE 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.SpzStart), @permissionPeriodEnd = MAX(s.SpzEnde)
		FROM Spielzeittabelle AS s
			INNER JOIN UserForAccess AS us	ON s.spznr = us.spznr
		WHERE us.UserId = @userId AND s.SpzNr <> 0

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

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

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

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


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

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

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

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

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

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

		IF (@joins&4 = 4 OR (@include = 0 AND CHARINDEX('zr.', @order) > 0 )) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN Zr ON Aufführg.ZrNr = Zr.ZrNr '

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

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

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

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

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


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

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

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

			END

			EXECUTE sp_Executesql  @SQLQuery

		END

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

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

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

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

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

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

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

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

CREATE 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 UserPW WHERE UserName  = CURRENT_USER
	EXECUTE GetActivitiesInternal @start, @end, @condition, @order, @joins, @include, @userId, @ShowActivitiesWithoutRights
END
GO

GRANT EXECUTE ON [GetActivities] TO PUBLIC
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.GetActivities2'))	DROP PROCEDURE dbo.GetActivities2 
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.GetActivitiesInternal2'))	DROP PROCEDURE dbo.GetActivitiesInternal2 
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.GetCastByActivityId2'))	DROP PROCEDURE dbo.GetCastByActivityId2 
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.GetCastByActivityIdInternal2'))	DROP PROCEDURE dbo.GetCastByActivityIdInternal2 
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.GetCastByPeriod2'))	DROP PROCEDURE dbo.GetCastByPeriod2 
IF EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.GetCastByPeriodInternal2'))	DROP PROCEDURE dbo.GetCastByPeriodInternal2 
GO
--#endregion

--#region
DELETE FROM Role_Season WHERE SeasonId = 0
--#endregion

--#region SH 2018-10-17 AufführgDetails.AuffNrExtern auf VARCHAR(20) umstellen

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('AufführgDetails') AND c.[name] = 'AuffNrExtern' AND s.name = 'INT')
BEGIN
	PRINT('Changing AufführgDetails.AuffNrExtern to string...')
	ALTER TABLE AufführgDetails ALTER COLUMN AuffNrExtern VARCHAR(20) SPARSE NULL
	
	UPDATE AufführgDetails SET AuffNrExtern = NULL WHERE AuffNrExtern = '0'
END
GO

--#endregion

--#region SH 2018-10-17 Bisherige ScheduleDataImportSettings umschreiben in die neue Section mit Key Standard

IF EXISTS(SELECT * FROM Settings WHERE Form = 'Import' AND [Control] = 'ScheduleDataImport')
AND NOT EXISTS(SELECT * FROM Settings WHERE Form = 'ScheduleDataImport' AND [Control] = 'Standard')
BEGIN
	PRINT('Changing settings of ScheduleDataImport...')
	UPDATE Settings SET Form = 'ScheduleDataImport', [Control] = 'Standard'
	WHERE Form = 'Import' AND [Control] = 'ScheduleDataImport'
END
GO

--#endregion

--#region dh 2018-10-12 Arbeitszeitmodelle
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DayOffCreditsFromDutyRosterEntries' and o.id = OBJECT_ID(N'dbo.Zyklen'))
BEGIN
BEGIN TRAN
ALTER TABLE Zyklen 
	ADD DebitFromWorktimeModel BIT not null 
	CONSTRAINT DF_Zyklen_DebitFromWorktimeModel DEFAULT 0;

ALTER TABLE Zyklen 
	ADD DayOffCreditsFromDutyRosterEntries BIT not null 
	CONSTRAINT DF_Zyklen_DayOffCreditsFromDutyRosterEntries DEFAULT 0;
EXEC (N'update Zyklen set DayOffCreditsFromDutyRosterEntries=1 where ZyklusNr in (select distinct ZyklusNr from ZyklusWochen ZW where zw.DayOffCredit=1)');
EXEC (N'update Zyklen set DebitFromWorktimeModel=1 where ZyklusNr in (select distinct ZyklusNr from ZyklusWochen zw inner join ContractPersoWorkingCycles cp on zw.ZyklusNr=cp.WorkingCycleId inner join VertragPerso vp on cp.ContractId=vp.VertragsNr where IsNull(Debit,0) >0 and vp.UseWorkTimeModelDebit=1)');


IF(@@ERROR>0)
BEGIN
ROLLBACK TRAN
END
COMMIT TRAN
END
--#endregion dh 2018-10-12

--#region SH 2018-10-19 Spalte Currency.CurrencyISOCode hinzufügen

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Currency') AND [name] = 'CurrencyISOCode')
BEGIN
	PRINT('Adding column Currency.CurrencyISOCode ...')
	ALTER TABLE dbo.Currency ADD CurrencyISOCode CHAR(3) NULL

	EXEC('UPDATE Currency SET CurrencyISOCode = CurrencyName WHERE LEN(CurrencyName) = 3')
END
GO

--#endregion (SH 2018-10-19)

--#region bm 180629 Währungskurse aktualisieren / update sh 2018-10-19 CurrencyISOCode verwenden
IF  EXISTS (SELECT * FROM  sys.objects o WHERE o.object_id = OBJECT_ID(N'[dbo].[UpdateCurrencyExchangeRates]'))
BEGIN
	DROP PROCEDURE dbo.[UpdateCurrencyExchangeRates]
END
GO

IF EXISTS (SELECT * FROM systypes WHERE name = 'ExchangeRatesTable')
BEGIN
	DROP TYPE ExchangeRatesTable
END
GO

CREATE TYPE ExchangeRatesTable as TABLE (currency nvarchar(4), [value] float)
GO

GRANT EXEC ON TYPE::ExchangeRatesTable TO [public]
GO

CREATE PROCEDURE [dbo].[UpdateCurrencyExchangeRates] 
	@CurrencyExchangeRates ExchangeRatesTable READONLY
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	UPDATE Currency 
	SET Currency.DefaultCurrencyRate = r.[value], LM = GETDATE(), UM = -1
	FROM Currency c
	INNER JOIN @CurrencyExchangeRates r ON c.CurrencyISOCode = r.currency
END
GO

GRANT EXECUTE ON UpdateCurrencyExchangeRates TO [public]
GO

--#endregion Währungskurse
--#region 20181108
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Gruppe') AND [name] = 'MainOwnerGroupId')
BEGIN
	PRINT('Adding column Gruppe.MainOwnerGroupId ...')
	ALTER TABLE dbo.Gruppe ADD MainOwnerGroupId INT NULL
	--Einige bekannte Fälle einstellen
	EXEC('UPDATE Gruppe SET MainOwnerGroupId = 1 WHERE GruppeBez = ''Regie u Konzert'' AND Modul = 1')
	EXEC('UPDATE Gruppe SET MainOwnerGroupId = 1 WHERE GruppeBez = ''Regie'' AND Modul = 1')
END
GO
--#endregion


--#endregion (4.184.x)

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

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

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('Gruppe') AND [name] = 'MainOwnerGroupId')
BEGIN
	PRINT('Adding column Gruppe.MainOwnerGroupId ...')
	ALTER TABLE dbo.Gruppe ADD MainOwnerGroupId INT NULL
	--Einige bekannte Fälle einstellen
	EXEC('UPDATE Gruppe SET MainOwnerGroupId = 1 WHERE GruppeBez = ''Regie u Konzert'' AND Modul = 1')
	EXEC('UPDATE Gruppe SET MainOwnerGroupId = 1 WHERE GruppeBez = ''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 StückeDetails s ON p.ProductionId = s.Snr AND ProductionFieldTypeId = 1 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = L20, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN StückeDetails s ON p.ProductionId = s.Snr AND ProductionFieldTypeId = 2 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = L30, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN StückeDetails s ON p.ProductionId = s.Snr AND ProductionFieldTypeId = 3 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = L40, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN StückeDetails s ON p.ProductionId = s.Snr AND ProductionFieldTypeId = 4 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = L50, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN StückeDetails s ON p.ProductionId = s.Snr AND ProductionFieldTypeId = 5 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = L60, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN StückeDetails s ON p.ProductionId = s.Snr AND ProductionFieldTypeId = 6 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = LRechts, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN StückeDetails s ON p.ProductionId = s.Snr AND ProductionFieldTypeId = 7 AND p.lm = s.lc

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

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

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

	UPDATE ProductionFieldData SET TextValue = Komponist, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN StückeDetails s ON p.ProductionId = s.Snr AND ProductionFieldTypeId = 22 AND p.lm = s.lc

	UPDATE ProductionFieldData SET TextValue = Memo, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN StückeDetails s ON p.ProductionId = s.Snr AND ProductionFieldTypeId = 28 AND p.lm = s.lc
	UPDATE ProductionFieldData SET TextValue = Memo_EN, lm = ISNULL(s.lm,'19000101') FROM ProductionFieldData p INNER JOIN StückeDetails s ON p.ProductionId = s.Snr 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.AuffNr 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.AuffNr 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.AuffNr 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.AuffNr 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.AuffNr 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.AuffNr 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.AuffNr 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.AuffNr 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.AuffNr 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.AuffNr 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.AuffNr 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.AuffNr 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.AuffNr 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.AuffNr AND ProductionFieldTypeId = 23 AND p.lm = s.lc
END
--#endregion

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

UPDATE VerteilerFeld SET ObjectName = 'Aufführg.zrNr' WHERE ObjectName = 'zr.zrNr' AND ControlContainerName = 'ts_DataAuff'
GO

--#endregion
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Qualification_Role_BesetzungStd') AND type = 'F') ALTER TABLE dbo.Qualification_Role	DROP CONSTRAINT FK_Qualification_Role_BesetzungStd
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Qualification_Role_Role') AND type = 'F') 
BEGIN
	Print 'Add FK_QualificationRole_Role'
	DELETE FROM Qualification_Role WHERE NOT EXISTS (SELECT * FROM BesetzungStd WHERE Qualification_Role.RoleId = BesetzungStd.id)

	ALTER TABLE dbo.Qualification_Role  WITH CHECK ADD  CONSTRAINT FK_Qualification_Role_Role FOREIGN KEY(RoleId)
		REFERENCES dbo.BesetzungStd (Id) ON DELETE CASCADE
	ALTER TABLE dbo.Qualification_Role CHECK CONSTRAINT FK_Qualification_Role_Role
	--Instrumente sind kein Kollektiv Orchester
	UPDATE RollenLtg SET TagesplanSpalte = 0 WHERE Module =2 AND TagesplanSpalte = 100 AND Rolle <> 'Orchester'

	--Farben für Aufgabenbereiche
	UPDATE RollenLtg SET Settings = NULL
	FROM RollenLtg WHERE TagesplanSpalte = 0 AND Module = 1 AND RollenLtgID > 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 RollenLtg SET Settings = NULL
	FROM RollenLtg WHERE TagesplanSpalte = 100 AND Module = 1 AND RollenLtgID > 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 RollenLtg SET Settings = NULL
	FROM RollenLtg WHERE TagesplanSpalte = 110 AND Module = 1 AND RollenLtgID > 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 RollenLtg SET Settings = NULL
	FROM RollenLtg WHERE TagesplanSpalte = 120 AND Module = 1 AND RollenLtgID > 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 RollenLtg SET Settings = NULL
	FROM RollenLtg WHERE TagesplanSpalte = 130 AND Module = 1 AND RollenLtgID > 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

--#region Nicht verwendete Soliprobenrollen entfernen
PRINT 'Deleting BesetzungStdSoli entries for soloist rehearsal roles...'
DELETE bsst FROM BesetzungStdSoliTabelle bsst
INNER JOIN BesetzungStd bs ON bsst.RolleID = bs.ID
WHERE bs.SNr = -1
GO

PRINT 'Deleting not used soloist rehearsal roles...'
DELETE FROM BesetzungStd WHERE snr = -1 AND ID <> -1 AND NOT EXISTS (SELECT * FROM BesetzungTabelle WHERE RolleID = BesetzungStd.id)
GO
--#endregion

--#region 2019-01-14 SH Repetitorrolle bei Bedarf wieder hinzufügen
IF NOT EXISTS(SELECT * FROM BesetzungStd bs WHERE bs.ID = -1)
BEGIN
	PRINT 'Adding Repetitor role...'
	SET IDENTITY_INSERT BesetzungStd ON
	INSERT INTO BesetzungStd (ID, SNr, Rolle, RollenLtgID, DruckSteuerung, DruckStd, Besitzer)
	VALUES (-1, -1, 'Repetitor', -1, 0, 1, 1)
	SET IDENTITY_INSERT BesetzungStd OFF
END
GO
--#endregion 

--#endregion (4.184.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 gibt,
			-- diese rückgängig machen,
			-- da sonst folgefehler auftreten können
			-- 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 zum löschen in 2019 vormarkiert

--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.BlockedBudgetItems') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)		DROP TABLE BlockedBudgetItems
--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 'BesetzungStd', 'StdPro'
--DropColumn 'BesetzungStd', 'Cover'
-- VertragDetails UnterkunftVs
--VertragDetails Reisekosten
--DropColumn 'BesetzungStd', '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.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
	--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)
--#endregion zum löschen in 2019 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 = 184
SET @build = 103
SET @Datum = 20181219
--#endregion ----------- Version aus ts_evt in TS_DataClass ------

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

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

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