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


IF NOT EXISTS 
	(SELECT * 
	 FROM dbo.sysobjects 
	 WHERE id = OBJECT_ID('dbo.NVData') AND OBJECTPROPERTY(id, 'IsUserTable') = 1)
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='
		
																																													Print ''
																																															Print '		Keine Theasoft 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


DECLARE @serverVersion INT
SELECT @serverVersion = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
	IF @serverVersion < 9
	
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='
		
																																													Print ''
																																															Print '		Die SQL-Server-Version wird nicht mehr unterstützt!!!'	
																																															Print '		Bitte migrieren Sie auf mindestens SQL Server 2005 (empfohlen 2012)'
																																															Print ''
																																															Print '=============================================='
																																															Print ''
																																															Print ''
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
																																															Print ''
																																															Print ''
																																															RAISERROR('Nicht unterstützte SQL-Server-Version!!!', 20, -1) WITH LOG
																																															SET NOEXEC ON
END
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major > 4 OR (Major = 4 AND (Minor >= 151))))
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='		
																																															Print ''
																																															Print '		Veraltete Skriptversion!!!'	
																																															Print '		Bitte führen Sie DbScript_2015.sql bzw. DbScript.sql aus.'
																																															Print ''
																																															Print '=============================================='
																																															Print ''
																																															Print ''																																															Print''
																																															Print''
																																															RAISERROR(N'Skriptversion veraltet!!!', 20, -1) WITH LOG
																																															SET NOEXEC ON
END
GO

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DeleteConstraint'))
BEGIN
	DROP PROCEDURE dbo.DeleteConstraint 
END
go

CREATE PROCEDURE dbo.DeleteConstraint
	@tab varchar(100), 
	@field varchar(100)
AS
BEGIN
	DECLARE @defname varchar(100)
	SELECT @defname = name 	FROM sysobjects so JOIN sysconstraints sc ON so.id = sc.constid 
			WHERE object_name(so.parent_obj) = @tab
			AND so.xtype = 'D'
			AND sc.colid = 	(SELECT colid FROM syscolumns WHERE id = OBJECT_ID(@tab) AND name = @field)
	
	IF @defname <> '' BEGIN
		EXEC ('ALTER TABLE '+@tab+' DROP CONSTRAINT '+@defname)
		Print 'Default Constraint '+@defname+' gelöscht.'
	END				
	--exec ('ALTER TABLE '+ @tab +' ALTER COLUMN ' + @field + ' int NOT NULL')
	--exec ('ALTER TABLE [dbo].'+ @tab +' ADD CONSTRAINT DF_BesetzungTabelle_CastStatusID DEFAULT (0) FOR [CastStatusID]')
END
GO



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

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

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

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


DECLARE @IndexName VARCHAR(100) 
DECLARE view_cursor CURSOR FOR 
	--SELECT i.name   FROM  sysindexes i INNER JOIN sysobjects o ON o.object_id = i.object_id
	-- WHERE objectproperty(o.object_id,'IsUserTable') = 1 and i.type <> 0  AND i.is_primary_key = 0
	--AND o.name = @tablename
	
		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
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DropColumn'))
BEGIN
	DROP PROCEDURE dbo.DropColumn 
END
go
CREATE PROCEDURE dbo.DropColumn 
	@tablename varchar(100),
	@columnname varchar(100)
AS
BEGIN
IF  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = @columnname and o.id = OBJECT_ID(N'[dbo].[' + @tablename+ ']'))	
	BEGIN
		--TODO: Ggf. Index entf.
		declare @defname varchar(100)
		declare @cmd varchar(100)
		select @defname = name 
		FROM sysobjects so JOIN sysconstraints sc
		ON so.id = sc.constid 
		WHERE object_name(so.parent_obj) = @tablename
		AND so.xtype = 'D'
		AND sc.colid = 
		(SELECT colid FROM syscolumns 
		WHERE id = object_id(@tablename) AND 
		name = @columnname)

		select @cmd='alter table '+@tablename+ ' drop constraint '+@defname
		--if @cmd is null print 'No default constraint to drop'
		exec (@cmd)
		declare @cmd2 varchar(100)
		select @cmd2 = @tablename + '.' + @columnname
		--EXECUTE sp_unbindefault  @cmd2

		select @cmd='alter table '+@tablename+ ' drop COLUMN ' + @columnname
			exec (@cmd)
	END
END
go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DropDefault'))
BEGIN
	DROP PROCEDURE dbo.DropDefault 
END
GO
CREATE PROCEDURE dbo.DropDefault 
	@tablename varchar(100),
	@columnname varchar(100)
AS 

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

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

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

--#region Stored Procedure zum Löschen von Rollen, die vorher allerdings alle Member aus de Rolle entfernt
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DropRoleWithDropRoleMember'))
BEGIN
	DROP PROCEDURE dbo.DropRoleWithDropRoleMember 
END
GO
CREATE PROCEDURE dbo.DropRoleWithDropRoleMember 
	@role varchar(100)
AS 

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


UPDATE PersH SET Besitzer = 1 where PersNr = 260
go
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'SecurityAdmin')
BEGIN
	EXEC sp_addrole @rolename = N'SecurityAdmin'
END
GO


GRANT DELETE ON UserGruppe TO SecurityAdmin
GRANT INSERT ON UserGruppe TO SecurityAdmin
GRANT UPDATE ON UserGruppe TO SecurityAdmin

GRANT DELETE ON Gruppe TO SecurityAdmin
GRANT INSERT ON Gruppe TO SecurityAdmin
GRANT UPDATE ON Gruppe TO SecurityAdmin

GRANT DELETE ON UserPw TO SecurityAdmin
GRANT INSERT ON UserPw TO SecurityAdmin
GRANT UPDATE ON UserPw TO SecurityAdmin

REVOKE DELETE ON UserGruppe TO [Spielzeitenverwalten]
REVOKE INSERT ON UserGruppe TO [Spielzeitenverwalten]
REVOKE UPDATE ON UserGruppe TO [Spielzeitenverwalten]
go
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoAdmin')
BEGIN
	EXEC sp_addrole @rolename = N'PersoAdmin'
END
GO
--if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoPublic')
--BEGIN
--	EXEC sp_addrole @rolename = N'PersoPublic'
--END
GO
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoBasicDataWrite')
BEGIN
	EXEC sp_addrole @rolename = N'PersoBasicDataWrite'
END
GO
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoContractWrite')
BEGIN
	EXEC sp_addrole @rolename = N'PersoContractWrite'
END

GO
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoPrintLayoutWrite')
BEGIN
	EXEC sp_addrole @rolename = N'PersoPrintLayoutWrite'
END
GO
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoCloseWrite')
BEGIN
	EXEC sp_addrole @rolename = N'PersoCloseWrite'
END

GO
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoWorkingModelWrite')
BEGIN
	EXEC sp_addrole @rolename = N'PersoWorkingModelWrite'
END
Go
--if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'DispoSecredCastRead')
--BEGIN
--	EXEC sp_addrole @rolename = N'DispoSecredCastRead'
--END
--go
--if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'DispoSecredActivitiesRead')
--BEGIN
--	EXEC sp_addrole @rolename = N'DispoSecredActivitiesRead'
--END
GO


if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoShiftGenericWrite')
BEGIN
	EXEC sp_addrole @rolename = N'PersoShiftGenericWrite'
END
go
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoShiftAbsenceWrite')
BEGIN
	EXEC sp_addrole @rolename = N'PersoShiftAbsenceWrite'
END
go
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoShiftDepartmentWrite')
BEGIN
	EXEC sp_addrole @rolename = N'PersoShiftDepartmentWrite'
END
go



--/****** Objekt:  Table [dbo].[DienstplanUser]    Skriptdatum: 09/18/2007 11:46:14 ******/
--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DienstplanUser]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
--BEGIN
--CREATE TABLE [dbo].[DienstplanUser](
--	[DienstplanUserID] [int] IDENTITY(1,1) NOT NULL,
--	[DienstplanArtenID] [int] NOT NULL ,
--	[UserID] [int] NOT NULL,
--	[Schreiben] [bit] NOT NULL Default 0,
--	[LM] [datetime] NULL,
--	[UM] [int] NULL,
--	[LC] [datetime] NULL,
--	[UC] [int] NULL,
--	CONSTRAINT [PK_DienstplanUser] PRIMARY KEY CLUSTERED (
--		DienstplanUserID ASC
--	)WITH FILLFACTOR = 90 ON [PRIMARY]
--) ON [PRIMARY]
--END
--GO
--GRANT SELECT ON DienstplanUser TO PersoPublic

--GRANT SELECT ON DienstplanUser TO PersoAdmin
--GRANT DELETE ON DienstplanUser TO PersoAdmin
--GRANT INSERT ON DienstplanUser TO PersoAdmin
--GRANT UPDATE ON DienstplanUser TO PersoAdmin

GRANT DELETE ON aufftypen TO PersoAdmin
GRANT INSERT ON aufftypen TO PersoAdmin
GRANT UPDATE ON aufftypen TO PersoAdmin

GO
/****** Objekt:  Table [dbo].[DPGruppen]    Skriptdatum: 09/18/2007 11:46:15 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DienstplanGruppen]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[DienstplanGruppen]( /* Name geändert */
	[DienstplanGruppenID] [int] IDENTITY(1,1) NOT NULL, /* Name geändert */
	[DienstplanGruppenBez] [varchar](20) NOT NULL, /* Name geändert */
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [IX_DienstplanGruppenID] PRIMARY KEY CLUSTERED (
		[DienstplanGruppenID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON DienstplanGruppen TO public
GRANT SELECT ON DienstplanGruppen TO PersoAdmin

GRANT DELETE ON DienstplanGruppen TO PersoAdmin
GRANT INSERT ON DienstplanGruppen TO PersoAdmin
GRANT UPDATE ON DienstplanGruppen TO PersoAdmin

GRANT DELETE ON DienstplanGruppen TO PersoBasicDataWrite
GRANT INSERT ON DienstplanGruppen TO PersoBasicDataWrite
GRANT UPDATE ON DienstplanGruppen TO PersoBasicDataWrite
GO
/****** Objekt:  Table [dbo].[FeiertageAusg]    Skriptdatum: 09/18/2007 11:46:18 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FeiertageAusg]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[FeiertageAusg](
	[FeiertageAusgID] [int] IDENTITY(1,1) NOT NULL,	
	[FTArt] [int] NOT NULL,
	[WT] [int] NOT NULL,
	[Zyklus] [bit] NOT NULL,
	[ArbFreiGeplant] [bit] NOT NULL,
	[ArbFrei] [bit] NOT NULL,
	[FF] [real] NOT NULL,	
	[AZA] [real] NOT NULL,		
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_FeiertageAusg] PRIMARY KEY CLUSTERED (
		[FeiertageAusgID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON FeiertageAusg TO PersoAdmin
GRANT UPDATE ON FeiertageAusg TO PersoAdmin
GRANT SELECT ON FeiertageAusg TO PersoContractWrite
GRANT UPDATE ON FeiertageAusg TO PersoContractWrite
GRANT SELECT ON FeiertageAusg TO public

GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DienstplanEintragArt]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[DienstplanEintragArt] (
	[DienstplanEintragArtId] [int] IDENTITY (1, 1) NOT NULL ,
	[Bezeichnung] [varchar] (20)  NOT NULL ,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL
	CONSTRAINT [PK_DienstplanEintragArt] PRIMARY KEY CLUSTERED 
	([DienstplanEintragArtId] ASC ) ON [PRIMARY]) ON [PRIMARY]

END

GRANT SELECT ON DienstplanEintragArt TO public
GRANT SELECT ON DienstplanEintragArt TO PersoAdmin

GRANT DELETE ON DienstplanEintragArt TO PersoAdmin
GRANT INSERT ON DienstplanEintragArt TO PersoAdmin
GRANT UPDATE ON DienstplanEintragArt TO PersoAdmin


GRANT DELETE ON DienstplanEintragArt TO PersoBasicDataWrite
GRANT INSERT ON DienstplanEintragArt TO PersoBasicDataWrite
GRANT UPDATE ON DienstplanEintragArt TO PersoBasicDataWrite

--/****** Objekt:  Table [dbo].[Frei]    Skriptdatum: 09/18/2007 11:46:19 ******/
--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Frei]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
--BEGIN
--CREATE TABLE [dbo].[Frei](
--	[FreiId] [int] IDENTITY(1,1) NOT NULL,
--	[Bez] [nvarchar](8) NULL,
--	[Sort] [smallint] NOT NULL Default 0,
--	[AbDatum] [datetime] NOT NULL,
--	[LM] [datetime] NULL,
--	[UM] [int] NULL,
--	[LC] [datetime] NULL,
--	[UC] [int] NULL,
--	CONSTRAINT [PK_Frei] PRIMARY KEY CLUSTERED (
--		[FreiId] ASC
--	)WITH FILLFACTOR = 90 ON [PRIMARY]
--) ON [PRIMARY]
--END
--GO
--GRANT SELECT ON Frei TO public

--GRANT SELECT ON Frei TO PersoAdmin
--GRANT DELETE ON Frei TO PersoAdmin
--GRANT INSERT ON Frei TO PersoAdmin
--GRANT UPDATE ON Frei TO PersoAdmin

--GRANT DELETE ON Frei TO PersoBasicDataWrite
--GRANT INSERT ON Frei TO PersoBasicDataWrite
--GRANT UPDATE ON Frei TO PersoBasicDataWrite
GO
/****** Objekt:  Table [dbo].[Jahresabschluss]    Skriptdatum: 09/18/2007 11:46:20 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Jahresabschluss]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Jahresabschluss](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[DienstplanArtenID] [int] NOT NULL,
	[ZeitKtoNr] [int] NOT NULL,
	VonJahrMonat INT NOT NULL,
	BisJahrMonat INT NOT NULL,
	Abgeschlossen BIT NOT NULL DEFAULT 0,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_Jahresabschluss] PRIMARY KEY CLUSTERED (
		[ID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON Jahresabschluss TO public

GRANT SELECT ON Jahresabschluss TO PersoAdmin
GRANT DELETE ON Jahresabschluss TO PersoAdmin
GRANT INSERT ON Jahresabschluss TO PersoAdmin
GRANT UPDATE ON Jahresabschluss TO PersoAdmin

GRANT DELETE ON Jahresabschluss TO PersoCloseWrite
GRANT INSERT ON Jahresabschluss TO PersoCloseWrite
GRANT UPDATE ON Jahresabschluss TO PersoCloseWrite

GO
/****** Objekt:  Table [dbo].[Ressourcen]    Skriptdatum: 09/18/2007 11:46:42 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Ressourcen]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Ressourcen](
	[ResID] [int] IDENTITY(1,1) NOT NULL,
	[ResBez] [varchar](50) NOT NULL,
	[ResArt] [int] NOT NULL Default 0,
	[Anzahl] [int] NOT NULL Default 0,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_Ressourcen] PRIMARY KEY CLUSTERED (
		[ResID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON Ressourcen TO public

GRANT SELECT ON Ressourcen TO PersoAdmin
GRANT DELETE ON Ressourcen TO PersoAdmin
GRANT INSERT ON Ressourcen TO PersoAdmin
GRANT UPDATE ON Ressourcen TO PersoAdmin

GRANT DELETE ON Ressourcen TO PersoBasicDataWrite
GRANT INSERT ON Ressourcen TO PersoBasicDataWrite
GRANT UPDATE ON Ressourcen TO PersoBasicDataWrite
GO
/****** Objekt:  Table [dbo].[ResAuff]    Skriptdatum: 09/18/2007 11:46:41 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ResAuff]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ResAuff](
	[ResAuffID] [int] IDENTITY(1,1) NOT NULL,
	[ResID] [int] NOT NULL ,
	[AuffNr] [int] NOT NULL ,
	[Anzahl] [int] NOT NULL Default 0,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_ResAuff] PRIMARY KEY CLUSTERED (
		[ResAuffID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON ResAuff TO public
GRANT SELECT ON ResAuff TO PersoAdmin

GRANT DELETE ON ResAuff TO PersoAdmin
GRANT INSERT ON ResAuff TO PersoAdmin
GRANT UPDATE ON ResAuff TO PersoAdmin
GO
--TO DO

--/****** Objekt:  Table [dbo].[KostenKonten]    Skriptdatum: 09/18/2007 11:46:22 ******/
--CREATE TABLE [dbo].[KostenKonten](
--	[KostenKontenId] [int] IDENTITY(1,1) NOT NULL,
--	[KontoNr] [varchar](8) NOT NULL ,
--	[KontoBez] [varchar](20) NULL,
--	[KostenArt] [int] NOT NULL Default 0,
--	[LM] [datetime] NULL,
--	[UM] [int] NULL,
--	[LC] [datetime] NULL,
--	[UC] [int] NULL,
--	CONSTRAINT [PK_KostenKonten] PRIMARY KEY CLUSTERED (
--		[KostenKontenId] ASC
--	)WITH FILLFACTOR = 90 ON [PRIMARY]
--) ON [PRIMARY]

/****** Objekt:  Table [dbo].[Kostentraeger]    Skriptdatum: 09/18/2007 11:46:23 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Kostentraeger]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Kostentraeger](
	[KstrID] [int] IDENTITY(1,1) NOT NULL,
	[KstrBezeichnung] [varchar](30) NOT NULL,
	[KstrBeschreibung] [varchar](200) NOT NULL,
	[Snr] [int] NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_Kostentraeger] PRIMARY KEY CLUSTERED (
		[KstrID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON Kostentraeger TO public

GRANT SELECT ON Kostentraeger TO PersoAdmin
GRANT DELETE ON Kostentraeger TO PersoAdmin
GRANT INSERT ON Kostentraeger TO PersoAdmin
GRANT UPDATE ON Kostentraeger TO PersoAdmin

GRANT DELETE ON Kostentraeger TO PersoBasicDataWrite
GRANT INSERT ON Kostentraeger TO PersoBasicDataWrite
GRANT UPDATE ON Kostentraeger TO PersoBasicDataWrite
GO
/****** Objekt:  Table [dbo].[Kostentraegerzeiten]    Skriptdatum: 09/18/2007 11:46:25 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Kostentraegerzeiten]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Kostentraegerzeiten](
	[KostentraegerzeitenID] [int] IDENTITY(1,1) NOT NULL,
	[DienstplanID] [int] NOT NULL,
	[KstrID] [int] NOT NULL,
	[KstrZeit] [real] NOT NULL Default 0,
	[AuffNr] [int] NOT NULL,
	[KostenId] [int] NULL,
	[Bem] [varchar](20) NULL,
	[verantwortlich] [tinyint] NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_Kostentraegerzeiten] PRIMARY KEY CLUSTERED (
		[KostentraegerzeitenID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON Kostentraegerzeiten TO public

GRANT SELECT ON Kostentraegerzeiten TO PersoAdmin
GRANT DELETE ON Kostentraegerzeiten TO PersoAdmin
GRANT INSERT ON Kostentraegerzeiten TO PersoAdmin
GRANT UPDATE ON Kostentraegerzeiten TO PersoAdmin
--TO DO
GO
/****** Objekt:  Table [dbo].[AuffDienstplanArten]    Skriptdatum: 09/18/2007 11:45:57 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[AuffDienstplanArten]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[AuffDienstplanArten](
	[AuffDienstplanArtenID] [int] IDENTITY(1,1) NOT NULL,
	[AuffNr] [int] NOT NULL,
	DienstplanArtenID [int] NOT NULL,
	[Farbe] [int] NOT NULL Default 0,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_AuffDienstplanArten] PRIMARY KEY CLUSTERED (
		[AuffDienstplanArtenID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON AuffDienstplanArten TO Public
GRANT DELETE ON AuffDienstplanArten TO Public
GRANT INSERT ON AuffDienstplanArten TO Public
GRANT UPDATE ON AuffDienstplanArten TO Public

GRANT SELECT ON AuffDienstplanArten TO PersoAdmin
GRANT DELETE ON AuffDienstplanArten TO PersoAdmin
GRANT INSERT ON AuffDienstplanArten TO PersoAdmin
GRANT UPDATE ON AuffDienstplanArten TO PersoAdmin
GO
/****** Objekt:  Table [dbo].[TransportKopf]    Skriptdatum: 09/18/2007 11:46:43 ******/
--CREATE TABLE [dbo].[TransportKopf](
--	[TransportKopfID] [int] IDENTITY(1,1) NOT NULL,
--	[SpaltenBez] [varchar](20) NULL,
--	[SpaltenSort] [tinyint] NOT NULL Default 0,
--	[LM] [datetime] NULL,
--	[UM] [int] NULL,
--	[LC] [datetime] NULL,
--	[UC] [int] NULL,
--	CONSTRAINT [PK_TransportKopf] PRIMARY KEY CLUSTERED (
--		[TransportKopfID] ASC
--	)WITH FILLFACTOR = 90 ON [PRIMARY]
--) ON [PRIMARY]
--GO
/****** Objekt:  Table [dbo].[Urlaubsberechnung]    Skriptdatum: 09/18/2007 11:46:45 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Urlaubsberechnung]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Urlaubsberechnung](
	[UrlaubsberechnungID] [int] IDENTITY(1,1) NOT NULL,
	--[ZeitKtoNr] [int] NOT NULL,
	[Tage] [smallint] NOT NULL Default 0,
	[Jahr] [smallint] NOT NULL Default 0,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_Urlaubsberechnung] PRIMARY KEY CLUSTERED (
		[UrlaubsberechnungID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON Urlaubsberechnung TO public

GRANT SELECT ON Urlaubsberechnung TO PersoAdmin
GRANT DELETE ON Urlaubsberechnung TO PersoAdmin
GRANT INSERT ON Urlaubsberechnung TO PersoAdmin
GRANT UPDATE ON Urlaubsberechnung TO PersoAdmin

GRANT DELETE ON Urlaubsberechnung TO PersoContractWrite
GRANT INSERT ON Urlaubsberechnung TO PersoContractWrite
GRANT UPDATE ON Urlaubsberechnung TO PersoContractWrite
GO
/****** Objekt:  Table [dbo].[VorlageDP]    Skriptdatum: 09/18/2007 11:46:52 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[VorlageDP]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[VorlageDP](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[SGName] [tinyint] NOT NULL Default 8,
	[SGZeiten] [tinyint] NOT NULL Default 8,
	[SGAZ] [tinyint] NOT NULL Default 8,
	[SGSumme] [tinyint] NOT NULL Default 8,
	[SGDatum] [tinyint] NOT NULL Default 8,
	[BrName] [smallint] NOT NULL Default 1000,
	[BrZeiten] [smallint] NOT NULL Default 1000,
	[BrAz] [smallint] NOT NULL Default 0,
	[BrSumme] [smallint] NOT NULL Default 0,
	[TextL] [nvarchar](30) NULL,
	[TextM] [nvarchar](30) NULL,
	[TextR] [nvarchar](30) NULL,
	[DPName] [nvarchar](30) NOT NULL,
	[QFormat] [bit] NOT NULL Default 0,
	[Format] [tinyint] NOT NULL Default 0,
	[FtNachweis] [bit] NOT NULL Default 0,
	[ZyNachweis] [bit] NOT NULL Default 0,
	[Farben] [bit] NOT NULL Default 0,
	[GtCr] [bit] NOT NULL Default 0,
	[FettName] [bit] NOT NULL Default 0,
	[WoUB] [bit] NOT NULL Default 0,
	[Frei] [bit] NOT NULL Default 0,
	[Zeilen] [tinyint] NOT NULL Default 1,
	[Urlaub] [bit] NOT NULL Default 0,
	[FreiFt] [bit] NOT NULL Default 0,
	[farbenAZ] [bit] NOT NULL Default 0,
	[Morgens] [int] NULL,
	[Mittag] [int] NULL,
	[Abends] [int] NULL,
	[Spalten] [smallint] NOT NULL Default 1,
	[ZeitLang] [int] NOT NULL Default 0,
	[BrVortrag] [smallint] NOT NULL Default 0,
	[BrSoll] [smallint] NOT NULL Default 0,
	[BrSaldo] [smallint] NOT NULL Default 0,
	[ExportNach] [smallint] NOT NULL Default 0,
	[keineLeerZeilen] [bit] NOT NULL Default 0,
	[Zulagen] [bit]  NOT NULL Default 0,
	[BrGes] [smallint] NOT NULL Default 0,
	[SgBem] [smallint] NOT NULL Default 8,
	[RandL] [smallint] NOT NULL Default 800,
	[RandR] [smallint] NOT NULL Default 800,
	[RandO] [smallint] NOT NULL Default 800,
	[RandU] [smallint] NOT NULL Default 800,
	[Schrift] [varchar](30) NULL,
	[Printer] [varchar](100) NULL,
	[SchichtProTag] [bit] NOT NULL Default 0,
	[Rowheight0] [smallint] NOT NULL Default -1,
	[Rowheight1] [smallint] NOT NULL Default -1,
	[AusrichtungNachSchicht] [bit] NOT NULL Default 0,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_VorlageDP] PRIMARY KEY CLUSTERED (
		[ID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON VorlageDP TO public

GRANT SELECT ON VorlageDP TO PersoAdmin
GRANT DELETE ON VorlageDP TO PersoAdmin
GRANT INSERT ON VorlageDP TO PersoAdmin
GRANT UPDATE ON VorlageDP TO PersoAdmin

GRANT DELETE ON VorlageDP TO PersoPrintLayoutWrite
GRANT INSERT ON VorlageDP TO PersoPrintLayoutWrite
GRANT UPDATE ON VorlageDP TO PersoPrintLayoutWrite
GO



/****** Objekt:  Table [dbo].[ZulagenDienstplan]    Skriptdatum: 09/18/2007 11:47:00 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ZulagenDienstplan]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ZulagenDienstplan](
	[ZulagenDienstplanId] [int] IDENTITY(1,1) NOT NULL,
	[ZulagenNr] [int] NOT NULL, /* PK */
	[DienstplanID] [int] NOT NULL, /* PK */
	[Wert] [real] NOT NULL Default 0,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_ZulagenDienstplan] PRIMARY KEY CLUSTERED (
		[ZulagenDienstplanId] ASC /* zusammengesetzt */
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT DELETE ON ZulagenDienstplan TO Public
GRANT INSERT ON ZulagenDienstplan TO Public
GRANT SELECT ON ZulagenDienstplan TO public
GRANT UPDATE ON ZulagenDienstplan TO Public

GRANT DELETE ON ZulagenDienstplan TO PersoAdmin
GRANT INSERT ON ZulagenDienstplan TO PersoAdmin
GRANT SELECT ON ZulagenDienstplan TO PersoAdmin
GRANT UPDATE ON ZulagenDienstplan TO PersoAdmin
GO
/****** Objekt:  Table [dbo].[Zyklen]    Skriptdatum: 09/18/2007 11:47:03 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Zyklen]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Zyklen](
	[ZyklusNr] [int] IDENTITY(1,1) NOT NULL,
	[ZyklusBez] [nvarchar](10) NOT NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_Zyklen] PRIMARY KEY CLUSTERED (
		[ZyklusNr] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON Zyklen TO public

GRANT SELECT ON Zyklen TO PersoAdmin
GRANT DELETE ON Zyklen TO PersoAdmin
GRANT INSERT ON Zyklen TO PersoAdmin
GRANT UPDATE ON Zyklen TO PersoAdmin

GRANT DELETE ON Zyklen TO PersoWorkingModelWrite
GRANT INSERT ON Zyklen TO PersoWorkingModelWrite
GRANT UPDATE ON Zyklen TO PersoWorkingModelWrite
GO
/****** Objekt:  Table [dbo].[Parameter]    Skriptdatum: 09/18/2007 11:46:33 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PersoParameter]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PersoParameter]( /* Name geändert */
	[PersoParameterID] [int] IDENTITY(1,1) NOT NULL,
	[MonatsAbrechnung] [bit] NOT NULL Default 0,
	[MonatsAzProz] [int] NULL Default 0,
--	[TBZUeberStd] [real] NULL,
	[AzName] [varchar](20) NOT NULL,
	[AZMAX] [real] NOT NULL Default 0,
	[AZMIN] [real] NOT NULL Default 0,
	[AZGTMIN] [real] NOT NULL Default 0,
	[NARUHE] [real] NOT NULL Default 0,
	[NARUHEGK] [real] NOT NULL Default 0,
	[BegNachtAZ] [real] NOT NULL Default 0,
	[BegSamAZ] [real] NOT NULL Default 0,
	[TBZFt] [bit] NOT NULL Default 0,
	[TBZUrlKrk] [bit] NOT NULL Default 0,
	--[ZuschlagFürArbDplFrTag] [bit] NOT NULL,
	[Garantiestunden] [tinyint] NOT NULL Default 0,
	[MehrAzBis] [real] NOT NULL Default 0,
	[ZwischenGt] [real] NOT NULL Default 0,
	[AzvAb] [real] NOT NULL Default 0,
	--[AbbErstMehrAz] [bit] NOT NULL Default 0,
	[UrlKrkTag] [bit] NOT NULL Default 0,
	[Art] [tinyint] NOT NULL Default 0,
	[PAUSE1] [real] NOT NULL Default 0,
	[AZPAUSE1] [real] NOT NULL Default 0,
	[Pause2] [real] NOT NULL Default 0,
	[AzPause2] [real] NOT NULL Default 0,
	[RID] [int] NULL,
	[Ueberstd] [tinyint] NOT NULL Default 0,
	[EndeNachtAZ] [real] NOT NULL Default 0,
	[FtPlusMaxAZ] [smallint] NOT NULL Default 0,
	
	[ZwischenGtMin1] [real] NOT NULL Default 0,
	[ZwischenGtMin2] [real] NOT NULL Default 0,
	[Beschaeftigung] [int] NOT NULL Default 0,
	[UeberStdAb] [real] NOT NULL Default 0,
	[RuhezeitFrei] [bit] NOT NULL Default 0,
	[UrlaubTageWo] [bit] NOT NULL Default 0,
	[Bereitschaftsdienst] [bit] NOT NULL Default 0,
	[ExportBez] [varchar](10) NULL,
	[GutschriftTag] [bit] NOT NULL Default 0,
	[Freitage] [real] NOT NULL Default 0,
	[GtPause] [bit] NOT NULL Default 0,
	[RID2] [int] NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	[AzNotizen] [varchar](200) NULL,
	CONSTRAINT [PK_Parameter] PRIMARY KEY CLUSTERED (
		[PersoParameterID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON PersoParameter TO public

GRANT SELECT ON PersoParameter TO PersoAdmin
GRANT DELETE ON PersoParameter TO PersoAdmin
GRANT INSERT ON PersoParameter TO PersoAdmin
GRANT UPDATE ON PersoParameter TO PersoAdmin

GRANT DELETE ON PersoParameter TO PersoContractWrite
GRANT INSERT ON PersoParameter TO PersoContractWrite
GRANT UPDATE ON PersoParameter TO PersoContractWrite

GRANT DELETE ON VertragsVorlagen TO PersoContractWrite
GRANT INSERT ON VertragsVorlagen TO PersoContractWrite
GRANT UPDATE ON VertragsVorlagen TO PersoContractWrite

GRANT DELETE ON VertragsVorlagen TO PersoAdmin
GRANT INSERT ON VertragsVorlagen TO PersoAdmin
GRANT UPDATE ON VertragsVorlagen TO PersoAdmin
GO
/****** Objekt:  Table [dbo].[RapportSpalte]    Skriptdatum: 09/18/2007 11:46:40 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[RapportSpalte]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[RapportSpalte](
	[RSpalteID] [int] IDENTITY(1,1) NOT NULL,
	[Sort] [tinyint] NOT NULL Default 0,
	--[Ausgabe] [tinyint] NOT NULL,
	[Ausgabe] [int] NOT NULL,
	[RID] [int] NOT NULL,
	[Lohnart] [nvarchar](8) NULL,
	[Faktor] [real] NOT NULL Default 1,
	[Jahressumme] [smallint] NULL,
	--[Saldo] [smallint] NULL,
	[LohnBez] [varchar](20) NULL,
	[X] [smallint] NULL,
	[Y] [smallint] NULL,
	[inMinuten] [bit] NOT NULL Default 0,
	[LohnartX] [smallint] NULL,
	[LohnartY] [smallint] NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_RapportSpalte] PRIMARY KEY CLUSTERED (
		[RSpalteID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON RapportSpalte TO public

GRANT SELECT ON RapportSpalte TO PersoAdmin
GRANT DELETE ON RapportSpalte TO PersoAdmin
GRANT INSERT ON RapportSpalte TO PersoAdmin
GRANT UPDATE ON RapportSpalte TO PersoAdmin

GRANT DELETE ON RapportSpalte TO PersoContractWrite
GRANT INSERT ON RapportSpalte TO PersoContractWrite
GRANT UPDATE ON RapportSpalte TO PersoContractWrite
GO
/****** Objekt:  Table [dbo].[ZulagenDienstplanArt]    Skriptdatum: 09/18/2007 11:47:02 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ZulagenDienstplanArt]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ZulagenDienstplanArt](
	[ZulagenDienstplanArtId] [int] IDENTITY(1,1) NOT NULL,
	[ZulagenNr] [int] NOT NULL, /* PK */
	[DienstplanArtenID] [int] NOT NULL, /* PK */
	[Spalte] [int] NOT NULL DEFAULT 0,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_ZulagenDienstplanArt] PRIMARY KEY CLUSTERED (
		[ZulagenDienstplanArtId] ASC /* zusammengesetzt */
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON ZulagenDienstplanArt TO public

GRANT SELECT ON ZulagenDienstplanArt TO PersoAdmin
GRANT DELETE ON ZulagenDienstplanArt TO PersoAdmin
GRANT INSERT ON ZulagenDienstplanArt TO PersoAdmin
GRANT UPDATE ON ZulagenDienstplanArt TO PersoAdmin

GRANT DELETE ON ZulagenDienstplanArt TO PersoContractWrite
GRANT INSERT ON ZulagenDienstplanArt TO PersoContractWrite
GRANT UPDATE ON ZulagenDienstplanArt TO PersoContractWrite
GO
/****** Objekt:  Table [dbo].[ZyklusWochen]    Skriptdatum: 09/18/2007 11:47:05 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ZyklusWochen]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ZyklusWochen](
	[ZyklusWoID] [int] IDENTITY(1,1) NOT NULL,
	[ZyklusNr] [int] NOT NULL DEFAULT 0,
	[ZyklusTag] [tinyint] NOT NULL DEFAULT 0,
	[AztNr] [int] NOT NULL DEFAULT 0,
	[ZyklusStatus] [tinyint] NOT NULL DEFAULT 0,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_ZyklusWochen] PRIMARY KEY CLUSTERED (
		[ZyklusWoID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON ZyklusWochen TO public

GRANT SELECT ON ZyklusWochen TO PersoAdmin
GRANT DELETE ON ZyklusWochen TO PersoAdmin
GRANT INSERT ON ZyklusWochen TO PersoAdmin
GRANT UPDATE ON ZyklusWochen TO PersoAdmin

GRANT DELETE ON ZyklusWochen TO PersoWorkingModelWrite
GRANT INSERT ON ZyklusWochen TO PersoWorkingModelWrite
GRANT UPDATE ON ZyklusWochen TO PersoWorkingModelWrite
GO
/****** Objekt:  Table [dbo].[Dienstplan]    Skriptdatum: 09/18/2007 11:46:03 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Dienstplan]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Dienstplan](
	[DienstplanID] [int] IDENTITY(1,1) NOT NULL,
	[Datum] [datetime] NOT NULL,
	[VertragsNr] [int] NOT NULL,
	[V1] [datetime] NULL,
	[B1] [datetime] NULL,
	[V2] [datetime] NULL,
	[B2] [datetime] NULL,
	[V3] [datetime] NULL,
	[B3] [datetime] NULL,
	[Az] [real] NOT NULL DEFAULT 0,
	[Az1] [real] NOT NULL DEFAULT 0,
	[Az2] [real] NOT NULL DEFAULT 0,	
	[AztNr1] [int] NOT NULL DEFAULT 0,
	[AztNr2] [int] NOT NULL DEFAULT 0,
	[ZyklusStatus] [tinyint] NOT NULL DEFAULT 0,
	[Status] [tinyint] NOT NULL DEFAULT 0,
	[Farbe] [int] NOT NULL DEFAULT 0,
	[Bemerkung] [nvarchar](40) NULL,
	[Anmerkung] [nvarchar](40) NULL,	
	[Ft] [real] NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_Dienstplan] PRIMARY KEY CLUSTERED (
		[DienstplanID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON Dienstplan TO public
GRANT DELETE ON Dienstplan TO public
GRANT INSERT ON Dienstplan TO public
GRANT UPDATE ON Dienstplan TO public


GO
/****** Objekt:  Table [dbo].[ZeitkontenMonat]    Skriptdatum: 09/18/2007 11:46:57 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ZeitkontenMonat]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ZeitkontenMonat](
	[zmID] [int] IDENTITY(1,1) NOT NULL,	
	[VertragsNr] [int] NOT NULL, /* PK */
	[ZeitKtoNr] [int] NOT NULL, /* PK */
	[JahrMonat] [int] NOT NULL, /* PK */
	[Wert] [real] NOT NULL DEFAULT 0,
	[WertKorr] [real] NOT NULL DEFAULT 0,
	[Vortrag] [real]  NOT NULL DEFAULT 0,	
	[Anspruch] [real] NOT NULL DEFAULT 0,
	[Bem] [nvarchar](30) NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_ZeitkontenMonat] PRIMARY KEY CLUSTERED (
		[VertragsNr] ASC,
		[ZeitKtoNr] ASC, /* zusammengesetzt */
		[JahrMonat] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY],
	CONSTRAINT [IX_ZeitkontenMonat] UNIQUE NONCLUSTERED (
		[zmID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON ZeitkontenMonat TO public

GRANT SELECT ON ZeitkontenMonat TO PersoAdmin
GRANT DELETE ON ZeitkontenMonat TO PersoAdmin
GRANT INSERT ON ZeitkontenMonat TO PersoAdmin
GRANT UPDATE ON ZeitkontenMonat TO PersoAdmin

GRANT DELETE ON ZeitkontenMonat TO PersoCloseWrite
GRANT INSERT ON ZeitkontenMonat TO PersoCloseWrite
GRANT UPDATE ON ZeitkontenMonat TO PersoCloseWrite
GO
/****** Objekt:  Table [dbo].[Zeitkonten]    Skriptdatum: 09/18/2007 11:46:54 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Zeitkonten]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Zeitkonten](
	[ZeitKtoNr] [int] IDENTITY(1,1) NOT NULL,
	[Bez] [nvarchar](20) NOT NULL,
--	[Tag] [bit] NOT NULL DEFAULT 0,
	[Arbeitszeit] [tinyint] NULL,
--	[Prüfen] [tinyint] NOT NULL DEFAULT 0,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_Zeitkonten] PRIMARY KEY CLUSTERED (
		[ZeitKtoNr] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON Zeitkonten TO PersoAdmin
GO


/****** Objekt:  Table [dbo].[AZTypen]    Skriptdatum: 09/18/2007 11:46:00 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[AZTypen]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[AZTypen](
	[AZTNr] [int] IDENTITY(1,1) NOT NULL,
	[AZTBez] [varchar](15) NULL,
	[KurzBez] [nvarchar](4) NULL,
	[ZeitKtoNr] [int] NULL DEFAULT 0,
	[Farbe] [int] NOT NULL DEFAULT 0,
	[FarbeDruck] [int] NULL,
	[Sort] [int] NULL DEFAULT 0,
	[aV1] [datetime] NULL,
	[aV2] [datetime] NULL,
	[aV3] [datetime] NULL,
	[aB1] [datetime] NULL,
	[aB2] [datetime] NULL,
	[aB3] [datetime] NULL,
	[inDienstplan] [int] NULL,
	[DPGruppenID] [int] NULL,
	[AztBemerkung] [nvarchar](40) NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_AZTypen] PRIMARY KEY CLUSTERED (
		[AZTNr] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON AZTypen TO public

GRANT DELETE ON AZTypen TO PersoAdmin
GRANT INSERT ON AZTypen TO PersoAdmin
GRANT UPDATE ON AZTypen TO PersoAdmin

GRANT DELETE ON AZTypen TO PersoShiftGenericWrite
GRANT INSERT ON AZTypen TO PersoShiftGenericWrite
GRANT UPDATE ON AZTypen TO PersoShiftGenericWrite

GRANT DELETE ON AZTypen TO PersoShiftDepartmentWrite
GRANT INSERT ON AZTypen TO PersoShiftDepartmentWrite
GRANT UPDATE ON AZTypen TO PersoShiftDepartmentWrite

GRANT DELETE ON AZTypen TO PersoBasicDataWrite
GRANT INSERT ON AZTypen TO PersoBasicDataWrite
GRANT UPDATE ON AZTypen TO PersoBasicDataWrite
GO
/****** Objekt:  Table [dbo].[DienstplanArtenTabelle]    Skriptdatum: 09/18/2007 11:46:10 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DienstplanArtenTabelle]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[DienstplanArtenTabelle](
	[DienstplanArtenID] [int] IDENTITY(1,1) NOT NULL,
	[DienstplanBez] [nvarchar](10) NOT NULL,
	[DienstplanBezLang] [nvarchar](30) NULL,
	[TransportBez] [varchar](15) NULL,
	[ZeitenOben] [bit] NOT NULL DEFAULT 0,
	 SumColVisible [int] NOT NULL DEFAULT 0,
	 MAbschluss INT,
	[Morgens] [datetime] NULL,
	[Mittag] [datetime] NULL,
	[KopfZeilen] [tinyint] NOT NULL DEFAULT 0,
	[Hintergrund] [bit] NOT NULL DEFAULT 0,
	[Teilung] [tinyint] NULL,
	[DPSpalten] [tinyint] NOT NULL  DEFAULT 40,
	[SchriftMorgens] [int] NULL,
	[SchriftMittag] [int] NULL,
	[SchriftAbends] [int] NULL,
	[HintergrundMorgens] [int] NULL,
	[HintergrundMittag] [int] NULL,
	[HintergrundAbends] [int] NULL,
	[DienstProTag] [smallint] NULL,
	[Zeilen] [smallint] NULL,
	[ZulageOhneAZ] [bit] NULL,
	[DPGruppenID] [int] NULL,
	[WoAbrechnung] [bit] NULL,
	[Printer] [varchar](100) NULL,
	[VorlageDpId] [int] NULL,
	[BemIn1Zeile] [bit] NULL,
	[ColWidth] [smallint] NULL,
	[cNew] [int] NULL,
	[cEdit] [int] NULL,
	[cDel] [int] NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	[ArchivDatum] [datetime] NULL,
	CONSTRAINT [PK_DienstplanArten] PRIMARY KEY CLUSTERED (
		[DienstplanArtenID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO

GO
/****** Objekt:  Table [dbo].[Rapport]    Skriptdatum: 09/18/2007 11:46:37 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Rapport]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Rapport](
	[RID] [int] IDENTITY(1,1) NOT NULL,
	[Bez] [nvarchar](12) NOT NULL,	
	[qFormat] [bit] NOT NULL DEFAULT 0,
	[Urlaub] [bit] NOT NULL DEFAULT 0,
	[FreieTage] [bit] NOT NULL DEFAULT 0,
	[Art] [smallint] NULL,
	[Mappe] [varchar](20) NULL,
	[NNX] [smallint] NULL,
	[NNY] [smallint] NULL,
	[VNX] [smallint] NULL,
	[VNY] [smallint] NULL,
	[PnrX] [smallint] NULL,
	[PnrY] [smallint] NULL,
	[JahrX] [smallint] NULL,
	[JahrY] [smallint] NULL,
	[MonatX] [smallint] NULL,
	[MonatY] [smallint] NULL,
	[ArbeitsbereichX] [smallint] NULL,
	[ArbeitsbereichY] [smallint] NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_Rapport] PRIMARY KEY CLUSTERED (
		[RID] ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON Rapport TO public

GRANT SELECT ON Rapport TO PersoAdmin
GRANT DELETE ON Rapport TO PersoAdmin
GRANT INSERT ON Rapport TO PersoAdmin
GRANT UPDATE ON Rapport TO PersoAdmin

GRANT DELETE ON Rapport TO PersoContractWrite
GRANT INSERT ON Rapport TO PersoContractWrite
GRANT UPDATE ON Rapport TO PersoContractWrite
GO
GO
--/****** Objekt:  Table [dbo].[confirm]    Skriptdatum: 09/20/2007 19:15:22 ******/
--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[confirm]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
--BEGIN
--CREATE TABLE [dbo].[confirm](
--	[confirmID] [int] IDENTITY(1,1) NOT NULL,
--	[Tab] [varchar](50) NOT NULL,
--	[UserID] [int] NOT NULL,
--	[confirmDate] [datetime] NOT NULL,
--	[PS] [int] NOT NULL,
--	[LM] [datetime] NULL,
--	[UM] [int] NULL,
--	[LC] [datetime] NULL,
--	[UC] [int] NULL,
-- CONSTRAINT [PK_confirm] PRIMARY KEY CLUSTERED ([confirmID] ASC) ON [PRIMARY]
--) ON [PRIMARY]
--END
--GO
--GRANT SELECT ON confirm TO PersoPublic
--GRANT DELETE ON confirm TO PersoPublic
--GRANT INSERT ON confirm TO PersoPublic
--GRANT UPDATE ON confirm TO PersoPublic

--GRANT SELECT ON confirm TO PersoAdmin
--GRANT DELETE ON confirm TO PersoAdmin
--GRANT INSERT ON confirm TO PersoAdmin
--GRANT UPDATE ON confirm TO PersoAdmin
GO

/****** Objekt:  Table [dbo].[DienstplanArtenKopf]    Skriptdatum: 09/20/2007 19:19:17 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DienstplanArtenKopf]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[DienstplanArtenKopf](
	[DienstplanArtenKopfID] [int] IDENTITY(1,1) NOT NULL,
	[DienstplanArtenID] [int] NOT NULL,
	[ZrNr] [int] NOT NULL,
	[KatNr] [smallint] NOT NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
 CONSTRAINT [PK_DienstplanArtenKopf] PRIMARY KEY CLUSTERED ([DienstplanArtenKopfID] ASC) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON DienstplanArtenKopf TO public
GRANT DELETE ON DienstplanArtenKopf TO public
GRANT INSERT ON DienstplanArtenKopf TO public
GRANT UPDATE ON DienstplanArtenKopf TO public

GRANT SELECT ON DienstplanArtenKopf TO PersoAdmin
GRANT DELETE ON DienstplanArtenKopf TO PersoAdmin
GRANT INSERT ON DienstplanArtenKopf TO PersoAdmin
GRANT UPDATE ON DienstplanArtenKopf TO PersoAdmin
GO


IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'vvon' and o.id = OBJECT_ID(N'[dbo].[Vertrag]'))
BEGIN
	ALTER TABLE dbo.Vertrag ADD vVon datetime NULL, vBis datetime NULL
END
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'KontoNr' and o.id = OBJECT_ID(N'[dbo].[Kosten]'))
BEGIN
	ALTER TABLE dbo.Kosten ADD 	KontoNr VarChar(20) NULL
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Ftart' and o.id = OBJECT_ID(N'[dbo].[Feiertage]'))
ALTER TABLE dbo.Feiertage ADD Ftart tinyint NULL

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Hoch' and o.id = OBJECT_ID(N'[dbo].[Feiertage]'))
ALTER TABLE dbo.Feiertage ADD Hoch smallint NULL




IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DPBem' and o.id = OBJECT_ID(N'[dbo].[AuffDienstplanArten]'))
BEGIN
	ALTER TABLE dbo.AuffDienstplanArten ADD DPBem VarChar(50) NULL
END

go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Gruppeid' and o.id = OBJECT_ID(N'[dbo].[AufführgTabelle]'))
BEGIN
	ALTER TABLE dbo.AufführgTabelle ADD 	Gruppeid int
END


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

GO

--Feld UserID anlegen und Daten aus User (Text) umschreiben
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'UserID' and o.name = 'UserForAccess')
BEGIN

	ALTER TABLE UserForAccess ADD UserID INT 
	EXEC ('UPDATE UserForAccess SET UserID =UserPW.UserID  
		FROM UserPW INNER JOIN UserForAccess ON cast(UserForAccess.[user] AS varchar(25)) COLLATE Latin1_General_CI_AI = cast(UserPW.Username AS varchar(25)) COLLATE Latin1_General_CI_AI  
		WHERE UserForAccess.UserID IS NULL')  
END
GO

-- [USER] wird nicht mehr verwendet, in der Ursprünglichen implementierung aber not null,

--Ggf Index löschen
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[UserForAccess]')  AND name = 'USER_')
	DROP Index UserForAccess.[USER_]

--Ggf Defaultwert löschen
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aaaaaUserForAccess_PK]') )
	ALTER TABLE [dbo].[UserForAccess] DROP CONSTRAINT [aaaaaUserForAccess_PK]
go
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_UserForAccess_User]') )
	ALTER TABLE [dbo].[UserForAccess] DROP CONSTRAINT [DF_UserForAccess_User]
go
--Feld löschen
ALTER TABLE UserForAccess DROP COLUMN [USER]
Go
--Und mit Default neu anlegen
ALTER TABLE UserForAccess ADD [USER] VarChar(10) NULL  CONSTRAINT [DF_UserForAccess_User] DEFAULT  ('[Obsolete]')

go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[StückeDienstplan]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].StückeDienstplan(
	[StückeDienstplanID] [int] IDENTITY(1,1) NOT NULL,
	[Snr] [int] NOT NULL,
	DienstplanArtenID [int] NOT NULL,
	[Notiz] varchar(250),
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL
 CONSTRAINT [PK_StückeDienstplan] PRIMARY KEY CLUSTERED ([StückeDienstplanID] ASC) ON [PRIMARY]
) ON [PRIMARY]
END

GO
GRANT DELETE ON StückeDienstplan TO public
GRANT INSERT ON StückeDienstplan TO public
GRANT SELECT ON StückeDienstplan TO public
GRANT UPDATE ON StückeDienstplan TO public

GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AufführgAlle]'))
BEGIN
	DROP VIEW [dbo].[AufführgAlle]
END
GO
CREATE VIEW dbo.AufführgAlle
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
WHERE    UserName = CURRENT_USER
	AND (a.Gesperrt = 0 
		OR (SELECT IS_MEMBER('Spielplan alles lesen'))=1
		OR (SELECT PERMISSIONS(OBJECT_ID('Aufführg'))&2)=2 
) 

WITH CHECK OPTION

GO

GRANT SELECT ON AufführgAlle TO public
GRANT SELECT ON AufführgAlle TO PersoAdmin

GO
/****** Objekt:  Table [dbo].[PersPersoDetails]    Skriptdatum: 09/20/2007 20:59:27 ******/

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[VertragPerso]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].VertragPerso(
	[VertragsNr] INT NOT NULL,
	[Zyklus] INT NOT NULL DEFAULT 0,
	[ZyklusWo] INT NOT NULL DEFAULT 0,
	[AbrechnungZyklus] [bit] not NULL DEFAULT 0,
	ABId INT NOT NULL ,
	PersSort Int NOT Null DEFAULT 0,
	MaxStunden INT NOT NULL DEFAULT 0,
    FtAuszahlen BIT NOT NULL DEFAULT 0,  
    AzAuszahlenAb REAL NOT NULL DEFAULT 0,
	AzAuszahlenBis REAL NOT NULL DEFAULT 0,
	[LM] [datetime] NULL,
	[UM] INT NULL,
	[LC] [datetime] NULL,
	[UC] INT NULL

 CONSTRAINT [PK_VertragPerso] PRIMARY KEY CLUSTERED (VertragsNr ASC) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON VertragPerso TO public
REVOKE UPDATE ON VertragPerso TO public

GRANT DELETE ON VertragPerso TO PersoAdmin
GRANT INSERT ON VertragPerso TO PersoAdmin

GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'persoParameterID' and o.id = OBJECT_ID(N'[dbo].[VertragsVorlagen]'))
BEGIN
	ALTER TABLE dbo.VertragsVorlagen ADD 	persoParameterID  int  NULL 
END

GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'tsAuffTypBasisID' and o.id = OBJECT_ID(N'[dbo].[Aufftypen]'))
BEGIN
	ALTER TABLE dbo.Aufftypen ADD 	tsAuffTypBasisID  int NOT  NULL  Default 0
	exec ('update Aufftypen set tsAuffTypBasisID = 500 where aufftnr=11 and tsAuffTypBasisID = 0')
END
	
go

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CountDown]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[CountDown](
	[CountDownID] [int] IDENTITY(1,1) NOT NULL,
	[SNr] [int] NOT NULL,
	[AufftNr] [int] NOT NULL,
	[BeginnOff] [real] NULL,
	[Dauer] [real] NULL,
	[ZrNr] [int] NOT NULL Default 0,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
 CONSTRAINT [PRIMARYKEY_CountDown] PRIMARY KEY CLUSTERED ([CountDownID] ASC) ON [PRIMARY]
) ON [PRIMARY]
END
GO
GRANT SELECT ON CountDown TO Public
GRANT DELETE ON CountDown TO public
GRANT INSERT ON CountDown TO public
GRANT UPDATE ON CountDown TO public


GO


IF  NOT EXISTS (SELECT * FROM  DienstplanArtenTabelle WHERE DienstplanArtenid = 0)
BEGIN
	SET IDENTITY_INSERT DienstplanArtenTabelle  ON
	INSERT INTO DienstplanArtenTabelle(DienstplanArtenid,DienstplanBez) VALUES (0,'')
	SET IDENTITY_INSERT DienstplanArtenTabelle  OFF
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ZeitKtoNr' and o.id = OBJECT_ID(N'[dbo].[Zulagen]'))
BEGIN
	ALTER TABLE dbo.Zulagen ADD 	ZeitKtoNr int NULL
	ALTER TABLE dbo.Zulagen ADD 	DruckDP Bit
	ALTER TABLE dbo.Zulagen ADD 	[Betrag] [real] NULL 
END
go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AufführgNr'))
BEGIN
drop VIEW [dbo].[AufführgNr]
END
go
CREATE VIEW [dbo].[AufführgNr]
AS
SELECT  AufführgTabelle.AuffNr
FROM    AufführgTabelle INNER JOIN Spielzeit ON AufführgTabelle.Datum <= Spielzeit.SpzEnde AND AufführgTabelle.Datum >= Spielzeit.SpzStart LEFT OUTER JOIN
          (SELECT zrnr
            FROM UserZrAccess INNER JOIN UserPW ON UserZrAccess.userid = userPW.userid
            WHERE Username = CURRENT_USER) Uzr ON AufführgTabelle.ZRNr = Uzr.zrnr
WHERE  
   AufführgTabelle.ZRNr = Uzr.zrnr OR
    (SELECT     IS_MEMBER('Spielplan ändern')) = 1 OR
                      CURRENT_USER = 'dbo' OR
      ((SELECT     IS_MEMBER('persoAdmin')) = 1 and Gruppeid=200  )


go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[AuffTechAufgabe]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[AuffTechAufgabe](
	[AuffTechAufgabeID] [int] IDENTITY(1,1) NOT NULL,
	[AuffNr] [int] NOT NULL,
	[ArbeiterAnzahl] [int] NULL,
	[Beschreibung] [varchar](200) ,
	[ABGruppeID] [int] NOT NULL,
	[Exklusiv] [bit] NOT NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,

	[UC] [int] NULL,
 CONSTRAINT [PRIMARYKEY_AuffTechAufgabe] PRIMARY KEY CLUSTERED 
(
	[AuffTechAufgabeID] ASC
) ON [PRIMARY]) ON [PRIMARY]
END

GRANT SELECT ON AuffTechAufgabe TO public
GRANT DELETE ON AuffTechAufgabe TO public
GRANT INSERT ON AuffTechAufgabe TO public
GRANT UPDATE ON AuffTechAufgabe TO public

GRANT DELETE ON AuffTechAufgabe TO PersoAdmin
GRANT INSERT ON AuffTechAufgabe TO PersoAdmin
GRANT UPDATE ON AuffTechAufgabe TO PersoAdmin

GRANT DELETE ON AuffTechAufgabe TO [Spielplan Ändern]
GRANT INSERT ON AuffTechAufgabe TO [Spielplan Ändern]
GRANT UPDATE ON AuffTechAufgabe TO [Spielplan Ändern]
GO

GRANT SELECT ON AbPersKom TO public

GO
GRANT SELECT ON PersAgentur TO public

GRANT INSERT ON PersAgentur TO [Soli-Daten ändern]
GRANT INSERT ON PersAgentur TO [Kontaktdaten ändern]
GRANT UPDATE ON PersAgentur TO [Soli-Daten ändern]
GRANT UPDATE ON PersAgentur TO [Kontaktdaten ändern]
GRANT DELETE ON PersAgentur TO [Soli-Daten ändern]
GRANT DELETE ON PersAgentur TO [Kontaktdaten ändern]

GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Module' and o.id = OBJECT_ID(N'[dbo].[perskat]'))
BEGIN
	ALTER TABLE dbo.perskat ADD 	Module INT NOT NULL Default 0 
END
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Modul' and o.id = OBJECT_ID(N'[dbo].[Gruppe]'))
BEGIN
	ALTER TABLE dbo.Gruppe ADD 	Modul INT NOT NULL Default 0 

END

GRANT INSERT ON updatelog TO public

UPDATE Gruppe SET Modul = 0  WHERE (Modul IS NULL OR Modul = 0 ) AND Gruppeid=0
UPDATE Gruppe SET Modul = 1  WHERE (Modul IS NULL OR Modul = 0 ) AND Gruppeid=1
UPDATE Gruppe SET Modul = 2  WHERE (Modul IS NULL OR Modul = 0 ) AND Gruppeid >= 100 AND Gruppeid < 200
UPDATE Gruppe SET Modul = 4  WHERE (Modul IS NULL OR Modul = 0 ) AND Gruppeid >= 200 AND Gruppeid < 300
UPDATE Gruppe SET Modul = 8  WHERE (Modul IS NULL OR Modul = 0 ) AND Gruppeid >= 300 AND Gruppeid < 400
UPDATE Gruppe SET Modul = 16 WHERE (Modul IS NULL OR Modul = 0 ) AND Gruppeid >= 400 AND Gruppeid < 500
UPDATE Gruppe SET Modul = 32 WHERE (Modul IS NULL OR Modul = 0 ) AND Gruppeid >= 500 

--perskat -- dienstplanartenid

GRANT SELECT ON AufführgFullUpdate TO public

GRANT DELETE ON AufführgFullUpdate TO public
GRANT INSERT ON AufführgFullUpdate TO public
GRANT UPDATE ON AufführgFullUpdate TO public

GRANT INSERT ON XHDelAufführg TO public

GRANT INSERT ON XHDelBesetzung TO public

GRANT SELECT ON AufführgAlle TO public
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AZ' and o.id = OBJECT_ID(N'[dbo].[Dienstplan]'))
	ALTER TABLE dbo.Dienstplan ADD 	Az real NOT NULL Default 0 

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DienstplanEintragArtId' and o.id = OBJECT_ID(N'[dbo].[Dienstplan]'))
	ALTER TABLE dbo.Dienstplan ADD 	DienstplanEintragArtId INT NOT NULL Default 0 

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AusrichtungNachSchicht' and o.id = OBJECT_ID(N'[dbo].[VorlageDP]'))
	ALTER TABLE dbo.VorlageDP ADD 	AusrichtungNachSchicht [bit] NOT NULL Default 0 

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AZSO' and o.id = OBJECT_ID(N'[dbo].[VertragsVorlagen]'))
BEGIN
	ALTER TABLE dbo.VertragsVorlagen ADD    [AZSO] [real] NOT NULL Default 0 
	ALTER TABLE dbo.VertragsVorlagen ADD 	[AZMO] [real] NOT NULL Default 0 
	ALTER TABLE dbo.VertragsVorlagen ADD 	[AZDI] [real] NOT NULL Default 0 
	ALTER TABLE dbo.VertragsVorlagen ADD 	[AZMI] [real] NOT NULL Default 0 
	ALTER TABLE dbo.VertragsVorlagen ADD 	[AZDO] [real] NOT NULL Default 0 
	ALTER TABLE dbo.VertragsVorlagen ADD 	[AZFR] [real] NOT NULL Default 0 
	ALTER TABLE dbo.VertragsVorlagen ADD 	[AZSA] [real] NOT NULL Default 0 	
END
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AzBerechnen' and o.id = OBJECT_ID(N'[dbo].[Dienstplan]'))
BEGIN
	ALTER TABLE dbo.Dienstplan ADD 	AzBerechnen BIT NOT NULL Default 1 
END 

go
IF NOT EXISTS (SELECT * FROM DienstplanEintragArt)
BEGIN 
	SET IDENTITY_INSERT DienstplanEintragArt  ON
	INSERT INTO DienstplanEintragArt([DienstplanEintragArtId],[Bezeichnung]) VALUES (0,'PLAN')
	INSERT INTO DienstplanEintragArt([DienstplanEintragArtId],[Bezeichnung]) VALUES (1,'SOLL')
	SET IDENTITY_INSERT DienstplanEintragArt  OFF
END
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'vVon' and o.id = OBJECT_ID(N'[dbo].[Vertrag]'))
BEGIN
	ALTER TABLE dbo.Vertrag ADD 	vVon [datetime]
	ALTER TABLE dbo.Vertrag ADD 	vBis [datetime]
END
go
IF NOT 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].[Jahresabschluss]'))
	ALTER TABLE dbo.[Jahresabschluss] ADD 	[DienstplanArtenID] [int]


IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'SumColVisible' and o.id = OBJECT_ID(N'[dbo].[DienstplanArtenTabelle]'))
	ALTER TABLE dbo.DienstplanArtenTabelle ADD 	SumColVisible [int] NOT NULL  Default 0

go


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].CountDownTechAufgabe') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].CountDownTechAufgabe(
	CntDwnAufgID [int] IDENTITY(1,1) NOT NULL,
	CountDownID [int] NOT NULL,
	ArbeiterAnzahl [int] NULL,
	TechAufgabeID [int] NOT NULL,
	Beschreibung [varchar](200) ,
	[Exklusiv] [bit] NOT NULL Default (0),
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
 CONSTRAINT [PRIMARYKEY_CountDownTechAufgabe] PRIMARY KEY CLUSTERED 
([CntDwnAufgID] ASC) ON [PRIMARY]) ON [PRIMARY]
END
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Exklusiv' and o.id = OBJECT_ID(N'[dbo].[CountdownTechAufgabe]'))
	ALTER TABLE dbo.CountdownTechAufgabe ADD 	Exklusiv bit NOT NULL  Default 0
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Formel' and o.id = OBJECT_ID(N'[dbo].[Zeitkonten]'))
	ALTER TABLE dbo.Zeitkonten ADD 	Formel int NOT NULL  Default 0
go

IF NOT 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]'))
BEGIN
	ALTER TABLE dbo.ZulagenDienstplan ADD 	DienstplanArtenId Datetime
END
	
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Abgeschlossen' and o.id = OBJECT_ID(N'[dbo].[Jahresabschluss]'))
BEGIN
	ALTER TABLE dbo.Jahresabschluss ADD 	Abgeschlossen Bit
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'FeiertagID' and o.id = OBJECT_ID(N'[dbo].[Feiertage]'))
BEGIN
	ALTER TABLE dbo.Feiertage ADD 	FeiertagID int IDENTITY(1,1) NOT NULL
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'UrlaubsberechnungsModellID' and o.id = OBJECT_ID(N'[dbo].[Urlaubsberechnung]'))
BEGIN
	ALTER TABLE Urlaubsberechnung ADD 	UrlaubsberechnungsModellID [int] 
END

IF  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'UrlaubsberechnungsArtenID' and o.id = OBJECT_ID(N'[dbo].[Urlaubsberechnung]'))
BEGIN
	ALTER TABLE Urlaubsberechnung DROP COLUMN	UrlaubsberechnungsArtenID 
END	
	
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AzBerechnen' and o.id = OBJECT_ID(N'[dbo].[Dienstplan]'))
BEGIN
	ALTER TABLE dbo.Dienstplan ADD 	AzBerechnen BIT NOT NULL Default 1 
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ABId' and o.id = OBJECT_ID(N'[dbo].[VertragPerso]'))
BEGIN
	ALTER TABLE dbo.VertragPerso ADD 	ABId INT  
END



go
GRANT SELECT ON Zulagen TO Public
REVOKE DELETE ON Zulagen TO public
REVOKE INSERT ON Zulagen TO public
REVOKE UPDATE ON Zulagen TO public

--zulagen + 10000
go


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[AB]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[AB] (
	[ABId] [int] IDENTITY (1, 1) NOT NULL ,
	[Bezeichnung] [varchar] (30)  NOT NULL ,
	[DienstplanArtenID] [int]  NOT NULL ,
	[Sort] [int]  NOT NULL Default 0,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL
 CONSTRAINT [PK_ABId] PRIMARY KEY CLUSTERED ([ABId] ASC) ON [PRIMARY]
) ON [PRIMARY]
END
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ABId' and o.id = OBJECT_ID(N'[dbo].[VertragPerso]'))
BEGIN
	ALTER Table AB ADD [Sort] [int]  NOT NULL Default 0
	ALTER Table VertragPerso ADD [ABId] [int]  
END
go
GRANT SELECT ON AB TO public

GRANT DELETE ON AB TO PersoAdmin
GRANT INSERT ON AB TO PersoAdmin
GRANT UPDATE ON AB TO PersoAdmin

GRANT DELETE ON AB TO PersoBasicDataWrite
GRANT INSERT ON AB TO PersoBasicDataWrite
GRANT UPDATE ON AB TO PersoBasicDataWrite
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UrlaubsberechnungsModell]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[UrlaubsberechnungsModell] (
	[UrlaubsberechnungsModellID] [int] IDENTITY (1, 1) NOT NULL ,
	[Bezeichnung] [varchar] (20)  NOT NULL ,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL
 CONSTRAINT [PK_UrlaubsberechnungsModellID] PRIMARY KEY CLUSTERED ([UrlaubsberechnungsModellID] ASC) ON [PRIMARY]
) ON [PRIMARY]
END

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UrlaubsberechnungsArten]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
DROP TABLE UrlaubsberechnungsArten
END
GRANT SELECT ON UrlaubsberechnungsModell TO public

GRANT SELECT ON UrlaubsberechnungsModell TO PersoAdmin
GRANT DELETE ON UrlaubsberechnungsModell TO PersoAdmin
GRANT INSERT ON UrlaubsberechnungsModell TO PersoAdmin
GRANT UPDATE ON UrlaubsberechnungsModell TO PersoAdmin

GRANT DELETE ON UrlaubsberechnungsModell TO PersoContractWrite
GRANT INSERT ON UrlaubsberechnungsModell TO PersoContractWrite
GRANT UPDATE ON UrlaubsberechnungsModell TO PersoContractWrite


go
IF NOT 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].[ZulagenDienstplanArt]'))
EXEC sp_rename 'ZulagenDienstplanArt.DienstplanArt', 'DienstplanArtenID', 'COLUMN'

go


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Dienstplan_DienstplanEintragArt]') AND type = 'F')
ALTER TABLE [dbo].[Dienstplan]  WITH CHECK ADD  CONSTRAINT [FK_Dienstplan_DienstplanEintragArt] FOREIGN KEY([DienstplanEintragArtId])
REFERENCES [dbo].[DienstplanEintragArt] ([DienstplanEintragArtId])
GO
ALTER TABLE [dbo].[Dienstplan] CHECK CONSTRAINT [FK_Dienstplan_DienstplanEintragArt]

GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_persoParameter_Rapport]') AND type = 'F')
ALTER TABLE [dbo].[persoParameter]  WITH CHECK ADD  CONSTRAINT [FK_persoParameter_Rapport] FOREIGN KEY([RID])
REFERENCES [dbo].[Rapport] ([RID])
GO
ALTER TABLE [dbo].[persoParameter] CHECK CONSTRAINT [FK_persoParameter_Rapport]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_RapportSpalte_Rapport]') AND type = 'F')
ALTER TABLE [dbo].[RapportSpalte]  WITH CHECK ADD  CONSTRAINT [FK_RapportSpalte_Rapport] FOREIGN KEY([RID])
REFERENCES [dbo].[Rapport] ([RID])
GO
ALTER TABLE [dbo].[RapportSpalte] CHECK CONSTRAINT [FK_RapportSpalte_Rapport]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ZeitkontenMonat_Vertrag]') AND type = 'F')
ALTER TABLE [dbo].[ZeitkontenMonat]  WITH CHECK ADD  CONSTRAINT [FK_ZeitkontenMonat_Vertrag] FOREIGN KEY([VertragsNr])
REFERENCES [dbo].[Vertrag] ([VertragsNr])
GO
ALTER TABLE [dbo].[ZeitkontenMonat] CHECK CONSTRAINT [FK_ZeitkontenMonat_Vertrag]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ZeitkontenMonat_Zeitkonten]') AND type = 'F')
ALTER TABLE [dbo].[ZeitkontenMonat]  WITH CHECK ADD  CONSTRAINT [FK_ZeitkontenMonat_Zeitkonten] FOREIGN KEY([ZeitKtoNr])
REFERENCES [dbo].[Zeitkonten] ([ZeitKtoNr])
GO
ALTER TABLE [dbo].[ZeitkontenMonat] CHECK CONSTRAINT [FK_ZeitkontenMonat_Zeitkonten]
GO
--2008-08-18 TOK mit DELETE CASCADE
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ZulagenDienstplanArt_DienstplanArten]') AND type = 'F')
	ALTER TABLE [dbo].[ZulagenDienstplanArt] DROP CONSTRAINT [FK_ZulagenDienstplanArt_DienstplanArten]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ZulagenDienstplanArt_DienstplanArten2]') AND type = 'F')
ALTER TABLE [dbo].[ZulagenDienstplanArt]  WITH CHECK ADD  CONSTRAINT [FK_ZulagenDienstplanArt_DienstplanArten2] FOREIGN KEY([DienstplanArtenID])
REFERENCES [dbo].[DienstplanArtenTabelle] ([DienstplanArtenID]) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ZulagenDienstplanArt] CHECK CONSTRAINT [FK_ZulagenDienstplanArt_DienstplanArten2]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ZulagenDienstplanArt_Zulagen]') AND type = 'F')
ALTER TABLE [dbo].[ZulagenDienstplanArt]  WITH CHECK ADD  CONSTRAINT [FK_ZulagenDienstplanArt_Zulagen] FOREIGN KEY([ZulagenNr])
REFERENCES [dbo].[Zulagen] ([ZulagenNr])
GO
ALTER TABLE [dbo].[ZulagenDienstplanArt] CHECK CONSTRAINT [FK_ZulagenDienstplanArt_Zulagen]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Jahresabschluss_DienstplanArten]') AND type = 'F')
ALTER TABLE [dbo].[Jahresabschluss]  WITH CHECK ADD  CONSTRAINT [FK_Jahresabschluss_DienstplanArten] FOREIGN KEY([DienstplanArtenID])
REFERENCES [dbo].[DienstplanArtentabelle] ([DienstplanArtenID])
GO
ALTER TABLE [dbo].[Jahresabschluss] CHECK CONSTRAINT [FK_Jahresabschluss_DienstplanArten]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_AuffDienstplanArten_Aufführg]') AND type = 'F')
ALTER TABLE dbo.AuffDienstplanArten ADD CONSTRAINT	FK_AuffDienstplanArten_Aufführg FOREIGN KEY	(AuffNr	)
REFERENCES dbo.AufführgTabelle	(AuffNr	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AuffDienstplanArten] CHECK CONSTRAINT [FK_AuffDienstplanArten_Aufführg]
Go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_AuffDienstplanArten_DienstplanArten]') AND type = 'F')
ALTER TABLE dbo.AuffDienstplanArten ADD CONSTRAINT	FK_AuffDienstplanArten_DienstplanArten FOREIGN KEY	(DienstplanArtenID)
REFERENCES dbo.DienstplanArtentabelle	(DienstplanArtenID) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AuffDienstplanArten] CHECK CONSTRAINT [FK_AuffDienstplanArten_Aufführg]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ZulagenDienstplan_Dienstplan]') AND type = 'F')
ALTER TABLE dbo.ZulagenDienstplan ADD CONSTRAINT	FK_ZulagenDienstplan_Dienstplan FOREIGN KEY	(DienstplanID)
REFERENCES dbo.Dienstplan	(DienstplanID) ON DELETE CASCADE
GO
ALTER TABLE [dbo].ZulagenDienstplan CHECK CONSTRAINT FK_ZulagenDienstplan_Dienstplan
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ZulagenDienstplan_Zulagen]') AND type = 'F')
ALTER TABLE dbo.ZulagenDienstplan ADD CONSTRAINT	FK_ZulagenDienstplan_Zulagen FOREIGN KEY	([ZulagenNr])
REFERENCES dbo.Zulagen	([ZulagenNr]) 
GO
ALTER TABLE [dbo].ZulagenDienstplan CHECK CONSTRAINT FK_ZulagenDienstplan_Zulagen


GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ZyklusWochen_Zyklen]') AND type = 'F')
ALTER TABLE dbo.ZyklusWochen ADD CONSTRAINT	FK_ZyklusWochen_Zyklen FOREIGN KEY	([ZyklusNr])
REFERENCES dbo.Zyklen([ZyklusNr]) 
GO
ALTER TABLE [dbo].ZyklusWochen CHECK CONSTRAINT FK_ZyklusWochen_Zyklen
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Dienstplan_AzTypen1]') AND type = 'F')
ALTER TABLE dbo.Dienstplan ADD CONSTRAINT	FK_Dienstplan_AzTypen1 FOREIGN KEY	([AztNr1])
REFERENCES dbo.AzTypen ([AztNr]) 
GO
ALTER TABLE [dbo].Dienstplan CHECK CONSTRAINT FK_Dienstplan_AzTypen1
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Dienstplan_AzTypen2]') AND type = 'F')
ALTER TABLE dbo.Dienstplan ADD CONSTRAINT	FK_Dienstplan_AzTypen2 FOREIGN KEY	([AztNr2])
REFERENCES dbo.AzTypen ([AztNr]) 
GO
ALTER TABLE [dbo].Dienstplan CHECK CONSTRAINT FK_Dienstplan_AzTypen2
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_AzTypen_Zeitkonten]') AND type = 'F')
ALTER TABLE dbo.AzTypen ADD CONSTRAINT	FK_AzTypen_Zeitkonten FOREIGN KEY	([ZeitKtoNr])
REFERENCES dbo.Zeitkonten ([ZeitKtoNr]) 
GO
ALTER TABLE [dbo].AzTypen CHECK CONSTRAINT FK_AzTypen_Zeitkonten
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_RapportSpalte_Rapport]') AND type = 'F')
ALTER TABLE dbo.RapportSpalte ADD CONSTRAINT	FK_RapportSpalte_Rapport FOREIGN KEY	([Rid])
REFERENCES dbo.Rapport ([Rid]) 
GO
ALTER TABLE [dbo].RapportSpalte CHECK CONSTRAINT FK_RapportSpalte_Rapport
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_DienstplanArtenKopf_DienstplanArten]') AND type = 'F')
ALTER TABLE dbo.DienstplanArtenKopf ADD CONSTRAINT	FK_DienstplanArtenKopf_DienstplanArten FOREIGN KEY	([DienstplanArtenID])
REFERENCES dbo.DienstplanArtenTabelle ([DienstplanArtenID])  ON DELETE CASCADE
GO
ALTER TABLE [dbo].DienstplanArtenKopf CHECK CONSTRAINT FK_DienstplanArtenKopf_DienstplanArten
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_DienstplanArtenKopf_Zr]') AND type = 'F')
ALTER TABLE dbo.DienstplanArtenKopf ADD CONSTRAINT	FK_DienstplanArtenKopf_Zr FOREIGN KEY	([ZrNr])
REFERENCES dbo.Zr ([ZrNr])  ON DELETE CASCADE
GO
ALTER TABLE [dbo].DienstplanArtenKopf CHECK CONSTRAINT FK_DienstplanArtenKopf_Zr
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_StückeDienstplan_DienstplanArten]') AND type = 'F')
ALTER TABLE dbo.StückeDienstplan ADD CONSTRAINT	FK_StückeDienstplan_DienstplanArten FOREIGN KEY	([DienstplanArtenID])
REFERENCES dbo.DienstplanArtenTabelle ([DienstplanArtenID])  ON DELETE CASCADE
GO
ALTER TABLE [dbo].StückeDienstplan CHECK CONSTRAINT FK_StückeDienstplan_DienstplanArten
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_StückeDienstplan_Stücke]') AND type = 'F')
ALTER TABLE dbo.StückeDienstplan ADD CONSTRAINT	FK_StückeDienstplan_Stücke FOREIGN KEY	([Snr])
REFERENCES dbo.Stücke ([Snr])  ON DELETE CASCADE
GO
ALTER TABLE [dbo].StückeDienstplan CHECK CONSTRAINT FK_StückeDienstplan_Stücke
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_VertragPerso_Vertrag]') AND type = 'F')
ALTER TABLE dbo.VertragPerso ADD CONSTRAINT	FK_VertragPerso_Vertrag FOREIGN KEY	([VertragsNr])
REFERENCES dbo.Vertrag ([VertragsNr]) 
GO
ALTER TABLE [dbo].VertragPerso CHECK CONSTRAINT FK_VertragPerso_Vertrag
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_VertragPerso_AB]') AND type = 'F')
ALTER TABLE dbo.VertragPerso ADD CONSTRAINT	FK_VertragPerso_AB FOREIGN KEY	([ABId])
REFERENCES dbo.AB ([ABId]) 
GO
ALTER TABLE [dbo].VertragPerso CHECK CONSTRAINT FK_VertragPerso_AB
GO

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

	exec ('UPDATE VertragPerso SET ABID = PersKattechnr where ABID IS NULL
	ALTER TABLE VertragPerso DROP COLUMN PersKattechnr')
END
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'FtAuszahlen' and o.id = OBJECT_ID(N'[dbo].[VertragPerso]'))
BEGIN
	ALTER Table VertragPerso ADD FtAuszahlen [bit] NOT NULL DEFAULT 0  
	ALTER Table VertragPerso ADD AfzAuszahlenAb REAL NOT NULL DEFAULT 0
	ALTER Table VertragPerso ADD AzAuszahlenBis REAL NOT NULL DEFAULT 0
END


go
 IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ABGruppe]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ABGruppe] (
	[ABGruppeId] INT IDENTITY (1, 1) NOT NULL ,
	[Bezeichnung]  VARCHAR (50)  NOT NULL ,
	[LM] [datetime] NULL,
	[UM] INT NULL,
	[LC] [datetime] NULL,
	[UC] INT NULL
	CONSTRAINT [PK_ABGruppe] PRIMARY KEY CLUSTERED 
	([ABGruppeId] ASC ) ON [PRIMARY]) ON [PRIMARY]
END
go

GRANT SELECT ON ABGruppe TO Public


GRANT DELETE ON ABGruppe TO PersoAdmin
GRANT INSERT ON ABGruppe TO PersoAdmin
GRANT UPDATE ON ABGruppe TO PersoAdmin


GRANT DELETE ON ABGruppe TO PersoBasicDataWrite
GRANT INSERT ON ABGruppe TO PersoBasicDataWrite
GRANT UPDATE ON ABGruppe TO PersoBasicDataWrite
go
 IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ABGruppe_AB]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ABGruppe_AB] (
	[ABGruppe_ABId] INT IDENTITY (1, 1) NOT NULL,
	[ABGruppeId] INT NOT NULL ,
	[ABId] INT NOT NULL ,
	[LM] [datetime] NULL,
	[UM] INT NULL,
	[LC] [datetime] NULL,
	[UC] INT NULL
	CONSTRAINT [PK_ABGruppe_AB] PRIMARY KEY CLUSTERED 
	([ABGruppe_ABId] ASC ) ON [PRIMARY]) ON [PRIMARY]
END
go
GRANT SELECT ON [ABGruppe_AB] TO public

GRANT SELECT ON ABGruppe_AB TO PersoAdmin
GRANT DELETE ON ABGruppe_AB TO PersoAdmin
GRANT INSERT ON ABGruppe_AB TO PersoAdmin
GRANT UPDATE ON ABGruppe_AB TO PersoAdmin

GRANT DELETE ON ABGruppe_AB TO PersoBasicDataWrite
GRANT INSERT ON ABGruppe_AB TO PersoBasicDataWrite
GRANT UPDATE ON ABGruppe_AB TO PersoBasicDataWrite
go
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ABGruppe_AB]')  AND name = 'ABGruppe_AB')
CREATE UNIQUE NONCLUSTERED INDEX ABGruppe_AB ON dbo.ABGruppe_AB
	(
	ABGruppeId,
	ABId
	) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ABGruppeID' and o.id = OBJECT_ID(N'[dbo].[BesetzungStd]'))
BEGIN

	ALTER Table BesetzungStd ADD ABGruppeID INT NULL 
	ALTER Table BesetzungStd ADD Anzahl INT NOT NULL DEFAULT 1
	ALTER Table BesetzungStd ADD AuffTNr INT NULL 

END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ABGruppe_AB_AB]') AND type = 'F')
ALTER TABLE [dbo].ABGruppe_AB DROP  CONSTRAINT ABGruppe_AB_AB

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ABGruppe_AB_ABGruppe]') AND type = 'F')
ALTER TABLE [dbo].ABGruppe_AB DROP  CONSTRAINT ABGruppe_AB_ABGruppe

Go
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ABGruppe_AB_AB]') AND type = 'F')
	ALTER TABLE dbo.ABGruppe_AB ADD CONSTRAINT	FK_ABGruppe_AB_AB FOREIGN KEY	(ABID)
	REFERENCES dbo.AB (ABID)  ON DELETE CASCADE
GO
	ALTER TABLE [dbo].ABGruppe_AB CHECK CONSTRAINT FK_ABGruppe_AB_AB

go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ABGruppe_AB_ABGruppe]') AND type = 'F')
ALTER TABLE dbo.ABGruppe_AB ADD CONSTRAINT	FK_ABGruppe_AB_ABGruppe FOREIGN KEY	(ABGruppeID)
REFERENCES dbo.ABGruppe (ABGruppeID)  ON DELETE CASCADE
GO
ALTER TABLE [dbo].ABGruppe_AB CHECK CONSTRAINT FK_ABGruppe_AB_AB
GO



IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ABGruppe_AB_ABGruppe]') AND type = 'F')
ALTER TABLE [dbo].ab DROP  CONSTRAINT ABGruppe_AB_ABGruppe
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_AB_DienstplanArten]') AND type = 'F')
ALTER TABLE dbo.AB ADD CONSTRAINT	FK_AB_DienstplanArten FOREIGN KEY	(DienstplanArtenID)
REFERENCES dbo.DienstplanArtenTabelle (DienstplanArtenID)  ON DELETE CASCADE

ALTER TABLE [dbo].AB CHECK CONSTRAINT FK_AB_DienstplanArten

GO

--###Beziehung ändern
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Dienstplan_Vertrag]') AND type = 'F')
ALTER TABLE [dbo].[Dienstplan] DROP  CONSTRAINT FK_Dienstplan_Vertrag
GO
--2013-10-25
--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Dienstplan_VertragPerso]') AND type = 'F')
--ALTER TABLE [dbo].[Dienstplan]  WITH CHECK ADD  CONSTRAINT [FK_Dienstplan_VertragPerso] FOREIGN KEY([VertragsNr])
--REFERENCES [dbo].[VertragPerso] ([VertragsNr])
--GO
--ALTER TABLE [dbo].[Dienstplan] CHECK CONSTRAINT [FK_Dienstplan_VertragPerso]
--GO
--###
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Aztypen_Zeitkonten]') AND type = 'F')
ALTER TABLE dbo.Aztypen ADD CONSTRAINT	FK_Aztypen_Zeitkonten FOREIGN KEY	(ZeitKtoNr)
REFERENCES dbo.Zeitkonten (ZeitKtoNr)  
GO
ALTER TABLE [dbo].Aztypen CHECK CONSTRAINT FK_Aztypen_Zeitkonten
GO

go
UPDATE AufführgTabelle SET Art = 0 FROM AufführgTabelle AS A LEFT JOIN Aufftypen AS T ON a.Art=T.AufftNr WHERE t.AufftNr IS NULL
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_AufführgTabelle_Aufftypen]') AND type = 'F')
ALTER TABLE dbo.AufführgTabelle ADD CONSTRAINT	FK_AufführgTabelle_Aufftypen FOREIGN KEY	(Art)
REFERENCES dbo.Aufftypen (AufftNr)  
GO
ALTER TABLE [dbo].AufführgTabelle CHECK CONSTRAINT FK_AufführgTabelle_Aufftypen

Go
IF not EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'MAbschluss' and o.id = OBJECT_ID(N'[dbo].[DienstplanArtenTabelle]'))
BEGIN
	ALTER TABLE  DienstplanArtenTabelle ADD  MAbschluss INT
	exec ('UPDATE DienstplanArtenTabelle SET MAbschluss = MAbJahr * 100 + MAbMonat')  
END

GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'VonJahrMonat' and o.id = OBJECT_ID(N'[dbo].[Jahresabschluss]'))
BEGIN
	ALTER TABLE  Jahresabschluss ADD VonJahrMonat INT 
	ALTER TABLE  Jahresabschluss ADD BisJahrMonat INT 

	
END
go
IF  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'vondatum' and o.id = OBJECT_ID(N'[dbo].[Jahresabschluss]'))
BEGIN

exec ('UPDATE jahresabschluss 
		SET vonJahrMonat = year(vondatum)*100 + month(vondatum) ,
		 bisJahrMonat =  year(bisdatum)*100  + month(bisdatum)  
	 WHERE vonJahrMonat  IS NULL')
	ALTER TABLE Jahresabschluss DROP COLUMN vondatum
	ALTER TABLE Jahresabschluss DROP COLUMN BISdatum
end 
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Wert' and o.id = OBJECT_ID(N'[dbo].[ZeitkontenMonat]'))
BEGIN

	ALTER TABLE  ZeitkontenMonat  ADD [Wert]     [real]  NOT NULL DEFAULT 0
	ALTER TABLE  ZeitkontenMonat  ADD [WertKorr] [real]  NOT NULL DEFAULT 0
	ALTER TABLE  ZeitkontenMonat  ADD [Vortrag]  [real]  NOT NULL DEFAULT 0
	ALTER TABLE  ZeitkontenMonat  ADD [Anspruch] [real]  NOT NULL DEFAULT 0
END
GO


IF  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PersKattechnr' and o.id = OBJECT_ID(N'[dbo].[VertragPerso]'))
BEGIN
	ALTER TABLE dbo.VertragPerso DROP	COLUMN PersKattechnr 
	ALTER TABLE dbo.VertragPerso
		DROP CONSTRAINT DF__VertragPe__Zyklu__6AE8EC13
END
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BackColor' and o.id = OBJECT_ID(N'[dbo].[RepArt]'))
BEGIN
	ALTER TABLE dbo.RepArt ADD BackColor INT NOT NULL DEFAULT 0
	ALTER TABLE dbo.RepArt ADD ShowInModul INT NOT NULL DEFAULT 0
	ALTER TABLE dbo.RepArt ADD Kuerzel  VARCHAR  (2)
	ALTER TABLE dbo.BesetzungStd ADD Exklusiv BIT NOT NULL DEFAULT 0
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BesRepertoireID' and o.id = OBJECT_ID(N'[dbo].[BesRepertoire]'))
BEGIN
		ALTER TABLE BesRepertoire ADD BesRepertoireID INT IDENTITY (1, 1) NOT NULL
END
GO


IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'funktion' AND o.id = OBJECT_ID(N'[dbo].persagentur') AND c.prec < 100)
BEGIN
	ALTER TABLE persagentur ALTER COLUMN funktion VARCHAR(100)
END

GO
GRANT SELECT ON BesRepertoire TO public

GRANT SELECT ON BesRepertoire TO PersoAdmin
GRANT DELETE ON BesRepertoire TO PersoAdmin
GRANT INSERT ON BesRepertoire TO PersoAdmin
GRANT UPDATE ON BesRepertoire TO PersoAdmin


GO
--GRANT DELETE ON RepArt TO PersoAdmin
GO
GRANT INSERT ON RepArt TO PersoAdmin
GO
--GRANT UPDATE ON RepArt TO PersoAdmin


GO
--ALTER TABLE dbo.AuffTechAufgabe DROP COLUMN PersKatNr
GO
IF  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TechAufgabeID' and o.id = OBJECT_ID(N'[dbo].AuffTechAufgabe'))
BEGIN


	ALTER TABLE dbo.AuffTechAufgabe
	DROP CONSTRAINT FK_AuffTechAufgabe_TechAufgabe_TechAufgabeID

	ALTER TABLE dbo.AuffTechAufgabe DROP COLUMN TechAufgabeID
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Exklusiv' and o.id = OBJECT_ID(N'[dbo].AuffTechAufgabe'))
BEGIN
	ALTER TABLE dbo.AuffTechAufgabe ADD Exklusiv BIT NOT NULL DEFAULT 0
END
GO


 

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'WoAbrechnung' and o.id = OBJECT_ID(N'[dbo].Zeitkonten'))
	Alter table Zeitkonten add WoAbrechnung  bit not null DEFAULT 0




--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_AB_DienstplanArten]') AND type = 'F')





-- 2008-03-03


IF  NOT EXISTS (SELECT * FROM  DienstplanGruppen WHERE DienstplanGruppenID = 0)
BEGIN
	SET IDENTITY_INSERT DienstplanGruppen  ON
	INSERT INTO DienstplanGruppen(DienstplanGruppenID,DienstplanGruppenBez) VALUES (0,'')
	SET IDENTITY_INSERT DienstplanGruppen  OFF
END

if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'ChorAdmin')
BEGIN
	EXEC sp_addrole @rolename = N'ChorAdmin'
END


GRANT SELECT ON VertragPerso TO public
GRANT DELETE ON VertragPerso TO ChorAdmin
GRANT INSERT ON VertragPerso TO ChorAdmin
GRANT UPDATE ON VertragPerso TO ChorAdmin


GRANT SELECT ON Zyklen TO public

GRANT SELECT ON persoParameter TO public
GRANT SELECT ON Zeitkonten TO public

GRANT SELECT ON DienstplanGruppen TO public
GRANT SELECT ON Jahresabschluss TO public
GRANT SELECT ON ZeitkontenMonat TO public



GRANT SELECT ON DienstplanArtenTabelle TO public


GRANT SELECT ON ZulagenDienstplanArt TO ChorAdmin
GRANT DELETE ON ZulagenDienstplanArt TO ChorAdmin
GRANT INSERT ON ZulagenDienstplanArt TO ChorAdmin
GRANT UPDATE ON ZulagenDienstplanArt TO ChorAdmin


GRANT DELETE ON Ab TO ChorAdmin
GRANT INSERT ON Ab TO ChorAdmin
GRANT UPDATE ON Ab TO ChorAdmin




IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ModulGruppeID' and o.id = OBJECT_ID(N'[dbo].DienstplanArtenTabelle'))
BEGIN
	ALTER TABLE DienstplanArtenTabelle ADD ModulGruppeID int NULL
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ModulGruppeID' and o.id = OBJECT_ID(N'[dbo].Vertrag'))
BEGIN
	ALTER TABLE Vertrag ADD ModulGruppeID int NOT NULL DEFAULT(0)
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Vertrag_Gruppe]') AND type = 'F')
ALTER TABLE dbo.Vertrag ADD CONSTRAINT	FK_Vertrag_Gruppe FOREIGN KEY	([ModulGruppeID])
REFERENCES dbo.Gruppe ([GruppeID])  ON DELETE CASCADE

GO
	
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TimePartitions' and o.id = OBJECT_ID(N'[dbo].[DienstplanArtenTabelle]'))
BEGIN
	ALTER TABLE dbo.[DienstplanArtenTabelle] ADD [TimePartitions] varchar(50) NULL
END
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DienstplanArten'))
BEGIN
	DROP VIEW [DienstplanArten]
END
go
			
CREATE VIEW [dbo].[DienstplanArten] 
	AS 
	SELECT DISTINCT da.*
	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 
			OR CURRENT_USER = 'dbo'
			OR (SELECT IS_MEMBER('PersoAdmin'))=1
			OR da.DienstplanArtenID = 0
			
GO
GRANT SELECT ON DienstplanArten TO public
GRANT DELETE ON DienstplanArten TO ChorAdmin
GRANT INSERT ON DienstplanArten TO ChorAdmin
GRANT UPDATE ON DienstplanArten TO ChorAdmin

GRANT DELETE ON DienstplanArten TO PersoAdmin
GRANT INSERT ON DienstplanArten TO PersoAdmin
GRANT UPDATE ON DienstplanArten TO PersoAdmin
go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DienstplanArten_Update'))
BEGIN
	drop VIEW [DienstplanArten_Update]
END
go
CREATE  VIEW [dbo].[DienstplanArten_Update] 
	AS 
	SELECT  dbo.DienstplanArtenTabelle.*
	FROM	dbo.DienstplanArtenTabelle WHERE 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	DienstplanUser			AS du	ON da.DienstplanArtenID = du.DienstplanArtenID 
				LEFT JOIN	UserPW					AS up	ON up.UserID= UG.UserID 
			WHERE up.UserName = CURRENT_USER 
					OR CURRENT_USER = 'dbo'
					OR (SELECT IS_MEMBER('PersoAdmin'))=1)

go
GRANT SELECT ON DienstplanArten_Update TO Public
GRANT UPDATE ON DienstplanArten_Update TO public


GRANT DELETE ON DienstplanArten_Update TO PersoAdmin
GRANT INSERT ON DienstplanArten_Update TO PersoAdmin


UPDATE DienstplanArtenTabelle SET ModulGruppeID = (SELECT MAX(GruppeId) FROM Gruppe WHERE Modul = 4) WHERE ModulGruppeID IS NULL
UPDATE DienstplanArtenTabelle SET ModulGruppeID = (SELECT MAX(GruppeId) FROM Gruppe WHERE Modul = 4) WHERE DienstplanArtenID IN (SELECT DienstplanArtenID FROM DienstplanArtenTabelle LEFT JOIN Gruppe ON DienstplanArtenTabelle.ModulGruppeID=Gruppe.GruppeID WHERE Gruppe.GruppeID IS NULL)
--20090622

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Department_UserGroup]') AND type = 'F')
ALTER TABLE dbo.DienstplanArtenTabelle ADD CONSTRAINT	FK_Department_UserGroup FOREIGN KEY	([ModulGruppeID])
REFERENCES dbo.Gruppe ([GruppeID])  


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Einheit' and o.id = OBJECT_ID(N'[dbo].Zeitkonten'))
BEGIN
	ALTER TABLE Zeitkonten ADD Einheit int NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS (SELECT * FROM Zeitkonten)
BEGIN
SET IDENTITY_INSERT Zeitkonten  ON
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 12  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 12          ,    'Unfall'               ,    0           ,    3011           ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 13  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 13          ,    'Jubiläumstage'        ,    0           ,    3003        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 14  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 14          ,    'Sondertage'           ,    0           ,    3000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 15  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 15          ,    'Wehrdienst'           ,    0           ,    3015           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 16  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 16          ,    'Bildung'              ,    0           ,    0           ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 17  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 17          ,    'Behördentag'          ,    0           ,    3016           ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 18  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 18          ,    'Eltenzeit'            ,    0           ,    3018           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 20  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 20          ,    'fza'                  ,    0           ,    0           ,    0            )
--DELETE FROM Zeitkonten WHERE ZeitKtoNr = 20
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 21  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 21          ,    'Frei AZ'              ,    0           ,    0           ,    0            )
--DELETE FROM Zeitkonten WHERE ZeitKtoNr = 21
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 25  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 25          ,    'Frei'                 ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 39  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 39          ,    'AZV mit TBZ'          ,    0           ,    0           ,    0            )
--DELETE FROM Zeitkonten WHERE ZeitKtoNr = 39
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 40  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 40          ,    'AZV'                  ,    0           ,    0           ,    0            )
--DELETE FROM Zeitkonten WHERE ZeitKtoNr = 40
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 41  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 41          ,    'FtAus'                ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 51  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 51          ,    'Mehr Az'              ,    0           ,    0           ,    0            )
--DELETE FROM Zeitkonten WHERE ZeitKtoNr = 51
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 52  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 52          ,    'Überstd.'             ,    0           ,    0           ,    1            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 53  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 53          ,    'Überstd.Zusch.'       ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 54  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 54          ,    'Effekt. Std'          ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 55  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 55          ,    'Br'                   ,    0           ,    0           ,    0            )
--DELETE FROM Zeitkonten WHERE ZeitKtoNr = 55
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 60  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 60          ,    'Abs.'                 ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 62  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 62          ,    'Abs ohne Az'          ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 64  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 64          ,    'Soll Az'              ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 65  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 65          ,    'Diff. Soll/Ist'       ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 66  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 66          ,    'Ist Az'               ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 67  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 67          ,    'Diff. Soll/Ist Plus'  ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 70  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 70          ,    'Überstd. nach 10'     ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 71  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 71          ,    'Überstd. nach 11'     ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 72  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 72          ,    'Überstd. nach 12'     ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 76  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 76          ,    'Überstd. voll 10'     ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 80          ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 80          ,    'Ruhezeit'             ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 81          ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 81          ,    'Ruhezeit in Std.'     ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 82          ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 82          ,    'Ruhezeit v. Std.'     ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 85          ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 85          ,    'täglich (Az-Soll)'    ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 100         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 100         ,    '1/2'                  ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 110         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 110         ,    'Zeitzulage Azv'       ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 111         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 111         ,    'Zeitzulage C3'        ,    0           ,    1303        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 112         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 112         ,    'Zeitzulage C6'        ,    0           ,    1306        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 113         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 113         ,    'Zeitzulage A26'       ,    0           ,    1302        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 114         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 114         ,    'Zeitzulage C4'        ,    0           ,    1304        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 115         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 115         ,    'Zeitzulage C5'        ,    0           ,    1305        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 116         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 116         ,    'Zeitzulage A21'       ,    0           ,    1301        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 117         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 117         ,    'Zeitzulage C7'        ,    0           ,    1307        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 170         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 170         ,    'Zulage 20'            ,    0           ,    2000        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 171         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 171         ,    'Zulage 21'            ,    0           ,    2000        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 172         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 172         ,    'Zulage 22'            ,    0           ,    2000        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 173         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 173         ,    'Zulage 23'            ,    0           ,    2000        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 174         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 174         ,    'Zulage 24'            ,    0           ,    2000        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 175         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 175         ,    'Zulage 25'            ,    0           ,    2000        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 176         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 176         ,    'Zulage 26'            ,    0           ,    2000        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 177         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 177         ,    'Zulage 27'            ,    0           ,    2000        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 178         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 178         ,    'Zulage 28'            ,    0           ,    2000        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 179         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 179         ,    'Zulage 29'            ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 180         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 180         ,    'Zulage 19'            ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 181         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 181         ,    'Zulage 10'            ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 182         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 182         ,    'Zulage 11'            ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 183         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 183         ,    'Zulage 12'            ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 184         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 184         ,    'Zulage 13'            ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 185         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 185         ,    'Zulage 14'            ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 186         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 186         ,    'Zulage 15'            ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 187         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 187         ,    'Zulage 16'            ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 188         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 188         ,    'Zulage 17'            ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 189         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 189         ,    'Zulage 18'            ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 190         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 190         ,    'Zulage 1'             ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 191         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 191         ,    'Zulage 2'             ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 192         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 192         ,    'Zulage 3'             ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 193         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 193         ,    'Zulage 4'             ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 194         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 194         ,    'Zulage 5'             ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 195         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 195         ,    'Zulage 6'             ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 196         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 196         ,    'Zulage 7'             ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 197         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 197         ,    'Zulage 8'             ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 198         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 198         ,    'Zulage 9'             ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 199         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 199         ,    'Zulage 10'            ,    0           ,    2000        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 200         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 200         ,    'Nacht'                ,    0           ,    1200        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 201         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 201         ,    'Sa'                   ,    0           ,    1201        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 202         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 202         ,    'So'                   ,    0           ,    1202        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 203         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 203         ,    'Arb.a.Dpf.Tag'        ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 204         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 204         ,    'So. u. Ft. Änderung'  ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 205         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 205         ,    'Sa. Änderung'         ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 206         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 206         ,    'Dreiteiler'           ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 207         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 207         ,    'Frei So'              ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 208         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 208         ,    'Inkonvenienzen '      ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 209         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 209         ,    'TBZ in Std'           ,    0           ,    1203        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 210         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 210         ,    'TBZ'                  ,    0           ,    1204        ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 211         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 211         ,    'Bereitschaft'         ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 212         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 212         ,    'Bereitschaft Ft'      ,    0           ,    0           ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 213         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung, Einheit) VALUES ( 213,    'Urlaub in Stunden'    ,    0           ,    1210        ,    0 ,1         )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 214         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung, Einheit) VALUES ( 214,    'Krank in Stunden'     ,    0           ,    1211        ,    0 ,1         )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 220         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 220         ,    'Wo.Ft.m.Ausg.'        ,    0           ,    0           ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 221         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 221         ,    'Wo.Ft.ohne Ausg.'     ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 222         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 222         ,    'vor Ft.St.pfli.'      ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 223         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 223         ,    'vor Ft.St.frei'       ,    0           ,    0           ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 224         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 224         ,    'So.Ft.m.Ausg.'        ,    0           ,    0           ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 225         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 225         ,    'So.Ft.ohne.Ausg.'     ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 230         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 230         ,    'Ft in Guthaben'       ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 231         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 231         ,    'Ft Stunden'           ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 232         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 232         ,    'WoFt Frei Stunden'    ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 235         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 235         ,    'Ft Nachweis'          ,    0           ,    0           ,    0            )
--IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 250         ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 250         ,    'Prozent'              ,    0           ,    0           ,    0            )
--DELETE FROM Zeitkonten WHERE ZeitKtoNr = 250
SET IDENTITY_INSERT Zeitkonten  OFF
END
GO

SET IDENTITY_INSERT Zeitkonten  ON
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 1   ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 1           ,    'Arbeitszeit'          ,    0           ,    0           ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 10  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 10          ,    'Urlaub'               ,    0           ,    3010        ,    0            )
IF  NOT EXISTS (SELECT * FROM  Zeitkonten WHERE ZeitKtoNr= 11  ) INSERT INTO Zeitkonten   (ZeitKtoNr, Bez,Arbeitszeit,Formel,WoAbrechnung) VALUES ( 11          ,    'Krank'                ,    0           ,    3011           ,    0            )
SET IDENTITY_INSERT Zeitkonten OFF
GO

IF  NOT EXISTS (SELECT * FROM  Aztypen WHERE AztNr = 0)
BEGIN
	SET IDENTITY_INSERT Aztypen  ON
	INSERT INTO Aztypen(AztNr,zeitktonr) VALUES (0,1)
	SET IDENTITY_INSERT Aztypen  OFF
END

GO
--2008-09-03
--UPDATE Zeitkonten SET Formel = 1203,Einheit = 1 WHERE  zeitktoNr = 209 AND Formel <> 1203 
--UPDATE Zeitkonten SET Formel = 1204 WHERE  zeitktoNr = 210 AND Formel <> 1204 

--UPDATE Zeitkonten SET Formel = 3010 WHERE  zeitktoNr = 10 AND Formel <> 3010
--UPDATE Zeitkonten SET Formel = 3011 WHERE  zeitktoNr = 11 AND Formel <> 3011
--UPDATE Zeitkonten SET Formel = 3013 WHERE  zeitktoNr = 13 AND Formel <> 3013
--UPDATE Zeitkonten SET Formel = 3015 WHERE  zeitktoNr = 15 AND Formel <> 3015
--UPDATE Zeitkonten SET Formel = 3017 WHERE  zeitktoNr = 17 AND Formel <> 3017
--UPDATE Zeitkonten SET Formel = 3018 WHERE  zeitktoNr = 18 AND Formel <> 3018
GO
--2008 04 18
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ModulGruppeIDWrite' and o.id = OBJECT_ID(N'[dbo].AuffTypen'))
BEGIN
	ALTER TABLE AuffTypen ADD ModulGruppeIDWrite int NOT NULL DEFAULT (1)
END


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BackColor' and o.id = OBJECT_ID(N'[dbo].AuffTypen'))
BEGIN
	ALTER TABLE AuffTypen ADD BackColor int NULL 
END

--2008 04 22


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

Go

CREATE VIEW [dbo].[Besetzung_Update]
AS
		SELECT   C.*
	FROM  BesetzungTabelle		AS C 
	WHERE RolleID IS NULL OR RolleID IN (SELECT ID FROM BesetzungStd AS BS
		WHERE (PERMISSIONS(OBJECT_ID('Besetzung'))&2) = 2 OR
		Besitzer IN 
			(
			SELECT GruppeID 
			FROM UserGruppe   
				INNER JOIN UserPW ON UserGruppe.Userid   = UserPW.Userid 
			WHERE (BerechtigungsbereichID = 2 OR BerechtigungsbereichID = 4)  
			AND schreiben <> 0 
			AND Username = CURRENT_USER)
			)
WITH CHECK OPTION


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'[dbo].AbGruppe'))
BEGIN
	ALTER TABLE AbGruppe ADD Sort int NOT NULL DEFAULT (0)
END

--2008-04-29


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'InReport' and o.id = OBJECT_ID(N'[dbo].RapportSpalte'))
BEGIN
	ALTER TABLE RapportSpalte ADD InReport int NOT NULL DEFAULT (0)
END






--Sollte das erstellen des INDEX iVertragsNrDatumDienstplanEintragArtId
--fehlschlagen sind bereits Doppelte Werte vorhanden - mit folgendender Abfrage
--können diese entfernt werden 
--!!ACHTUNG!! 
--vorher prüfen!!!
DELETE FROM Dienstplan WHERE Dienstplanid IN (
SELECT   max(Dienstplanid)
	FROM Dienstplan
	GROUP BY  Datum, VertragsNr, DienstplanEintragArtId
	HAVING Count(*) > 1)



IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Dienstplan]')  AND name = 'iVertragsNrDatumDienstplanEintragArtId')
BEGIN
CREATE UNIQUE NONCLUSTERED INDEX iVertragsNrDatumDienstplanEintragArtId ON dbo.Dienstplan
	(
	Datum,
	VertragsNr,
	DienstplanEintragArtId
	) ON [PRIMARY]
END
GO


--Perso Verträge
UPDATE Vertrag SET ModulGruppeID=200 
	WHERE ModulGruppeID = 0 AND 
		VertragsNr 	in (
		SELECT Vertrag.vertragsnr 
		FROM Vertrag 
		INNER JOIN VertragsVorlagen as vv On Vertrag.VorlagenID = vv.VorlagenID 
		WHERE Vart = 200)

--Dispo Verträge
UPDATE Vertrag SET ModulGruppeID=1 WHERE ModulGruppeID=0 

GO


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BerechtigungsbereichID' and o.id = OBJECT_ID(N'[dbo].UserGruppe'))
BEGIN
	ALTER TABLE UserGruppe ADD BerechtigungsbereichID INT NOT NULL DEFAULT (0)

END

GO


--Modified 2008-05-05 (AbVertrag) auf "ModulGruppeID"
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbVertrag'))
BEGIN
DROP VIEW [dbo].[AbVertrag]
END
go
CREATE VIEW [dbo].[AbVertrag]
AS 
SELECT  v.*  FROM  Vertrag AS v  
	INNER  JOIN	
		(SELECT DISTINCT GruppeID 
		FROM UserGruppe 
			INNER JOIN	UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE Username = CURRENT_USER AND (BerechtigungsbereichID = 1 OR BerechtigungsbereichID = 5)
		) AS UG	ON v.ModulGruppeID = UG.GruppeID

go
GRANT SELECT ON AbVertrag TO public
GRANT SELECT ON AbVertrag TO PersoAdmin
GRANT SELECT ON AbVertrag TO public
go


GRANT SELECT ON AbVertrag TO ChorAdmin
GRANT DELETE ON AbVertrag TO ChorAdmin
GRANT INSERT ON AbVertrag TO ChorAdmin
GRANT UPDATE ON AbVertrag TO ChorAdmin


IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbVertrag_Update'))
BEGIN
DROP VIEW [dbo].AbVertrag_Update
END
go
CREATE VIEW [dbo].AbVertrag_Update
AS 
SELECT * FROM Vertrag WHERE 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) AS UG
					ON v.ModulGruppeID = UG.GruppeID
		WHERE UG.Schreiben = 1)

GO
GRANT SELECT ON AbVertrag_Update TO public
GRANT SELECT ON AbVertrag_Update TO PersoAdmin
go


GRANT SELECT ON AbVertrag_Update TO ChorAdmin
GRANT DELETE ON AbVertrag_Update TO ChorAdmin
GRANT INSERT ON AbVertrag_Update TO ChorAdmin
GRANT UPDATE ON AbVertrag_Update TO ChorAdmin


GRANT SELECT ON [AbVertrag_Update] TO public

GRANT SELECT ON [AbVertrag_Update] TO PersoAdmin
GRANT DELETE ON [AbVertrag_Update] TO PersoAdmin
GRANT INSERT ON [AbVertrag_Update] TO PersoAdmin
GRANT UPDATE ON [AbVertrag_Update] TO PersoAdmin

REVOKE DELETE ON [AbVertrag_Update] TO PersoContractWrite
REVOKE INSERT ON [AbVertrag_Update] TO PersoContractWrite
REVOKE UPDATE ON [AbVertrag_Update] TO PersoContractWrite

GRANT DELETE ON [AbVertrag_Update] TO [Honorar-Daten ändern]
GRANT INSERT ON [AbVertrag_Update] TO [Honorar-Daten ändern]
GRANT UPDATE ON [AbVertrag_Update] TO [Honorar-Daten ändern]
go
GRANT INSERT ON StückeSpz TO [Honorar-Daten ändern]
GRANT UPDATE ON StückeSpz TO [Honorar-Daten ändern]
go
GRANT UPDATE ON Ring TO [Honorar-Daten ändern]
go
GRANT UPDATE ON Preise TO [Honorar-Daten ändern]
go
GRANT UPDATE ON ABPersonalDetails TO [Honorar-Daten ändern]
go

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'vrVon' and o.id = OBJECT_ID(N'[dbo].VertragRolle'))
BEGIN
	ALTER TABLE VertragRolle ADD vrVon DateTime  NULL
	ALTER TABLE VertragRolle ADD vrBis DateTime  NULL
END



GO
DELETE FROM UserGruppe WHERE UserGruppeID IN (
SELECT max(UserGruppeID)  FROM UserGruppe Group BY Gruppeid, userID,BerechtigungsbereichID  HAVING Count(*) > 1
)
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].UserGruppe')  AND name = 'iGruppeIDUserIDBerechtigungsbereichID')
BEGIN
CREATE UNIQUE NONCLUSTERED INDEX iGruppeIDUserIDBerechtigungsbereichID ON dbo.UserGruppe
	(
	GruppeID,
	UserID,
	BerechtigungsbereichID
	) ON [PRIMARY]
END
GO

--BerechtigungsbereichID 
--	0 = Kontaktdaten
--  1 = VertragsDaten
--  2 = Dispo (Schreiben, lesen können alle)

GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbVertragRolle'))
BEGIN
DROP VIEW [dbo].[AbVertragRolle]
END
GO
-- änderungshistory history
-- 2013-10-28 sh auswertung vom flag für honorare lesen und ggf. -1 bei honorarfeldern zurück geben
CREATE VIEW [dbo].[AbVertragRolle]
AS 
SELECT
	vr.VertragsNr,
	vr.RolleId,
	vr.VRID,
	vr.ProbUnbez,
	vr.AbrechnungProben,
	vr.ProbBezahltAnz,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.ProbBezahltWert ELSE -1 END AS ProbBezahltWert,
	vr.ProbVorstAnteilAnz,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.Honorar ELSE -1 END AS Honorar,
	vr.VorstAnz,
	vr.AbrechnungVs,
	vr.VorstAnzMin,
	--CASE WHEN UG.HasFeesPermission = 1 THEN vr.Ausstattungskosten ELSE -1 END AS Ausstattungskosten,
	vr.VertragRolleTS,
	vr.VorstAnzVortrag,
	--CASE WHEN UG.HasFeesPermission = 1 THEN vr.HonorarIst ELSE -1 END AS HonorarIst,
	vr.LM,
	vr.UM,
	vr.LC,
	vr.UC,
	vr.vrVon,
	vr.vrBis,
	--CASE WHEN UG.HasFeesPermission = 1 THEN vr.BonusFee ELSE -1 END AS BonusFee,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.ExtraFee ELSE -1 END AS ExtraFee,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.SalaryLevelId ELSE -1 END AS SalaryLevelId,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.CoverFee ELSE -1 END AS CoverFee,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.DayFee ELSE -1 END AS DayFee,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.TravelExpensesFlat ELSE -1 END AS TravelExpensesFlat,
	vr.ProductionId,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.OvernightExpensesFlat ELSE -1 END AS OvernightExpensesFlat,
	vr.RehearsalsCompensatedByPerformance
FROM  
	VertragRolle AS vr 
	INNER JOIN Vertrag AS v ON VR.VertragsNr = v.VertragsNr  
	INNER JOIN	(SELECT GruppeID, Schreiben, (CASE WHEN OptionsFlag & 1 <> 1 THEN 0 ELSE 1 END) AS HasFeesPermission
						FROM			UserGruppe 
						INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
						WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 1) AS UG
				ON v.ModulGruppeID = UG.GruppeID
GO

-- berechtigungen alle auf public
GRANT SELECT ON AbVertragRolle TO public
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbVertragRolle_Update'))
BEGIN
DROP VIEW [dbo].[AbVertragRolle_Update]
END
go
CREATE VIEW [dbo].[AbVertragRolle_Update]
AS 
SELECT  vr.*  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

GRANT SELECT ON AbVertragRolle_Update TO public
GRANT DELETE ON AbVertragRolle_Update TO public
GRANT INSERT ON AbVertragRolle_Update TO public
GRANT UPDATE ON AbVertragRolle_Update TO public

GO

sp_addrolemember  'Soli-Daten ändern', 'ChorAdmin'
GO

sp_addrolemember  'Soli-Daten ändern', 'PersoAdmin'
go

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Module' and o.id = OBJECT_ID(N'[dbo].VertragsVorlagen'))
BEGIN
	ALTER TABLE VertragsVorlagen ADD Module INT NOT NULL DEFAULT (0)
	
END
GO
	UPDATE VertragsVorlagen SET Module = 1 WHERE Module = 0 AND  VART <> 200
	UPDATE VertragsVorlagen SET Module = 4 WHERE Module = 0 AND VART = 200
	UPDATE VertragsVorlagen SET VART = 255 WHERE  VART = 200


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Bemerkung' and o.id = OBJECT_ID(N'[dbo].PersKom'))
BEGIN
	ALTER TABLE PersKom ADD Bemerkung VARCHAR(150)
	Print 'PersKom/Bemerkung'
END
go
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
		WHERE c.name = 'Bemerkung' AND o.id = OBJECT_ID(N'[dbo].PersKom') AND c.prec < 150)
	BEGIN
		ALTER TABLE PersKom ALTER COLUMN Bemerkung VARCHAR(150)
	END

GO

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Modul' and o.id = OBJECT_ID(N'[dbo].Gruppe'))
BEGIN
	ALTER TABLE Gruppe ADD Modul INT 
END
go


UPDATE Gruppe SET Modul=1 WHERE GruppeID<100  AND Modul = 0
UPDATE Gruppe SET Modul=2 WHERE GruppeID=100  AND Modul = 0
UPDATE Gruppe SET Modul=4 WHERE GruppeID=200  AND Modul = 0
UPDATE Gruppe SET Modul=8 WHERE GruppeID>=300 AND GruppeID<400  AND Modul = 0
UPDATE Gruppe SET Modul=16 WHERE GruppeID=400  AND Modul = 0
UPDATE Gruppe SET Modul=32 WHERE GruppeID=500  AND Modul = 0




IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AddCurrentUser'))
BEGIN
	DROP PROCEDURE dbo.AddCurrentUser
END
go
CREATE PROCEDURE dbo.AddCurrentUser
AS
BEGIN
	DECLARE @id INT
	IF  NOT EXISTS (SELECT * FROM  UserPW WHERE UserName = Current_User)
		BEGIN
			INSERT INTO UserPW( UserName, lm, lc, Um, uc) VALUES (Current_User, GetDate(), GetDate(), 0, 0)
			SELECT @id = ISNULL(scope_identity(), 0)
			UPDATE UserPW SET um = @id, uc = @id WHERE UserId =  @id
		END
	SET NOCOUNT ON;
END

go
GRANT EXECUTE ON AddCurrentUser TO Public

go

ALTER VIEW [dbo].[AufführgFullUpdate]
AS
SELECT a.*
	FROM AufführgTabelle AS a 
	WHERE   a.Datum <= dbo.AccessDatum()  
	AND ((SELECT PERMISSIONS(OBJECT_ID('Aufführg'))&2) = 2 
	OR (a.Gesperrt = 0 AND (
				a.Art IN (SELECT at.AuffTNr 
							FROM AuffTypen AS At 
								INNER JOIN Gruppe AS g ON (At.ModulGruppeIDWrite&g.Modul) = g.Modul 
								INNER JOIN UserGruppe AS Ug ON g.GruppeID = Ug.GruppeID   
								INNER JOIN UserPW ON Ug.Userid  = UserPW.Userid 
							WHERE BerechtigungsbereichID=2 AND schreiben<>0 and Username = CURRENT_USER )
				
				OR 
				a.zrnr IN (SELECT ZrNr  
							FROM UserZrAccess 
								INNER JOIN UserPW ON UserZrAccess.userid = UserPW.Userid 
							WHERE Username = CURRENT_USER))         
			 ) 
		  )

WITH CHECK OPTION

go

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ZeitenNachAzAusrichten' and o.id = OBJECT_ID(N'[dbo].VorlageDP'))
BEGIN
	ALTER TABLE VorlageDP ADD ZeitenNachAzAusrichten BIT  DEFAULT(0)
END
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ShowInModul' and o.id = OBJECT_ID(N'[dbo].PersH'))
BEGIN
	ALTER TABLE PersH ADD ShowInModul INT  
END
GO
UPDATE Persh SET ShowInModul=1 WHERE Besitzer=1 AND ShowInModul IS NULL
UPDATE Persh SET ShowInModul=2 WHERE Besitzer=100  AND ShowInModul IS NULL
UPDATE Persh SET ShowInModul=4 WHERE Besitzer>=200 AND Besitzer<300 AND ShowInModul IS NULL
UPDATE Persh SET ShowInModul=8 WHERE Besitzer>=300 AND Besitzer<400  AND ShowInModul IS NULL
GO


--2008 05 22
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AuffLayer' and o.id = OBJECT_ID(N'[dbo].VorlageDP'))
BEGIN
	ALTER TABLE VorlageDP ADD AuffLayer INT  NOT NULL  DEFAULT(0)
END
GO
-- 2008 05 23

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Bemerkung' and o.id = OBJECT_ID(N'[dbo].CountDown'))
BEGIN
	ALTER TABLE CountDown ADD Bemerkung VARCHAR(100)
END
GO

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BemerkungTechnik' and o.id = OBJECT_ID(N'[dbo].CountDown'))
BEGIN
	ALTER TABLE CountDown ADD BemerkungTechnik VARCHAR(100)
END
GO

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BemKurz' AND o.id = OBJECT_ID(N'[dbo].AufführgTabelle') AND c.prec < 100)
BEGIN
	ALTER TABLE AufführgTabelle ALTER COLUMN BemKurz VARCHAR(100)
END
GO

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BemKurz2' AND o.id = OBJECT_ID(N'[dbo].AufführgTabelle') AND c.prec < 100)
BEGIN
	ALTER TABLE AufführgTabelle ALTER COLUMN BemKurz2 VARCHAR(100)
END
GO


IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Zulagen]')  AND name = 'Index_EA74D431_B50C_4BEA')
BEGIN

DROP INDEX dbo.Zulagen.Index_EA74D431_B50C_4BEA

END
go

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Dienstplan]')  AND name = 'iDatum')
CREATE INDEX iDatum ON dbo.Dienstplan
	(Datum) ON [PRIMARY]
GO


IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Dienstplan]')  AND name = 'iVertragsNr')
CREATE INDEX iVertragsNr ON dbo.Dienstplan
	(VertragsNr) ON [PRIMARY]
GO

--2008 05 26
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TypId' and o.id = OBJECT_ID(N'[dbo].PersZusatzDatenTyp'))
BEGIN
	ALTER TABLE PersZusatzDatenTyp ADD TypId INT NOT NULL DEFAULT(0)
END
GO

UPDATE PersZusatzDatenTyp SET TypId=1 WHERE TypId=0 AND Typ = 'String'
UPDATE PersZusatzDatenTyp SET TypId=2 WHERE TypId=0 AND Typ = 'Int32' OR Typ='int'
UPDATE PersZusatzDatenTyp SET TypId=3 WHERE TypId=0 AND Typ = 'DateTime'

UPDATE PersZusatzDatenTyp SET Typ='String'   WHERE TypId=1
UPDATE PersZusatzDatenTyp SET Typ='Int32'    WHERE TypId=2
UPDATE PersZusatzDatenTyp SET Typ='DateTime' WHERE TypId=3

GO

--2008 05 30
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'StdABGruppeId' and o.id = OBJECT_ID(N'[dbo].VertragPerso'))
BEGIN
	ALTER TABLE VertragPerso ADD StdABGruppeId INT
END
GO


IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'zrBez' AND o.id = OBJECT_ID(N'[dbo].zr') AND c.prec < 60)
BEGIN
	ALTER TABLE zr ALTER COLUMN zrBez VARCHAR(60)
	Print 'WertText geändert'
END
GO
--20080711 BugFix
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'zrBez' AND o.id = OBJECT_ID(N'[dbo].zr') AND c.prec = 1000)
BEGIN
	DROP INDEX dbo.ZR.PK_ZRBez
	ALTER TABLE zr ALTER COLUMN zrBez VARCHAR(60)
	CREATE INDEX PK_ZRBez ON dbo.ZR (zrBez) ON [PRIMARY]
	Print 'WertText geändert'
END

go

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'rolle' AND o.id = OBJECT_ID(N'[dbo].besetzungstd') AND c.prec < 150)
BEGIN
	ALTER TABLE besetzungstd ALTER COLUMN rolle VARCHAR(150)
	Print 'WertText geändert'
END

--2008 06 13
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'WebPublish' and o.id = OBJECT_ID(N'[dbo].StückeDetails'))
BEGIN
	ALTER TABLE StückeDetails ADD WebPublish BIT NOT NULL DEFAULT(1)
END
GO

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'tempUserID' and o.id = OBJECT_ID(N'[dbo].UserPW'))
BEGIN
	ALTER TABLE UserPW ADD tempUserID INT
END
GO



IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ABGruppe_Person]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ABGruppe_Person] (
	[ABGruppe_PersonId] INT IDENTITY (1, 1) NOT NULL,
	[ABGruppeId] INT NOT NULL ,
	[PersNr] INT NOT NULL ,
	[LM] [datetime] NULL,
	[UM] INT NULL,
	[LC] [datetime] NULL,
	[UC] INT NULL
	CONSTRAINT [PK_ABGruppe_Person] PRIMARY KEY CLUSTERED 
	([ABGruppe_PersonId] ASC ) ON [PRIMARY]) ON [PRIMARY]
END
go
GRANT SELECT ON [ABGruppe_Person] TO public

GRANT SELECT ON [ABGruppe_Person] TO PersoAdmin
GRANT DELETE ON [ABGruppe_Person] TO PersoAdmin
GRANT INSERT ON [ABGruppe_Person] TO PersoAdmin
GRANT UPDATE ON [ABGruppe_Person] TO PersoAdmin

GRANT DELETE ON [ABGruppe_Person] TO PersoBasicDataWrite
GRANT INSERT ON [ABGruppe_Person] TO PersoBasicDataWrite
GRANT UPDATE ON [ABGruppe_Person] TO PersoBasicDataWrite
go
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ABGruppe_Person]')  AND name = 'IDX_ABGruppeId_PersNr')
CREATE UNIQUE NONCLUSTERED INDEX [IDX_ABGruppeId_PersNr] ON [dbo].[ABGruppe_Person]
	(
	[ABGruppeId],
	[PersNr]
	) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ABGruppe_Person_Persh]') AND type = 'F')
	ALTER TABLE [dbo].[ABGruppe_Person] ADD CONSTRAINT [FK_ABGruppe_Person_Persh] FOREIGN KEY (PersNr)
	REFERENCES dbo.Persh (PersNr) ON DELETE CASCADE
GO

ALTER TABLE [dbo].[ABGruppe_Person] CHECK CONSTRAINT [FK_ABGruppe_Person_Persh]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ABGruppe_Person_ABGruppe]') AND type = 'F')
	ALTER TABLE [dbo].[ABGruppe_Person] ADD CONSTRAINT [FK_ABGruppe_Person_ABGruppe] FOREIGN KEY (ABGruppeID)
	REFERENCES dbo.ABGruppe (ABGruppeID)  ON DELETE CASCADE
GO

ALTER TABLE [dbo].[ABGruppe_Person] CHECK CONSTRAINT [FK_ABGruppe_Person_ABGruppe]
GO


IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'UrlaubsberechnungsModellID' and o.id = OBJECT_ID(N'[dbo].[VertragsVorlagen]'))
BEGIN
	ALTER TABLE dbo.VertragsVorlagen ADD  UrlaubsberechnungsModellID INT 
END

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ZeitKtoNr' and o.id = OBJECT_ID(N'[dbo].Urlaubsberechnung'))
BEGIN
	ALTER TABLE Urlaubsberechnung ADD ZeitKtoNr INT NOT NULL DEFAULT (0)
END
	
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'RolleKurz' and o.id = OBJECT_ID(N'[dbo].BesetzungStd'))
BEGIN
	ALTER TABLE BesetzungStd ADD RolleKurz VARCHAR(15) 
END
go




IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ByModulScript' and o.id = OBJECT_ID(N'[dbo].NvData'))
BEGIN
	ALTER TABLE NvData ADD ByModulScript INT NOT NULL DEFAULT(0) 
	ALTER TABLE NvData ADD Major INT NOT NULL DEFAULT(0) 
	ALTER TABLE NvData ADD Minor INT NOT NULL DEFAULT(0) 
END
GO


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ExportBez' and o.id = OBJECT_ID(N'[dbo].AZTypen'))
BEGIN
	ALTER TABLE AZTypen ADD ExportBez VARCHAR(5) 
END
go



IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'StartOffset' and o.id = OBJECT_ID(N'[dbo].BesetzungStd'))
BEGIN
	ALTER TABLE BesetzungStd ADD StartOffset [real] NOT NULL DEFAULT(0) 
	ALTER TABLE BesetzungStd ADD EndOffset   [real] NOT NULL DEFAULT(0) 
END
Go

--2012-07-03 SH
--IF um die Updates drumherum gebaut damit nicht jedes mal ausgeführt
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND Major <= 1 AND Minor < 296)
BEGIN
	
--Korrektur für falschen Datumsteil, ist auch im Import geänder
--Kann raus wenn in allen DBs die bis zum 20080707 importiert wurden ausgeführt
 UPDATE AzTypen SET 
			aV1 = CASE WHEN [aV1] IS NULL THEN NULL ELSE '19000101 ' + CONVERT(varchar(5), [aV1], 108) END
           ,aB1 = CASE WHEN [aB1] IS NULL THEN NULL ELSE '19000101 ' + CONVERT(varchar(5), [aB1], 108) END
           ,aV2 = CASE WHEN [aV2] IS NULL THEN NULL ELSE '19000101 ' + CONVERT(varchar(5), [aV2], 108) END
           ,aB2 = CASE WHEN [aB2] IS NULL THEN NULL ELSE '19000101 ' + CONVERT(varchar(5), [aB2], 108) END
		   ,aV3 = CASE WHEN [aV3] IS NULL THEN NULL ELSE '19000101 ' + CONVERT(varchar(5), [aV3], 108) END
           ,aB3 = CASE WHEN [aB3] IS NULL THEN NULL ELSE '19000101 ' + CONVERT(varchar(5), [aB3], 108) END

 UPDATE Dienstplan SET 
			V1 = CASE WHEN [V1] IS NULL THEN NULL ELSE '19000101 ' + CONVERT(varchar(5), [V1], 108) END
           ,B1 = CASE WHEN [B1] IS NULL THEN NULL ELSE '19000101 ' + CONVERT(varchar(5), [B1], 108) END
           ,V2 = CASE WHEN [V2] IS NULL THEN NULL ELSE '19000101 ' + CONVERT(varchar(5), [V2], 108) END
           ,B2 = CASE WHEN [B2] IS NULL THEN NULL ELSE '19000101 ' + CONVERT(varchar(5), [B2], 108) END
		   ,V3 = CASE WHEN [V3] IS NULL THEN NULL ELSE '19000101 ' + CONVERT(varchar(5), [V3], 108) END
           ,B3 = CASE WHEN [B3] IS NULL THEN NULL ELSE '19000101 ' + CONVERT(varchar(5), [B3], 108) END

 UPDATE DienstplanArtenTabelle SET 
			Morgens ='19000101 ' + CONVERT(varchar(5), [Morgens], 108),
			Mittag = '19000101 ' + CONVERT(varchar(5), [Mittag], 108)
END
GO
 


IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AbGruppeID' and o.id = OBJECT_ID(N'[dbo].AuffTechAufgabe'))
BEGIN
	ALTER TABLE dbo.AuffTechAufgabe ADD AbGruppeID INT
	--2010 05 02 AbGruppe nicht vorhanden, alle Daten sollten übernommen sein
	--EXEC ('UPDATE AuffTechAufgabe SET AbGruppeID = AbGruppe')
END


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CreateCountDownId' and o.id = OBJECT_ID(N'[dbo].AufführgTabelle'))
BEGIN
	ALTER TABLE AufführgTabelle ADD CreateCountDownId INT
END
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CountDownId' and o.id = OBJECT_ID(N'[dbo].BesetzungStd'))
BEGIN
	ALTER TABLE BesetzungStd ADD CountDownId INT
END
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CountDownArtID' and o.id = OBJECT_ID(N'[dbo].CountDown'))
BEGIN
	ALTER TABLE CountDown ADD CountDownArtID INT NOT NULL DEFAULT(0)
END


go

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'RolleID' and o.id = OBJECT_ID(N'[dbo].AuffTechAufgabe'))
BEGIN
	ALTER TABLE AuffTechAufgabe ADD RolleID INT NOT NULL DEFAULT(0)
	DELETE FROM AuffTechAufgabe
END
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_AuffTechAufgabe_BesetzungStd]') AND type = 'F')
ALTER TABLE [dbo].[AuffTechAufgabe]  WITH CHECK ADD  CONSTRAINT [FK_AuffTechAufgabe_BesetzungStd] FOREIGN KEY([RolleID])
REFERENCES [dbo].[BesetzungStd] ([ID])

go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CountDownArt]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[CountDownArt](
	CountDownArtID [int] IDENTITY(1,1) NOT NULL,
	[Bezeichung] [varchar](100) ,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
 CONSTRAINT [PRIMARYKEY_CountDownArt] PRIMARY KEY CLUSTERED 
(
	[CountDownArtID] ASC
) ON [PRIMARY]) ON [PRIMARY]

END
GO

GRANT SELECT ON CountDownArt TO Public
GRANT DELETE ON CountDownArt TO PersoAdmin
GRANT INSERT ON CountDownArt TO PersoAdmin
GRANT UPDATE ON CountDownArt TO PersoAdmin


GO
IF  NOT EXISTS (SELECT * FROM  CountDownArt)
BEGIN
	SET IDENTITY_INSERT CountDownArt  ON
	INSERT INTO CountDownArt(CountDownArtID,Bezeichung) VALUES (0,'Standard')
	SET IDENTITY_INSERT CountDownArt  OFF
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_CountDown_CountDownArt]') AND type = 'F')
ALTER TABLE [dbo].[CountDown]  WITH CHECK ADD  CONSTRAINT [FK_CountDown_CountDownArt] FOREIGN KEY([CountDownArtID])
REFERENCES [dbo].[CountDownArt] ([CountDownArtID])
GO


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CountDownTyp' and o.id = OBJECT_ID(N'[dbo].AuffTypen'))
BEGIN
	ALTER TABLE AuffTypen ADD CountDownTyp BIT DEFAULT(0)
END
go

--2008 07 16 
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CountDownDate' and o.id = OBJECT_ID(N'[dbo].Gruppe'))
BEGIN
	ALTER TABLE Gruppe ADD CountDownDate DATETIME
END


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Pos' and o.id = OBJECT_ID(N'[dbo].AuffTechAufgabe'))
BEGIN
	ALTER TABLE AuffTechAufgabe ADD StartOffset [real] NOT NULL DEFAULT(0) 
	ALTER TABLE AuffTechAufgabe ADD EndOffset   [real] NOT NULL DEFAULT(0) 
	ALTER TABLE AuffTechAufgabe ADD Pos   [smallint] NOT NULL DEFAULT(0)
END
Go

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AutoCreate' and o.id = OBJECT_ID(N'[dbo].Countdown'))
	ALTER TABLE Countdown ADD AutoCreate BIT NOT NULL DEFAULT(1) 
GO
--2007 17 7
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CountDownDate' and o.id = OBJECT_ID(N'[dbo].Gruppe'))
	ALTER TABLE CountDownDate ADD Gruppe DATETIME 

GO
--2008 08 01
UPDATE Aufftypen Set tsAuffTypBasisID=500 Where  (tsAuffTypBasisID = 0 OR tsAuffTypBasisID IS NULL) AND (AufftBez = 'Vorstellung')
UPDATE Aufftypen Set tsAuffTypBasisID=550 Where  (tsAuffTypBasisID = 0 OR tsAuffTypBasisID IS NULL) AND (AufftKurz = 'WA')
UPDATE Aufftypen Set tsAuffTypBasisID=560 Where  (tsAuffTypBasisID = 0 OR tsAuffTypBasisID IS NULL) AND (AufftKurz = 'Prem')
UPDATE Aufftypen Set tsAuffTypBasisID=561 Where  (tsAuffTypBasisID = 0 OR tsAuffTypBasisID IS NULL) AND (AufftBez = 'Uraufführung')
GO

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Nachname' AND o.id = OBJECT_ID(N'[dbo].PersH') AND c.prec < 60)
BEGIN
	ALTER TABLE PersH ALTER COLUMN Vorname VARCHAR(60)
	ALTER TABLE PersH ALTER COLUMN Nachname VARCHAR(60)
END
GO




--***************** CountDowns Umschreiben **********************************
--UPDATE BesetzungStd SET CountDownID = c.CountDownID  FROM
--	BesetzungStd b INNER JOIN CountDown c
--		ON b.aufftNr=c.aufftnr AND b.snr = c.snr
--	
--**************** Verweiste Countdowns prüfen und ggf löschen ***********************
--select * from BesetzungStd WHERE countdownid IS NULL  AND aufftNr <> 0 AND NOT AufftNR IS NULL

GO

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AgPersNr' and o.id = OBJECT_ID(N'[dbo].VertragDetails'))
	ALTER TABLE VertragDetails ADD AgPersNr INT  
GO



IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'SollAz' and o.id = OBJECT_ID(N'[dbo].Dienstplan')) 
BEGIN
	ALTER TABLE Dienstplan ADD SollAz INT  NOT NULL DEFAULT(0)

	EXEC ('UPDATE  Dienstplan 
	SET SollAZ = CASE DATEPART(weekday, Datum)
		WHEN 1 THEN   ROUND(AZMO * 60, 0) 
		WHEN 2 THEN   ROUND(AZDI * 60, 0) 
		WHEN 3 THEN   ROUND(AZMI * 60, 0) 
		WHEN 4 THEN   ROUND(AZDO * 60, 0) 
		WHEN 5 THEN   ROUND(AZFR * 60, 0) 
		WHEN 6 THEN   ROUND(AZSA * 60, 0) 
		WHEN 7 THEN   ROUND(AZSO * 60, 0) 
		ELSE -1
	END 
	FROM  Dienstplan  
	INNER JOIN Vertrag AS v ON Dienstplan.VertragsNr=v.VertragsNr 
	INNER JOIN VertragsVorlagen AS vv ON V.VorlagenID = vv.VorlagenID
	WHERE NOT V1 IS NULL OR NOT V2 IS NULL OR NOT V3 IS NULL OR AZTNR1 > 0 OR AZTNR2 >0 ')
END







GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ZmType' and o.id = OBJECT_ID(N'[dbo].[ZeitkontenMonat]'))
BEGIN

	ALTER TABLE  ZeitkontenMonat  ADD [ZmType]		[INT]  NOT NULL DEFAULT (1)
	ALTER TABLE  ZeitkontenMonat  ADD [zmSort]		[INT]  NOT NULL DEFAULT 0

	ALTER TABLE [dbo].[ZeitkontenMonat] DROP CONSTRAINT PK_ZeitkontenMonat
	ALTER TABLE [dbo].[ZeitkontenMonat] DROP CONSTRAINT IX_ZeitkontenMonat

	ALTER TABLE dbo.ZeitkontenMonat ADD CONSTRAINT
	PK_ZeitkontenMonat PRIMARY KEY CLUSTERED 
	(zmID) ON [PRIMARY]
	

	CREATE UNIQUE NONCLUSTERED INDEX iVertragsNrDatumDienstplanEintragArtId ON [dbo].[ZeitkontenMonat]
		(VertragsNr,
		ZeitktoNr,
		JahrMonat,
		ZmType,
		zmSort) ON [PRIMARY]


	EXEC ('INSERT INTO ZeitkontenMonat (VertragsNr, ZeitktoNr, JahrMonat, Wert, lm, um, lc, uc, zmType, zmSort) 
		SELECT  VertragsNr, ZeitktoNr, JahrMonat, WertKorr, lm, um, lc, uc, 4, 0 FROM ZeitkontenMonat WHERE WertKorr<>0')

	EXEC ('INSERT INTO ZeitkontenMonat (VertragsNr, ZeitktoNr, JahrMonat, Wert, lm, um, lc, uc, zmType, zmSort) 
		SELECT  VertragsNr, ZeitktoNr, JahrMonat, Vortrag, lm, um, lc, uc, 32, 0 FROM ZeitkontenMonat WHERE Vortrag<>0')

	EXEC ('INSERT INTO ZeitkontenMonat (VertragsNr, ZeitktoNr, JahrMonat, Wert, lm, um, lc, uc, zmType, zmSort) 
		SELECT  VertragsNr, ZeitktoNr, JahrMonat, Anspruch, lm, um, lc, uc, 16, 0 FROM ZeitkontenMonat WHERE Anspruch<>0')
END


GO

UPDATE KenntnisDel Set KenntnisDel.um = UserPW.userid, KenntnisDel.uc = UserPW.userid, KenntnisDel.lm = KenntnisDel.ViewTime, KenntnisDel.lc = KenntnisDel.ViewTime FROM KenntnisDel LEFT JOIN UserPW ON KenntnisDel.DbUser=Userpw.Username  WHERE KenntnisDel.um IS NULL OR KenntnisDel.UC IS NULL 
UPDATE XHDelAufführg Set xhDBUser='dbo' WHERE xhDBUser='sa'
UPDATE XHDelAufführg Set XHDelAufführg.um = UserPW.userid, XHDelAufführg.uc = UserPW.userid, XHDelAufführg.lm = XHDelAufführg.XHTime, XHDelAufführg.lc = XHDelAufführg.XHTime FROM XHDelAufführg LEFT JOIN UserPW ON XHDelAufführg.xhDbUser=Userpw.Username  WHERE XHDelAufführg.um IS NULL OR  XHDelAufführg.UC IS NULL

--2008 09 01 VertragsTermine
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ContractDates]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ContractDates](
	[ContractDateId] [int] IDENTITY(1,1) NOT NULL,
	[RoleId] [int] NOT NULL,
	[ContractRoleId] [int] NOT NULL,
	[Start] [datetime] NOT NULL,
	[End] [datetime] NULL,
	[Note] [varchar](50) NULL,
	[IsRehearsal] [bit] NOT NULL CONSTRAINT [DF_ContractDates_IsRehearsal] DEFAULT (0),
	[IsCover] [bit] NOT NULL CONSTRAINT [DF_ContractDates_IsCover] DEFAULT (0),
	[StageId] [int] NOT NULL,
	[CastId] [int] NULL,
	[ReplacementContractDateId] [int] NULL,
	[IsCanceled] [bit] NULL CONSTRAINT [DF_ContractDates_IsCanceled] DEFAULT (0),
	[IsConfirmed] [bit] NOT NULL CONSTRAINT [DF_ContractDates_IsConfirmed] DEFAULT (0),
	[UC] [int] NOT NULL,
	[LC] [datetime] NOT NULL,
	[UM] [int] NOT NULL,
	[LM] [datetime] NULL,
	CONSTRAINT [PK_ContractDates] PRIMARY KEY CLUSTERED (
		[ContractDateId] ASC
	) ON [PRIMARY]
) ON [PRIMARY]
END
GO
--2008-09-01
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractDates_ContractRole]') AND type = 'F')
ALTER TABLE [dbo].[ContractDates]  WITH CHECK ADD  CONSTRAINT [FK_ContractDates_ContractRole] FOREIGN KEY([ContractRoleId])
REFERENCES [dbo].[VertragRolle] ([VrID])
GO
ALTER TABLE [dbo].[ContractDates] CHECK CONSTRAINT [FK_ContractDates_ContractRole]
Go

GRANT SELECT ON [dbo].[ContractDates]  TO [Honorar-Daten ändern]
GRANT DELETE ON [dbo].[ContractDates]  TO [Honorar-Daten ändern]
GRANT INSERT ON [dbo].[ContractDates]  TO [Honorar-Daten ändern]
GRANT UPDATE ON [dbo].[ContractDates]  TO [Honorar-Daten ändern]
GRANT SELECT ON [dbo].[ContractDates]  TO public
GRANT SELECT ON [dbo].[ContractDates]  TO [Honorar-Daten lesen]

--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractDates_Stages]') AND type = 'F')
--ALTER TABLE [dbo].[ContractDates]  WITH CHECK ADD  CONSTRAINT [FK_ContractDates_Stages] FOREIGN KEY([StageId])
--REFERENCES [dbo].[Zr] ([ZrNr])
--GO
--ALTER TABLE [dbo].[ContractDates] CHECK CONSTRAINT [FK_ContractDates_Stages]

--2008-09-02
--GRANT SELECT ON XHDelAufführg TO PersoPublic
--GRANT DELETE ON XHDelAufführg TO PersoPublic
GRANT INSERT ON XHDelAufführg TO public


--2008-09-08
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'InAccountID' and o.id = OBJECT_ID(N'[dbo].RapportSpalte'))
BEGIN
	ALTER TABLE RapportSpalte ADD InAccountID INT
END

GO

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PFunktion' AND o.id = OBJECT_ID(N'[dbo].PersH') AND c.prec < 80)
BEGIN
	ALTER TABLE PersH ALTER COLUMN PFunktion VARCHAR(80)
	Print 'WertText geändert'
END
GO
DELETE FROM Personaldetails WHERE Pnr IN (select d.pnr from Persh as p RIGHT Join Personaldetails  as d
ON p.Persnr = d.pnr WHERE p.Persnr is null)
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[BankAccount]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[BankAccount](
	[BankAccountID] [int] IDENTITY(1,1) NOT NULL,
	[PersID] [int] NOT NULL,
	[Sort] [int] NOT NULL,
	[BankName] [varchar](50) NULL,
	[City] [varchar](50)  NULL,
	[PostalCode] [varchar](50) NULL,
	[CountryCode] [varchar](50) NULL,
	[SWIFTNumber] [varchar](50)  NULL,
	[Iban] [varchar](50) NULL,
	[BankCode] [varchar](50) NULL,
	[AccountNumber] [varchar](50) NULL,
	[AccountHolder] [varchar](50)  NULL,
	[Note] [varchar](200)  NULL,
	[LC] [datetime] NOT NULL,
	[UC] [int] NOT NULL,
	[LM] [datetime] NOT NULL,
	[UM] [int] NOT NULL,
 CONSTRAINT [PK_bank] PRIMARY KEY CLUSTERED 
(
	[BankAccountID] ASC
) ON [PRIMARY]
) ON [PRIMARY]

exec ('INSERT INTO [BankAccount] ([PersID],[BankName], [BankCode],[AccountNumber],[AccountHolder], sort, lc,uc,lm,um )
SELECT pnr,Bank,BLZ,KtoNr,KtoInhaber,0, GETDATE(),0,GETDATE(), 0 FROM PersonalDetails')

END

GRANT SELECT ON [dbo].[BankAccount]  TO [Soli-Daten ändern]
GRANT DELETE ON [dbo].[BankAccount]  TO [Soli-Daten ändern]
GRANT INSERT ON [dbo].[BankAccount]  TO [Soli-Daten ändern]
GRANT UPDATE ON [dbo].[BankAccount]  TO [Soli-Daten ändern]
GRANT SELECT ON [dbo].[BankAccount]  TO [Soli-Daten Lesen]
GO
DELETE FROM BankAccount WHERE PersID IN (select d.PersID from Persh as p RIGHT Join BankAccount  as d
ON p.Persnr = d.PersID WHERE p.Persnr is null)


IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_BankAccount_Personal]') AND type = 'F')
	ALTER TABLE [dbo].[BankAccount] DROP CONSTRAINT [FK_BankAccount_Personal]
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_BankAccount_Personal2]') AND type = 'F')
ALTER TABLE [dbo].[BankAccount]  WITH CHECK ADD  CONSTRAINT [FK_BankAccount_Personal2] FOREIGN KEY([PersID])
REFERENCES [dbo].[PersH] ([PersNr]) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[BankAccount] CHECK CONSTRAINT [FK_BankAccount_Personal2]
GO

--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_PersonalDetails_PersH]') AND type = 'F')
--ALTER TABLE [dbo].[PersonalDetails]  WITH CHECK ADD  CONSTRAINT [FK_PersonalDetails_PersH] FOREIGN KEY([PnR])
--REFERENCES [dbo].[PersH] ([PersNr]) ON DELETE CASCADE
--GO
--ALTER TABLE [dbo].[PersonalDetails] CHECK CONSTRAINT [FK_PersonalDetails_PersH]
--GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_production_genre]') AND type = 'F')
ALTER TABLE [dbo].[Stücke]  WITH CHECK ADD  CONSTRAINT [FK_production_genre] FOREIGN KEY([TypID])
REFERENCES [dbo].[Typ] ([TypID])
GO
ALTER TABLE [dbo].[Stücke] CHECK CONSTRAINT [FK_production_genre]

--2008-11-22
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_genre_branch]') AND type = 'F')
ALTER TABLE [dbo].[Typ]  WITH CHECK ADD  CONSTRAINT [FK_genre_branch] FOREIGN KEY([SparteID])
REFERENCES [dbo].[Sparte] ([SparteID])
GO
ALTER TABLE [dbo].[Typ] CHECK CONSTRAINT [FK_genre_branch]



DELETE FROM PlanSort WHERE Inhalt IN ('Firmen','PrimärerFirmenname','Angestellte','Kostuemdaten','DataPersDetail')

--2008 09 12 Zusätzliche Spalte in eitkonten für Export Nürnberg
--Hinterlegung von Tarifart und Tarifgruppe

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ExportTag' and o.id = OBJECT_ID(N'[dbo].Zeitkonten'))
BEGIN
	ALTER TABLE [Zeitkonten] ADD [ExportTag] [nvarchar](50) NULL
END

GO

--2008-09-16 Feldgrößen
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Ausgabe' AND o.id = OBJECT_ID(N'[dbo].RapportSpalte')  AND c.length = 1)
BEGIN
	ALTER TABLE RapportSpalte ALTER COLUMN Ausgabe INT NOT NULL
END
GO
--2008-09-16 Feldgrößen
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'LohnBez' AND o.id = OBJECT_ID(N'[dbo].RapportSpalte') AND c.prec < 20)
BEGIN
	ALTER TABLE RapportSpalte ALTER COLUMN LohnBez VARCHAR(20) NULL
END
-- 2008-09-24
-- Neue Spalte in RapportSpalten um anzugeben
-- ob leere Spalten nicht mit ausgegeben werden sollen
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'NoPrintIfEmpty' and o.id = OBJECT_ID(N'[dbo].RapportSpalte'))
BEGIN
	ALTER TABLE RapportSpalte ADD NoPrintIfEmpty BIT NOT NULL DEFAULT(0)
END
go
--2008-09-26
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PrintWorkCellCaption' and o.id = OBJECT_ID(N'[dbo].VorlageDP'))
BEGIN
	ALTER TABLE VorlageDP ADD PrintWorkCellCaption BIT NOT NULL DEFAULT(0)
END
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'VisibleAreas' and o.id = OBJECT_ID(N'[dbo].DienstplanArtenTabelle'))
BEGIN
	ALTER TABLE DienstplanArtenTabelle ADD  VisibleAreas INT NOT NULL DEFAULT(1)
	EXEC ('UPDATE  DienstplanArtenTabelle SET VisibleAreas = 3')
END
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'VisibleLayer' and o.id = OBJECT_ID(N'[dbo].DienstplanArtenTabelle'))
BEGIN
	ALTER TABLE  DienstplanArtenTabelle ADD VisibleLayer INT NOT NULL DEFAULT(1)
END

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'civilName' and o.id = OBJECT_ID(N'[dbo].Personaldetails'))
BEGIN
	ALTER TABLE Personaldetails ADD civilName NVARCHAR(60) NULL
	ALTER TABLE Personaldetails ADD familyStatusId INT NULL

	ALTER TABLE Personaldetails ALTER COLUMN GebOrt NVARCHAR(50) NULL
	ALTER TABLE Personaldetails ALTER COLUMN VersicherungsNr NVARCHAR(40) NULL
END

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'stageSupplyNo' and o.id = OBJECT_ID(N'[dbo].Personaldetails'))
BEGIN
	ALTER TABLE Personaldetails ADD stageSupplyNo VARCHAR(50) NULL
	ALTER TABLE Personaldetails ADD healthFund		VARCHAR(50) NULL

END

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsSecret' and o.id = OBJECT_ID(N'[dbo].PersKom'))
BEGIN
	ALTER TABLE PersKom ADD IsSecret  BIT NOT NULL DEFAULT(0)
END
--2008 10 02

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'SpecialLeaveDays' and o.id = OBJECT_ID(N'[dbo].VertragPerso'))
BEGIN
	ALTER TABLE VertragPerso ADD SpecialLeaveDays INT NOT NULL DEFAULT(0)
END
--2008 05 23 Refresh aller Views, immer unten stehen lassen...
GO 

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ContractConfirmations]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ContractConfirmations](
		[ContractConfirmationId] [int] IDENTITY(1,1) NOT NULL,
		[ContractId] [int] NOT NULL,
		[Subject] [nchar](100) COLLATE Latin1_General_CI_AS NOT NULL,
		[Summary] [text] COLLATE Latin1_General_CI_AS NULL,
		[PersAdresseId] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
	 CONSTRAINT [PK_ContractConfirmations] PRIMARY KEY CLUSTERED 
	(
		[ContractConfirmationId] ASC
	) ON [PRIMARY]
	) ON [PRIMARY] 
END

GRANT SELECT ON [dbo].ContractConfirmations  TO [Honorar-Daten ändern]
GRANT DELETE ON [dbo].ContractConfirmations  TO [Honorar-Daten ändern]
GRANT INSERT ON [dbo].ContractConfirmations  TO [Honorar-Daten ändern]
GRANT UPDATE ON [dbo].ContractConfirmations  TO [Honorar-Daten ändern]
GRANT SELECT ON [dbo].ContractConfirmations  TO [Honorar-Daten lesen]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractConfirmations_Vertrag]') AND type = 'F')
ALTER TABLE [dbo].[ContractConfirmations]  WITH NOCHECK ADD  CONSTRAINT [FK_ContractConfirmations_Vertrag] FOREIGN KEY([ContractId])
REFERENCES [dbo].[Vertrag] ([VertragsNr])
GO
ALTER TABLE [dbo].[ContractConfirmations] CHECK CONSTRAINT [FK_ContractConfirmations_Vertrag]

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractConfirmations_Vertrag]') AND type = 'F')
ALTER TABLE [dbo].[ContractConfirmations]  WITH NOCHECK ADD  CONSTRAINT [FK_ContractConfirmations_Vertrag] FOREIGN KEY([ContractId])
REFERENCES [dbo].[Vertrag] ([VertragsNr])
GO
ALTER TABLE [dbo].[ContractConfirmations] CHECK CONSTRAINT [FK_ContractConfirmations_Vertrag]

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ContractDateConfirmations]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ContractDateConfirmations](
		[ContractDateConfirmationId] [int] IDENTITY(1,1) NOT NULL,
		[ContractConfirmationId] [int] NOT NULL,
		[ContractDateId] [int] NOT NULL,
		[IsCancellation] [bit] NOT NULL CONSTRAINT [DF_ContractConfirmations_ContractDates_Cancellation]  DEFAULT (0),
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
	 CONSTRAINT [PK_ContractDateConfirmations] PRIMARY KEY CLUSTERED 
	(
		[ContractDateConfirmationId] ASC
	) ON [PRIMARY]
	) ON [PRIMARY]
END
go
GRANT SELECT ON [dbo].ContractDateConfirmations  TO [Honorar-Daten ändern]
GRANT DELETE ON [dbo].ContractDateConfirmations  TO [Honorar-Daten ändern]
GRANT INSERT ON [dbo].ContractDateConfirmations  TO [Honorar-Daten ändern]
GRANT UPDATE ON [dbo].ContractDateConfirmations  TO [Honorar-Daten ändern]
GRANT SELECT ON [dbo].ContractDateConfirmations  TO [Honorar-Daten lesen]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractDateConfirmations_ContractConfirmations]') AND type = 'F')
ALTER TABLE [dbo].[ContractDateConfirmations]  WITH NOCHECK ADD  CONSTRAINT [FK_ContractDateConfirmations_ContractConfirmations] FOREIGN KEY([ContractConfirmationId])
REFERENCES [dbo].[ContractConfirmations] ([ContractConfirmationId])
GO
ALTER TABLE [dbo].[ContractDateConfirmations] CHECK CONSTRAINT [FK_ContractDateConfirmations_ContractConfirmations]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractDateConfirmations_ContractDates]') AND type = 'F')
ALTER TABLE [dbo].[ContractDateConfirmations]  WITH NOCHECK ADD  CONSTRAINT [FK_ContractDateConfirmations_ContractDates] FOREIGN KEY([ContractDateId])
REFERENCES [dbo].[ContractDates] ([ContractDateId])
GO
ALTER TABLE [dbo].[ContractDateConfirmations] CHECK CONSTRAINT [FK_ContractDateConfirmations_ContractDates]



IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Str' AND o.id = OBJECT_ID(N'[dbo].PersAdresse') AND c.prec < 110)
BEGIN
	ALTER TABLE PersAdresse ALTER COLUMN [Str] VARCHAR(110) NULL
	ALTER TABLE PersAdresse ALTER COLUMN [Ort] VARCHAR(80) NULL
END




--2008-10-14
--farbspalten für dienstplaneintraege
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BackColor1' and o.id = OBJECT_ID(N'[dbo].Dienstplan'))
BEGIN
	ALTER TABLE Dienstplan ADD BackColor1 INT NOT NULL DEFAULT(0), 
	BackColor2 INT NOT NULL DEFAULT(0), BackColor3 INT NOT NULL DEFAULT(0)	
END


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CastStatusID' and o.id = OBJECT_ID(N'[dbo].BesetzungTabelle'))
BEGIN
	ALTER TABLE BesetzungTabelle ADD CastStatusID int NOT NULL DEFAULT(0)
END

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CastStatusID' AND o.id = OBJECT_ID(N'[dbo].BesetzungTabelle') AND c.xtype <> 56)
BEGIN
--ggf anderer CONSTRAINT Name
	declare @defname varchar(100)
	SELECT @defname = name 	FROM sysobjects so JOIN sysconstraints sc ON so.id = sc.constid 
			WHERE object_name(so.parent_obj) = 'BesetzungTabelle'
			AND so.xtype = 'D'
			AND sc.colid = 
				(SELECT colid FROM syscolumns 
				WHERE id = OBJECT_ID(N'[dbo].BesetzungTabelle') AND 
				name = 'CastStatusID')

		exec ('alter table BesetzungTabelle drop constraint '+@defname)
	
	ALTER TABLE BesetzungTabelle ALTER COLUMN CastStatusID int NOT NULL 
	ALTER TABLE [dbo].[BesetzungTabelle] ADD CONSTRAINT DF_BesetzungTabelle_CastStatusID DEFAULT (0) FOR [CastStatusID]
	Print 'WertText geändert'
END


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CheckHoliday' and o.id = OBJECT_ID(N'[dbo].Dienstplan'))
BEGIN
	ALTER TABLE Dienstplan ADD CheckHoliday BIT NOT NULL DEFAULT(1)
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CalenderID' and o.id = OBJECT_ID(N'[dbo].[Kalender]'))
BEGIN
	ALTER TABLE dbo.Kalender ADD 	CalenderID int IDENTITY(1,1) NOT NULL
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'RollePresse' and o.id = OBJECT_ID(N'[dbo].[BesetzungStd]'))
BEGIN
	ALTER TABLE dbo.BesetzungStd ADD RollePresse VARCHAR(100) NULL
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ExemptionStatus1' and o.id = OBJECT_ID(N'[dbo].[Dienstplan]'))
BEGIN
	ALTER TABLE dbo.Dienstplan ADD ExemptionStatus1 INT NOT NULL DEFAULT(0), ExemptionStatus2 INT NOT NULL DEFAULT(0)
END
go
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TrennRegie' AND o.id = OBJECT_ID(N'[dbo].[Plan]') AND c.prec < 3)
BEGIN
	ALTER TABLE  [Plan] ALTER COLUMN  TrennRegie VARCHAR (3)
	ALTER TABLE  [Plan] ALTER COLUMN  TrennSoli VARCHAR (3)
END

go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PersonnelNo' and o.id = OBJECT_ID(N'[dbo].[PersH]'))
BEGIN
	ALTER TABLE dbo.PersH ADD PersonnelNo VARCHAR(10) NULL
	exec ('UPDATE PersH SET PersonnelNo = PersNrVorh FROM PersH INNER JOIN PersonalDetails ON Persh.PersNr=PersonalDetails.pnr')
END

go

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'OptionsFlag' and o.id = OBJECT_ID(N'[dbo].UserGruppe'))
BEGIN
	ALTER TABLE UserGruppe ADD OptionsFlag INT NOT NULL DEFAULT(0)
	--ALTER TABLE DienstplanArtenTabelle ADD ModulGruppeID INT NOT NULL DEFAULT(0)
	Print 'WertText geändert'
END	

go
ALTER VIEW [dbo].[AbPersD]
AS
SELECT Ph.PersNr as pnr, PersAdresse.str, PersAdresse.ort,PersAdresse.plz,PersAdresse.land,PersAdresse.co,
(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =5 AND PersKom.PersNR=Ph.PersNr) AS Homepage,
(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =4 AND PersKom.PersNR=Ph.PersNr) AS eMail,
(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =3 AND PersKom.PersNR=Ph.PersNr) AS Fax,
(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =2 AND PersKom.PersNR=Ph.PersNr) AS Handy,
(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =1 AND PersKom.PersNR=Ph.PersNr) AS HausRuf,
(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =0 AND PersKom.PersNR=Ph.PersNr) AS Tel, 
UG.schreiben,'' AS InternetLink, '' AS PersNrVorh, GebDatum, '' AS KstAbt, RepetiSoliProSort,  [Memo], [National], GebOrt, MemoExtern, Adressplan,0 as Plan_Person,'' AS BildVerweis,MemoExtern_en, 0 AS InTrs,InWeb,
VersicherungsNr, SteuerNr, Finanzamt, UstID, PassNr, PassAusAmt, PassAusOrt, PassAusDatum, PassAblDatum
 FROM     PersH  as Ph LEFT  JOIN (SELECT GruppeID, schreiben  FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid WHERE  BerechtigungsbereichID=0 AND Username = CURRENT_USER ) UG ON (Ph.Besitzer = UG.GruppeID )
LEFT JOIN PersAdresse ON ph.PersNr = PersAdresse.PersNr LEFT JOIN PersonalDetails on ph.persnr=PersonalDetails.pnr WHERE ((ph.Gesperrt =0) or not  UG.GruppeID IS NULL) or CURRENT_USER = 'dbo'
GO


ALTER VIEW [dbo].[AbPersKomAlle]
AS
SELECT Ph.PersNr, 
(SELECT top 1 Wert FROM PersKom WHERE IsSecret=0 AND Sort = 0 and PersKTypID =5 and PersKom.PersNR=Ph.PersNr) AS Homepage,
(SELECT top 1 Wert FROM PersKom WHERE IsSecret=0 AND Sort = 0 and PersKTypID =4 and  PersKom.PersNR=Ph.PersNr) AS eMail,
(SELECT top 1 Wert FROM PersKom WHERE IsSecret=0 AND Sort = 0 and PersKTypID =3 and  PersKom.PersNR=Ph.PersNr) AS Fax,
(SELECT top 1 Wert FROM PersKom WHERE IsSecret=0 AND Sort = 0 and PersKTypID =2 and  PersKom.PersNR=Ph.PersNr) AS Handy,
(SELECT top 1 Wert FROM PersKom WHERE IsSecret=0 AND Sort = 0 and PersKTypID =1 and  PersKom.PersNR=Ph.PersNr) AS HausRuf,
(SELECT top 1 Wert FROM PersKom WHERE IsSecret=0 AND Sort = 0 and PersKTypID =0 and  PersKom.PersNR=Ph.PersNr) AS Tel, UG.schreiben
  FROM     PersH  as Ph LEFT  JOIN 
(SELECT GruppeID, schreiben  FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid WHERE  BerechtigungsbereichID=0 AND Username = CURRENT_USER ) UG 
ON (Ph.Besitzer = UG.GruppeID )
WHERE ((ph.Gesperrt =0) or not  UG.GruppeID IS NULL) or CURRENT_USER = 'dbo'

go

ALTER VIEW [dbo].[AbPersKontakt]
AS
SELECT Ph.PersNr as pnr, PersAdresse.str, PersAdresse.ort,PersAdresse.plz,PersAdresse.land,PersAdresse.co,
(SELECT top 1 Wert FROM PersKom WHERE  IsSecret=0 AND  Sort = 0 and PersKTypID =5 and PersKom.PersNR=Ph.PersNr) AS Homepage,
(SELECT top 1 Wert FROM PersKom WHERE  IsSecret=0 AND  Sort = 0 and PersKTypID =4 and  PersKom.PersNR=Ph.PersNr) AS eMail,
(SELECT top 1 Wert FROM PersKom WHERE  IsSecret=0 AND  Sort = 0 and PersKTypID =3 and  PersKom.PersNR=Ph.PersNr) AS Fax,
(SELECT top 1 Wert FROM PersKom WHERE  IsSecret=0 AND  Sort = 0 and PersKTypID =2 and  PersKom.PersNR=Ph.PersNr) AS Handy,
(SELECT top 1 Wert FROM PersKom WHERE  IsSecret=0 AND  Sort = 0 and PersKTypID =1 and  PersKom.PersNR=Ph.PersNr) AS HausRuf,
(SELECT top 1 Wert FROM PersKom WHERE  IsSecret=0 AND  Sort = 0 and PersKTypID =0 and  PersKom.PersNR=Ph.PersNr) AS Tel, 
UG.schreiben,'' AS InternetLink, '' AS PersNrVorh,  '' AS KstAbt, RepetiSoliProSort,  [Memo], MemoExtern, Adressplan, 0 as Plan_Person,'' AS BildVerweis,MemoExtern_en,0 AS InTrs,InWeb
 FROM     PersH  as Ph LEFT  JOIN (SELECT GruppeID, schreiben  FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid WHERE  BerechtigungsbereichID=0 AND  Username = CURRENT_USER ) UG ON (Ph.Besitzer = UG.GruppeID )
LEFT JOIN PersAdresse ON ph.PersNr = PersAdresse.PersNr LEFT JOIN PersonalDetails on ph.persnr=PersonalDetails.pnr WHERE ((ph.Gesperrt =0) or not  UG.GruppeID IS NULL) or CURRENT_USER = 'dbo'


GO




--ALTER VIEW dbo.PersonalOrchesterDetails
--AS 
--SELECT Ph.PersNr ,Nachname, Vorname, geschlecht, PersAdresse.str, PersAdresse.ort,PersAdresse.plz,PersAdresse.land,PersAdresse.co,
--(SELECT top 1 Wert FROM PersKom WHERE IsSecret=0 AND  Sort = 0 and PersKTypID =5 and PersKom.PersNR=Ph.PersNr) AS Homepage,
--(SELECT top 1 Wert FROM PersKom WHERE IsSecret=0 AND  Sort = 0 and PersKTypID =4 and  PersKom.PersNR=Ph.PersNr) AS eMail,
--(SELECT top 1 Wert FROM PersKom WHERE IsSecret=0 AND  Sort = 0 and PersKTypID =3 and  PersKom.PersNR=Ph.PersNr) AS Fax,
--(SELECT top 1 Wert FROM PersKom WHERE IsSecret=0 AND  Sort = 0 and PersKTypID =2 and  PersKom.PersNR=Ph.PersNr) AS Handy,
--(SELECT top 1 Wert FROM PersKom WHERE IsSecret=0 AND  Sort = 0 and PersKTypID =1 and  PersKom.PersNR=Ph.PersNr) AS HausRuf,
--(SELECT top 1 Wert FROM PersKom WHERE IsSecret=0 AND  Sort = 0 and PersKTypID =0 and  PersKom.PersNR=Ph.PersNr) AS Tel, 
--(SELECT top 1 BankCode FROM Bankaccount WHERE Bankaccount.PersID=Ph.PersNr) AS BLZ, 
--(SELECT top 1 BankName FROM Bankaccount WHERE Bankaccount.PersID=Ph.PersNr) AS Bank, 
--(SELECT top 1 AccountNumber FROM Bankaccount WHERE Bankaccount.PersID=Ph.PersNr) AS KtoNr, 
--(SELECT top 1 AccountHolder FROM Bankaccount WHERE Bankaccount.PersID=Ph.PersNr) AS KtoInhaber, 
--UG.schreiben,  InternetLink, PersonnelNo as altPersNr, GebDatum, KstAbt, RepetiSoliProSort, [Memo], [National], GebOrt, MemoExtern, Adressplan, 0 as  Plan_Person,BildVerweis,MemoExtern_en,InTrs,InWeb,
--VersicherungsNr, SteuerNr, Finanzamt, UstID, PassNr, PassAusAmt, PassAusOrt, PassAusDatum, PassAblDatum
-- FROM     PersH  as Ph LEFT  JOIN (SELECT GruppeID, schreiben  FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid WHERE  BerechtigungsbereichID=0 AND  Username = CURRENT_USER ) UG ON (Ph.Besitzer = UG.GruppeID )
--LEFT JOIN PersAdresse ON ph.PersNr = PersAdresse.PersNr LEFT JOIN PersonalDetails on ph.persnr=PersonalDetails.pnr WHERE ((ph.Gesperrt =0) or not  UG.GruppeID IS NULL) or CURRENT_USER = 'dbo' and Besitzer=100
--GO

ALTER VIEW [dbo].[AbPersP]
AS
SELECT PNr, RepetiSoliProSort,'' AS KstAbt, '' AS InternetLink, 0 AS InTrs, InWeb, Adressplan,'' AS BildVerweis,MemoExtern_en,MemoExtern, '' AS PersNrVorh, UM, LM, LC, UC, civilName, CivilFirstName
FROM PersonalDetails
go
ALTER VIEW [dbo].[AbAgentur]
AS 
SELECT PersH.Nachname AS Name, PersH.PersNr AS Nr, PersH.Suchname AS NameKurz, pa.Str AS  strasse, pa.Plz, pa.Ort, pa.Land, pa.Co, PMail.Wert AS eMail, PFax.Wert AS Fax, PTel.Wert AS Tel, PersonalDetails.Memo,  PersKat.AdressArt, PersKat.PersKat AS AgFilterBez
FROM (PersKat INNER JOIN PersH ON PersKat.PersKatNr = PersH.PersKatNr) LEFT JOIN (((((SELECT  PersNr, Co, Str, Plz, Ort, Land FROM PersAdresse WHERE Sort=0) AS pa RIGHT JOIN PersonalDetails ON pa.PersNr = PersonalDetails.PNr) LEFT JOIN (SELECT top 1 PersNr, Wert FROM PersKom WHERE  Sort = 0 and PersKTypID =0) AS PTel ON PersonalDetails.PNr = PTel.PersNr) LEFT JOIN (SELECT  top 1 PersNr, Wert FROM 
PersKom WHERE  Sort = 0 and PersKTypID =3) AS PFax ON PersonalDetails.PNr = PFax.PersNr) LEFT JOIN (SELECT  top 1 PersNr, Wert FROM PersKom WHERE  Sort = 0 and PersKTypID =4) AS PMail ON PersonalDetails.PNr = PMail.PersNr) ON PersH.PersNr = PersonalDetails.PNr
WHERE (((PersKat.AdressArt)>10))
go

IF  NOT EXISTS (SELECT * FROM  Land)
BEGIN
	INSERT INTO Land(LandLang,Land) VALUES ('Andorra','AD')
	INSERT INTO Land(LandLang,Land) VALUES ('Australien','AUS')
	INSERT INTO Land(LandLang,Land) VALUES ('Belgien','B')
	INSERT INTO Land(LandLang,Land) VALUES ('Bulgarien','BG') 
	INSERT INTO Land(LandLang,Land) VALUES ('Dänemark','DK')
	INSERT INTO Land(LandLang,Land) VALUES ('Deutschland','D')
	INSERT INTO Land(LandLang,Land) VALUES ('Estland','EE')
	INSERT INTO Land(LandLang,Land) VALUES ('Färöer','FR')
	INSERT INTO Land(LandLang,Land) VALUES ('Finnland','FIN') 
	INSERT INTO Land(LandLang,Land) VALUES ('Frankreich','F')
	INSERT INTO Land(LandLang,Land) VALUES ('Griechenland','GR')
	INSERT INTO Land(LandLang,Land) VALUES ('Italien','I')
	INSERT INTO Land(LandLang,Land) VALUES ('Japan','J')
	INSERT INTO Land(LandLang,Land) VALUES ('Serbien','SRB')
	INSERT INTO Land(LandLang,Land) VALUES ('Kanada','CDN')
	INSERT INTO Land(LandLang,Land) VALUES ('Kroatien','HR')
	INSERT INTO Land(LandLang,Land) VALUES ('Lettland','LV')
	INSERT INTO Land(LandLang,Land) VALUES ('Liechtenstein','FL')
	INSERT INTO Land(LandLang,Land) VALUES ('Litauen','LT')
	INSERT INTO Land(LandLang,Land) VALUES ('Luxemburg','L')
	INSERT INTO Land(LandLang,Land) VALUES ('Mazedonien','MK')
	INSERT INTO Land(LandLang,Land) VALUES ('Monaco','MC')
	INSERT INTO Land(LandLang,Land) VALUES ('Neuseeland','NZ')
	INSERT INTO Land(LandLang,Land) VALUES ('Niederlande','NL')
	INSERT INTO Land(LandLang,Land) VALUES ('Norwegen','N')
	INSERT INTO Land(LandLang,Land) VALUES ('Österreich','A')
	INSERT INTO Land(LandLang,Land) VALUES ('Polen','PL')
	INSERT INTO Land(LandLang,Land) VALUES ('Portugal','P')
	INSERT INTO Land(LandLang,Land) VALUES ('Rumänien','RO')
	INSERT INTO Land(LandLang,Land) VALUES ('Russland','RUS')
	INSERT INTO Land(LandLang,Land) VALUES ('Schweden','S')
	INSERT INTO Land(LandLang,Land) VALUES ('Schweiz','CH')
	INSERT INTO Land(LandLang,Land) VALUES ('Slowakei','SK')
	INSERT INTO Land(LandLang,Land) VALUES ('Slowenien','SLO')
	INSERT INTO Land(LandLang,Land) VALUES ('Spanien','E')
	INSERT INTO Land(LandLang,Land) VALUES ('Türkei','TR')
	INSERT INTO Land(LandLang,Land) VALUES ('Tschechische Republik','CZ')
	INSERT INTO Land(LandLang,Land) VALUES ('Tunesien','TN')
	INSERT INTO Land(LandLang,Land) VALUES ('Ungarn','H')
	INSERT INTO Land(LandLang,Land) VALUES ('Vereinigtes Königreich','UK')
	INSERT INTO Land(LandLang,Land) VALUES ('Vereinigte Arabische Emirate','AE')
	INSERT INTO Land(LandLang,Land) VALUES ('Amerika','USA')
END
go
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'FtBez' AND o.id = OBJECT_ID(N'[dbo].Feiertage') AND c.prec < 20)
BEGIN
	ALTER TABLE  Feiertage ALTER COLUMN  FtBez VARCHAR (20)
END




go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CastStatus]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CastStatus](
		[CastStatusId] [int] IDENTITY(1,1) NOT NULL,
		[CastStatusTyp] [int] NOT NULL,
		[NameShort] [varchar](2) NULL,
		[Name] [varchar](25) NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
	 CONSTRAINT [PK_CastStatus] PRIMARY KEY CLUSTERED 
	(	[CastStatusId] ASC) ON [PRIMARY]
	) ON [PRIMARY] 


SET IDENTITY_INSERT CastStatus  ON
INSERT INTO CastStatus ([CastStatusId],[CastStatusTyp],[Name],[NameShort],[LC],[UC],[LM],[UM]) VALUES (0,4,'--','--','19000101',0,'19000101',0)
INSERT INTO CastStatus ([CastStatusId],[CastStatusTyp],[Name],[NameShort],[LC],[UC],[LM],[UM]) VALUES (7,10,'Zusage','OK','19000101',0,'19000101',0)
INSERT INTO CastStatus ([CastStatusId],[CastStatusTyp],[Name],[NameShort],[LC],[UC],[LM],[UM]) VALUES (8,6,'Termin moeglich','TM','19000101',0,'19000101',0)
INSERT INTO CastStatus ([CastStatusId],[CastStatusTyp],[Name],[NameShort],[LC],[UC],[LM],[UM]) VALUES (9,6,'Anfrage','AN','19000101',0,'19000101',0)
--INSERT INTO CastStatus ([CastStatusId],[CastStatusTyp],[Name],[NameShort],[LC],[UC],[LM],[UM]) VALUES (10,-1,'Absage','NO','19000101',0,'19000101',0)
SET IDENTITY_INSERT CastStatus  OFF
END
GRANT SELECT ON [dbo].CastStatus  TO Public
GRANT DELETE ON [dbo].CastStatus  TO [Stammdaten ändern]
GRANT INSERT ON [dbo].CastStatus  TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].CastStatus  TO [Stammdaten ändern]

go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ContractDateStatus]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ContractDateStatus](
		[CDStatusId] [int] IDENTITY(1,1) NOT NULL,
		[CDStatusTyp] [int] NOT NULL,
		[NameShort] [varchar](2) NULL,
		[Name] [varchar](25) NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
	 CONSTRAINT [PK_ContractDateStatus] PRIMARY KEY CLUSTERED 
	(	[CDStatusId] ASC) ON [PRIMARY]
	) ON [PRIMARY] 


SET IDENTITY_INSERT ContractDateStatus  ON
INSERT INTO ContractDateStatus ([CDStatusId],[CDStatusTyp],[Name],[NameShort],[LC],[UC],[LM],[UM]) VALUES (1,15,'Vert. unterschrieben','VU','19000101',0,'19000101',0)
INSERT INTO ContractDateStatus ([CDStatusId],[CDStatusTyp],[Name],[NameShort],[LC],[UC],[LM],[UM]) VALUES (3,10,'Vert. verschickt','VV','19000101',0,'19000101',0)
INSERT INTO ContractDateStatus ([CDStatusId],[CDStatusTyp],[Name],[NameShort],[LC],[UC],[LM],[UM]) VALUES (4,15,'Daten Unterschrieben','DU','19000101',0,'19000101',0)
INSERT INTO ContractDateStatus ([CDStatusId],[CDStatusTyp],[Name],[NameShort],[LC],[UC],[LM],[UM]) VALUES (5,10,'Daten bestaetigt','DB','19000101',0,'19000101',0)
INSERT INTO ContractDateStatus ([CDStatusId],[CDStatusTyp],[Name],[NameShort],[LC],[UC],[LM],[UM]) VALUES (6,10,'Vertragsanforderung','VA','19000101',0,'19000101',0)
INSERT INTO ContractDateStatus ([CDStatusId],[CDStatusTyp],[Name],[NameShort],[LC],[UC],[LM],[UM]) VALUES (0,0,'neu','DN','19000101',0,'19000101',0)
SET IDENTITY_INSERT ContractDateStatus  OFF
END
go

GRANT SELECT ON [dbo].ContractDateStatus  TO Public
GRANT DELETE ON [dbo].ContractDateStatus  TO [Stammdaten ändern]
GRANT INSERT ON [dbo].ContractDateStatus  TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].ContractDateStatus  TO [Stammdaten ändern]


go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CDStatusId' and o.id = OBJECT_ID(N'[dbo].[ContractDates]'))
BEGIN
	ALTER TABLE dbo.ContractDates ADD CDStatusId INT NOT NULL DEFAULT(0)
END
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AgencyId' and o.id = OBJECT_ID(N'[dbo].[BesetzungTabelle]'))
BEGIN
	ALTER TABLE dbo.BesetzungTabelle ADD AgencyId INT NULL 
END
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsCover' and o.id = OBJECT_ID(N'[dbo].[BesetzungTabelle]'))
BEGIN
	ALTER TABLE dbo.BesetzungTabelle ADD IsCover BIT NOT NULL  DEFAULT(0)
END
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsCanceled' and o.id = OBJECT_ID(N'[dbo].[BesetzungTabelle]'))
BEGIN
	ALTER TABLE dbo.BesetzungTabelle ADD IsCanceled BIT NOT NULL  DEFAULT(0)
END

Go
ALTER VIEW dbo.Besetzung
AS
SELECT	a.*
FROM    dbo.BesetzungTabelle AS a 
WHERE	IsCanceled=0 AND IsCover=0 
	AND (a.Gesperrt = 0 
	OR (SELECT PERMISSIONS(OBJECT_ID('Besetzung'))&2) = 2
	--OR (SELECT IS_MEMBER('Spielplan alles lesen'))=1
	)
go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[Cast]'))
BEGIN
	DROP VIEW [dbo].[Cast]
END
go
CREATE VIEW dbo.[Cast]
AS
SELECT	a.*
FROM    dbo.BesetzungTabelle AS a 
WHERE	(a.Gesperrt IS NULL OR (SELECT   PERMISSIONS(OBJECT_ID('Besetzung')) & 2) = 2
	OR (SELECT IS_MEMBER('Spielplan alles lesen'))=1)
go


GRANT SELECT ON [dbo].[Cast] TO Public
GRANT UPDATE ON [dbo].[Cast] TO  [Spielplan ändern]
GRANT DELETE ON [dbo].[Cast] TO  [Spielplan ändern]
GRANT INSERT ON [dbo].[Cast] TO  [Spielplan ändern]


GO

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

GRANT SELECT ON [dbo].BesetzungTabelle TO [Spielplan alles lesen]
GRANT SELECT ON [dbo].BesetzungTabelle TO [Spielplan ändern]
go
ALTER VIEW dbo.AbBesetzungStd
AS
Select BesetzungStd.ID, BesetzungStd.Besitzer,  BesetzungStd.Rolle,BesetzungStd.RolleKurz, BesetzungStd.Pos, BesetzungStd.Leporello, BesetzungStd.PresseSort, BesetzungStd.nameDrucken, BesetzungStd.StdVs, BesetzungStd.StdPro, BesetzungStd.RollenLtgID, BesetzungStd.RolleMann, BesetzungStd.RolleFrau, BesetzungStd.GruppeID, BesetzungStd.DruckSteuerung, BesetzungStd.DruckStd, BesetzungStd.Cover, StückeTeil.sort,
Case WHEN StückeTeil.snr IS NULL THEN BesetzungStd.snr ELSE StückeTeil.snr END as SNR , BesetzungStd.snr as osnr
FROM BesetzungStd LEFT JOIN StückeTeil ON BesetzungStd.SNr = StückeTeil.SnrTeil WHERE ISNULL(BesetzungStd.Besitzer,1)<=1
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'SickTimeFromQuota' and o.id = OBJECT_ID(N'[dbo].[PersoParameter]'))
BEGIN
	ALTER TABLE dbo.PersoParameter ADD 	SickTimeFromQuota BIT DEFAULT(0)
END 
go

GRANT SELECT ON [dbo].[Besetzung_Update]   TO Public
GRANT DELETE ON [dbo].[Besetzung_Update]   TO Public
GRANT INSERT ON [dbo].[Besetzung_Update]   TO Public
GRANT UPDATE ON [dbo].[Besetzung_Update]   TO Public

go



--Ab 01.01.2009 entfernen
ALTER TABLE dbo.ContractConfirmations  ALTER COLUMN [Subject] VARCHAR(100) NOT NULL
UPDATE ContractConfirmations SET  [Subject] = RTRIM([Subject])
--
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DocumentTypeID' and o.id = OBJECT_ID(N'[dbo].[ContractConfirmations]'))
BEGIN
	ALTER TABLE dbo.ContractConfirmations ADD DocumentTypeID INT NOT NULL DEFAULT(0)
END 
go
--2008-11-22
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ContractDates]')  AND name = 'IX_CastID')
CREATE NONCLUSTERED INDEX IX_CastID ON dbo.ContractDates (CastId)  ON [PRIMARY]
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsCanceled' and o.id = OBJECT_ID(N'[dbo].[Vertrag]'))
BEGIN
	ALTER TABLE dbo.Vertrag ADD IsCanceled BIT NOT NULL DEFAULT(0)
END 
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'[dbo].[ContractDateStatus]'))
BEGIN
	ALTER TABLE dbo.ContractDateStatus ADD Sort INT NOT NULL DEFAULT(0)
END 
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'[dbo].[CastStatus]'))
BEGIN
	ALTER TABLE dbo.CastStatus ADD Sort INT NOT NULL DEFAULT(0)
END 
go

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ExtraFee' and o.id = OBJECT_ID(N'[dbo].VertragRolle'))
BEGIN
	ALTER TABLE VertragRolle ADD ExtraFee MONEY NOT NULL DEFAULT(0)
END
go

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Creditable' and o.id = OBJECT_ID(N'[dbo].BesetzungTabelle'))
BEGIN
	ALTER TABLE BesetzungTabelle ADD Creditable REAL NULL
END	
go

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AllocateExtraFee'))
BEGIN
	DROP PROCEDURE dbo.AllocateExtraFee
END
go
CREATE PROCEDURE [dbo].[AllocateExtraFee]
@Start datetime,
@End datetime
AS
DECLARE @PersId INT, @Vr INT, @Limit INT, @ContractFee REAL
SET NOCOUNT ON;
-- Ensembleverträge laden --
DECLARE contracts CURSOR
FOR SELECT  v.PersNr, vr.vrid, ISNULL(VorstAnz,0) - ISNULL(VorstAnzVortrag,0), vr.ExtraFee
		FROM		   VertragRolle			AS vr
			INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
			INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
		WHERE 
			 vv.Vart = 255 -- Ensemble 
			AND (@Start >= vr.vrvon OR vr.vrvon IS NULL) AND (@Start >= v.vvon OR v.vvon IS NULL)
			AND (@End <= vr.vrbis OR vr.vrbis IS NULL) AND (@End  <= v.vbis OR v.vbis IS NULL)
			AND v.IsCanceled=0
OPEN contracts
-- Durchlaufen der Ensembleverträge --
FETCH NEXT FROM contracts INTO  @PersId, @Vr, @Limit, @ContractFee
WHILE @@FETCH_STATUS = 0
BEGIN
	--Print 'PersID: ' + CAST(@PersId AS VARCHAR(10)) + ' Fee: ' + CAST(@ContractFee AS VARCHAR(10))
	DECLARE @ActivetyId INT, @CastId INT, @VbhId INT, @tabFee REAL, @castCount INT, @LastActivetyId INT, @Creditable INT
	SET @castCount = 0
	SET @LastActivetyId = 0
	-- Besetzunden laden ---
	DECLARE castfee CURSOR FOR SELECT b.Auffnr, b.Id,  vbh.Id, Betrag, ISNULL(Creditable,1)
			FROM	BesetzungTabelle		AS b	
			INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr
			INNER JOIN Aufftypen			AS at	ON a.art = at.AufftNr
			LEFT JOIN VertragsBesetzungsHonorar AS vbh ON b.ID = vbh.BesID
		WHERE 
			a.Status BETWEEN 0 AND 99
			AND at.KatNr = 0 -- Nur Vst
			AND a.Datum BETWEEN  @Start AND @End 
			--AND vbh.KostenArt = -1
			AND b.PersNr = @PersId
			--AND b.IsCanceled=0
		ORDER BY Datum, UhrBeg, a.Auffnr
	OPEN castfee
	-- Durchlaufen der Besetzungen --
	FETCH NEXT FROM castfee INTO  @ActivetyId, @CastId, @VbhId, @tabFee, @Creditable	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE @newFee INT
		-- Prüfen auf mehrere Rollen in einer Vst. --
		IF @LastActivetyId <> @ActivetyId  AND @Creditable > 0
			BEGIN
				-- Wenn neu Vst, Id merken und Zähler erhöhen
				SET @LastActivetyId = @ActivetyId
				SET @castCount = @castCount + 1	
				-- Limit überschitten?
				IF @Limit < @castCount AND @Limit > 0
					SET @newFee = @ContractFee
				ELSE
					SET @newFee = 0
			END
		ELSE
			-- Sonst Gage auf 0
			SET @newFee = 0	
		
		--Print 'auff: ' + CAST(@ActivetyId AS VARCHAR(10)) + ' CastID: ' + CAST(@CastId AS VARCHAR(10)) + ' Fee: ' + CAST(@newFee AS VARCHAR(10))
		IF @VbhId IS NULL AND @newFee <> 0
			-- Noch kein DS vorhanden und Gage > 0 - anlegen
			INSERT INTO VertragsBesetzungsHonorar (BesID, VRID, Betrag, KostenArt) VALUES (@CastId, @Vr, @newFee, -1)
		ELSE IF @newFee <> @tabFee
			-- ...wenn abweichende Gage - updaten
			UPDATE VertragsBesetzungsHonorar SET Betrag = @newFee, KostenArt = -1 WHERE ID = @VbhId 

		FETCH NEXT FROM castfee INTO  @ActivetyId, @CastId, @VbhId, @tabFee, @Creditable
	END
	CLOSE castfee
	DEALLOCATE castfee
	FETCH NEXT FROM contracts INTO  @PersId, @Vr, @Limit, @ContractFee
END
CLOSE contracts
DEALLOCATE contracts
RETURN

go
GRANT EXECUTE ON AllocateExtraFee TO Public
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ProductionTimeFlow]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ProductionTimeFlow](
		ProductionTimeFlowId INT IDENTITY(1,1) NOT NULL,
		ProductionId int NOT NULL,
		Name varchar(80) NULL,
		IsPause BIT NOT NULL DEFAULT(0),
		Position int NOT NULL,
		Duration int NOT NULL,
		[LM] [datetime]  NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime]  NOT NULL,
		[UC] [int] NOT NULL,
	CONSTRAINT [PK_ProductionTimeFlow] PRIMARY KEY CLUSTERED (
		ProductionTimeFlowId ASC
		)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ProductionTimeFlow]')  AND name = 'IX_ProductionId')
BEGIN
	CREATE NONCLUSTERED INDEX [IX_ProductionId] ON [dbo].[ProductionTimeFlow] (
		[ProductionId] ASC
	) ON [PRIMARY]
END	
	
GO
GRANT SELECT ON [dbo].ProductionTimeFlow TO Public
GRANT DELETE ON [dbo].ProductionTimeFlow TO [Stammdaten ändern]
GRANT INSERT ON [dbo].ProductionTimeFlow TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].ProductionTimeFlow TO [Stammdaten ändern]

go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ProductionTimeFlow_Production]') AND type = 'F')
ALTER TABLE [dbo].[ProductionTimeFlow]  WITH CHECK ADD  CONSTRAINT [FK_ProductionTimeFlow_Production] FOREIGN KEY([ProductionId])
REFERENCES [dbo].[Stücke] ([Snr]) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ProductionTimeFlow] CHECK CONSTRAINT [FK_ProductionTimeFlow_Production]

go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Note' and o.id = OBJECT_ID(N'[dbo].[PersAdresse]'))
BEGIN
	ALTER TABLE dbo.PersAdresse ADD [Note] [varchar](200)  NULL
END 

go
--2008-12-01 (Hauptrolle)
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'StarRole' and o.id = OBJECT_ID(N'[dbo].[BesetzungStd]'))
BEGIN
	ALTER TABLE dbo.BesetzungStd ADD StarRole BIT NOT NULL DEFAULT(0)
END 
go
--2008-12-04

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QualificationCategory]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[QualificationCategory](
		[QualificationCategoryId] [int] IDENTITY(1,1) NOT NULL,
		[Name] [varchar](20) NOT NULL,
		[Module] [int] NOT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
	 CONSTRAINT [PK_QualificationCategory] PRIMARY KEY CLUSTERED 
	(
		[QualificationCategoryId] ASC
	)WITH FILLFACTOR = 90  ON [PRIMARY]
	) ON [PRIMARY]	
END
go
GRANT SELECT ON [dbo].QualificationCategory TO Public
GRANT DELETE ON [dbo].QualificationCategory TO [Stammdaten ändern]
GRANT INSERT ON [dbo].QualificationCategory TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].QualificationCategory TO [Stammdaten ändern]

GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Qualification]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qualification](
		[QualificationId] [int] IDENTITY(1,1) NOT NULL,
		[QualificationCategoryId] [int] NOT NULL,
		[Name] [varchar](20) NOT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
	 CONSTRAINT [PK_Qualification] PRIMARY KEY CLUSTERED 
	(
		[QualificationId] ASC
	) WITH FILLFACTOR = 90  ON [PRIMARY],
	 CONSTRAINT [IX_Name_CategoryId] UNIQUE NONCLUSTERED 
	(	[Name] ASC,
		[QualificationCategoryId] ASC
	) ON [PRIMARY]
	) ON [PRIMARY]
END
go
GRANT SELECT ON [dbo].Qualification TO Public
GRANT DELETE ON [dbo].Qualification TO [Stammdaten ändern]
GRANT INSERT ON [dbo].Qualification TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].Qualification TO [Stammdaten ändern]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Qualification_QualificationCategory]') AND type = 'F')
ALTER TABLE [dbo].[Qualification]  WITH CHECK ADD  CONSTRAINT [FK_Qualification_QualificationCategory] FOREIGN KEY([QualificationCategoryId])
REFERENCES [dbo].[QualificationCategory] ([QualificationCategoryId])
GO
ALTER TABLE [dbo].[Qualification] CHECK CONSTRAINT [FK_Qualification_QualificationCategory]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Qualification_Person]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qualification_Person](
		[Qualification_PersonId] [int] IDENTITY(1,1) NOT NULL,
		[QualificationId] [int] NOT NULL,
		[PersonId] [int] NOT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
	 CONSTRAINT [PK_Qualification_Person] PRIMARY KEY CLUSTERED 
	(	[Qualification_PersonId] ASC
	)WITH FILLFACTOR = 90   ON [PRIMARY],
	 CONSTRAINT [IX_PersonId_QualificationId] UNIQUE NONCLUSTERED 
	(	[PersonId] ASC,
		[QualificationId] ASC
	) ON [PRIMARY]
	) ON [PRIMARY]
END
go
GRANT SELECT ON [dbo].Qualification_Person TO Public
GRANT DELETE ON [dbo].Qualification_Person TO [Soli-Daten ändern]
GRANT INSERT ON [dbo].Qualification_Person TO [Soli-Daten ändern]
GRANT UPDATE ON [dbo].Qualification_Person TO [Soli-Daten ändern]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Qualification_Person_PersH]') AND type = 'F')
ALTER TABLE [dbo].[Qualification_Person]  WITH CHECK ADD  CONSTRAINT [FK_Qualification_Person_PersH] FOREIGN KEY([PersonId])
REFERENCES [dbo].[PersH] ([PersNr])ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Qualification_Person] CHECK CONSTRAINT [FK_Qualification_Person_PersH]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Qualification_Person_Qualification]') AND type = 'F')
ALTER TABLE [dbo].[Qualification_Person]  WITH CHECK ADD  CONSTRAINT [FK_Qualification_Person_Qualification] FOREIGN KEY([QualificationId])
REFERENCES [dbo].[Qualification] ([QualificationId]) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Qualification_Person] CHECK CONSTRAINT [FK_Qualification_Person_Qualification]
GO



IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Qualification_Role]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Qualification_Role](
		[Qualification_RoleId] [int] IDENTITY(1,1) NOT NULL,
		[QualificationId] [int] NOT NULL,
		[RoleId] [int] NOT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
	 CONSTRAINT [PK_Qualification_Role] PRIMARY KEY CLUSTERED 
	(	[Qualification_RoleId] ASC
	)WITH  FILLFACTOR = 90   ON [PRIMARY] 
	) ON [PRIMARY]
END
go
GRANT SELECT ON [dbo].Qualification_Role TO Public
GRANT DELETE ON [dbo].Qualification_Person TO [Soli-Daten ändern]
GRANT INSERT ON [dbo].Qualification_Person TO [Soli-Daten ändern]
GRANT UPDATE ON [dbo].Qualification_Person TO [Soli-Daten ändern]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Qualification_Role_BesetzungStd]') AND type = 'F')
ALTER TABLE [dbo].[Qualification_Role]  WITH CHECK ADD  CONSTRAINT [FK_Qualification_Role_BesetzungStd] FOREIGN KEY([RoleId])
REFERENCES [dbo].[BesetzungStd] ([ID])  ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Qualification_Role] CHECK CONSTRAINT [FK_Qualification_Role_BesetzungStd]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Qualification_Role_Qualification]') AND type = 'F')
ALTER TABLE [dbo].[Qualification_Role]  WITH CHECK ADD  CONSTRAINT [FK_Qualification_Role_Qualification] FOREIGN KEY([QualificationId])
REFERENCES [dbo].[Qualification] ([QualificationId])  ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Qualification_Role] CHECK CONSTRAINT [FK_Qualification_Role_Qualification]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Qualification_Person]')  AND name = 'IX_PersonId')
BEGIN

CREATE NONCLUSTERED INDEX [IX_PersonId] ON [dbo].[Qualification_Person] 
(	[PersonId] ASC
) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IX_QualificationCategoryId] ON [dbo].[Qualification] 
(	[QualificationCategoryId] ASC
) ON [PRIMARY]

CREATE UNIQUE NONCLUSTERED INDEX [IX_QualificationCategory_Module] ON [dbo].[QualificationCategory] 
(	[Name] ASC,
	[Module] ASC
) ON [PRIMARY]

CREATE UNIQUE NONCLUSTERED INDEX [IX_Role_QualificationId_RoleId] ON [dbo].[Qualification_Role] 
(	[QualificationId] ASC,
	[RoleId] ASC
) ON [PRIMARY]

CREATE NONCLUSTERED INDEX [IX_QualificationId] ON [dbo].[Qualification_Role] 
(	[QualificationId] ASC
) ON [PRIMARY]

END
GO
UPDATE v SET  persoParameterID = NULL  FROM VertragsVorlagen as v  LEFT JOIN PersoParameter as p  on v.[persoParameterID]=p.[persoParameterID]
WHERE p.[persoParameterID] IS NULL AND NOT v.[persoParameterID] IS NULL

GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_VertragsVorlagen_persoParameter]') AND type = 'F')
ALTER TABLE [dbo].[VertragsVorlagen ]  WITH CHECK ADD  CONSTRAINT [FK_VertragsVorlagen_persoParameter] FOREIGN KEY([persoParameterID])
REFERENCES [dbo].[persoParameter] ([persoParameterID])
Go
ALTER TABLE [dbo].[VertragsVorlagen] CHECK CONSTRAINT FK_VertragsVorlagen_persoParameter


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsInactive' and o.id = OBJECT_ID(N'[dbo].BesetzungStd'))
BEGIN				
	ALTER TABLE BesetzungStd ADD IsInactive BIT NOT NULL DEFAULT(0)
END


go

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Cast_CastStatus]') AND type = 'F')
ALTER TABLE [dbo].[BesetzungTabelle]  WITH CHECK ADD  CONSTRAINT [FK_Cast_CastStatus] FOREIGN KEY([CastStatusId])
REFERENCES [dbo].[CastStatus] ([CastStatusId])  
GO
ALTER TABLE [dbo].[BesetzungTabelle] CHECK CONSTRAINT [FK_Cast_CastStatus]
GO
DELETE FROM VertragDetails WHERE Vertragsnr IN (
  SELECT d.Vertragsnr FROM VertragDetails AS d
  LEFT JOIN Vertrag AS v ON d.vertragsnr=v.Vertragsnr
  WHERE v.vertragsnr IS NULL)
go

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractDetails_Contract]') AND type = 'F')
ALTER TABLE [dbo].[VertragDetails]  WITH CHECK ADD  CONSTRAINT [FK_ContractDetails_Contract] FOREIGN KEY([VertragsNr])
REFERENCES [dbo].[Vertrag] ([VertragsNr])   ON DELETE CASCADE
GO
ALTER TABLE [dbo].[VertragDetails] CHECK CONSTRAINT [FK_ContractDetails_Contract]

go
DELETE FROM PersAgentur  WHERE ChildPersNr IS NULL

DELETE FROM PersAgentur  WHERE PersAgNr IN (
	SELECT PersAgNr FROM PersAgentur LEFT JOIN Persh ON PersAgentur.PersNr=Persh.PersNr WHERE Persh.PersNr IS NULL
	)
	
DELETE FROM PersAgentur  WHERE PersAgNr IN (	
	SELECT PersAgNr FROM PersAgentur LEFT JOIN Persh ON PersAgentur.ChildPersNr=Persh.PersNr WHERE Persh.PersNr IS NULL
	)
go	

--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContactHierarchical1_Contact]') AND type = 'F')
--ALTER TABLE [dbo].[PersAgentur]  WITH CHECK ADD  CONSTRAINT [FK_ContactHierarchical1_Contact] FOREIGN KEY([PersNr])
--REFERENCES [dbo].[PersH] ([PersNr])   ON DELETE CASCADE
--GO
--ALTER TABLE [dbo].[PersAgentur] CHECK CONSTRAINT [FK_ContactHierarchical1_Contact]

--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContactHierarchical2_Contact]') AND type = 'F')
--ALTER TABLE [dbo].[PersAgentur]  WITH CHECK ADD  CONSTRAINT [FK_ContactHierarchical2_Contact] FOREIGN KEY([ChildPersNr])
--REFERENCES [dbo].[PersH] ([PersNr])    ON DELETE CASCADE
--GO
--ALTER TABLE [dbo].[PersAgentur] CHECK CONSTRAINT [FK_ContactHierarchical2_Contact]

go


-----------------------------------
-- Tabelle BodyMeasureCategories --
-----------------------------------

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[BodyMeasureCategories]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BodyMeasureCategories](
		[BodyMeasureCategoryId] [int] IDENTITY(1,1) NOT NULL,
		[Sort] [int] NULL DEFAULT 0,
		[Name] [varchar](20) NOT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		CONSTRAINT [PK_BodyMeasureCategories] PRIMARY KEY CLUSTERED (
			[BodyMeasureCategoryId] ASC
		) ON [PRIMARY],
		CONSTRAINT [UQ_BodyMeasureCategories_Name] UNIQUE NONCLUSTERED (			
			[Name] ASC
		) ON [PRIMARY]
	) ON [PRIMARY]
END

GRANT SELECT ON [dbo].[BodyMeasureCategories] TO Public
GRANT DELETE ON [dbo].[BodyMeasureCategories] TO [Stammdaten ändern]
GRANT INSERT ON [dbo].[BodyMeasureCategories] TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].[BodyMeasureCategories] TO [Stammdaten ändern]
GO

--------------------------
-- Tabelle BodyMeasures --
--------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[BodyMeasures]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BodyMeasures](
		[BodyMeasureId] [int] IDENTITY(1,1) NOT NULL,
		[BodyMeasureCategoryId] [int] NOT NULL,
		[Sort] [int] NULL DEFAULT 0,
		[Name] [varchar](30) NOT NULL,
		[Description] [varchar](30) NULL,
		[GenderFilter] [bit] NULL,
		[TheasoftBodyMeasureId] [int] NULL,
		[Module] [int] NOT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		CONSTRAINT [PK_BodyMeasures] PRIMARY KEY CLUSTERED (
			[BodyMeasureId] ASC
		) ON [PRIMARY],
		CONSTRAINT [UQ_BodyMeasures_Name] UNIQUE NONCLUSTERED (			
			[Name] ASC
		) ON [PRIMARY],
	CONSTRAINT [FK_BodyMeasures_BodyMeasureCategories] FOREIGN KEY ([BodyMeasureCategoryId])
		REFERENCES [dbo].[BodyMeasureCategories] ([BodyMeasureCategoryId])
		ON DELETE CASCADE		
	) ON [PRIMARY]
END
GO


IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BodyMeasures]')  AND name = 'IX_BodyMeasures_BodyMeasureCategoryId')
CREATE NONCLUSTERED INDEX [IX_BodyMeasures_BodyMeasureCategoryId] ON [dbo].[BodyMeasures] (
	[BodyMeasureCategoryId]
) ON [PRIMARY]
GO

GRANT SELECT ON [dbo].[BodyMeasures] TO Public
GRANT DELETE ON [dbo].[BodyMeasures] TO [Stammdaten ändern]
GRANT INSERT ON [dbo].[BodyMeasures] TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].[BodyMeasures] TO [Stammdaten ändern]
GO

------------------------------
-- Tabelle BodyMeasurements --
------------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[BodyMeasurements]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BodyMeasurements](
		[BodyMeasurementId] [int] IDENTITY(1,1) NOT NULL,
		[PersonId] [int] NOT NULL,
		[MeasuredAt] [datetime] NOT NULL,
		[Note] [text] NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		CONSTRAINT [PK_BodyMeasurements] PRIMARY KEY CLUSTERED (
			[BodyMeasurementId] ASC
		) ON [PRIMARY],
		CONSTRAINT [UQ_BodyMeasurements_PersonId_MeasuredAt] UNIQUE NONCLUSTERED (
			[PersonId] ASC,
			[MeasuredAt] ASC
		) ON [PRIMARY],
		CONSTRAINT [FK_BodyMeasurements_PersH] FOREIGN KEY ([PersonId])
			REFERENCES [dbo].[PersH] ([PersNr])
			ON DELETE CASCADE
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BodyMeasurements]')  AND name = 'IX_BodyMeasurements_PersonId')
CREATE NONCLUSTERED INDEX [IX_BodyMeasurements_PersonId] ON [dbo].[BodyMeasurements] (
	[PersonId]
) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BodyMeasurements]')  AND name = 'IX_BodyMeasurements_MeasuredAt')
CREATE NONCLUSTERED INDEX [IX_BodyMeasurements_MeasuredAt] ON [dbo].[BodyMeasurements] (
	[MeasuredAt]
) ON [PRIMARY]
GO

GRANT SELECT ON [dbo].[BodyMeasurements] TO [Kostüm-Daten lesen]
GRANT SELECT ON [dbo].[BodyMeasurements] TO KostümDatenSchreiben
GRANT DELETE ON [dbo].[BodyMeasurements] TO KostümDatenSchreiben
GRANT INSERT ON [dbo].[BodyMeasurements] TO KostümDatenSchreiben
GRANT UPDATE ON [dbo].[BodyMeasurements] TO KostümDatenSchreiben


GO

---------------------------------
-- Tabelle BodyMeasurementData --
---------------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[BodyMeasurementData]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BodyMeasurementData](
		[BodyMeasurementDataId] [int] IDENTITY(1,1) NOT NULL,
		[BodyMeasurementId] [int] NOT NULL,
		[BodyMeasureId] [int] NOT NULL,
		[MeasuredValue] [varchar](10) NULL DEFAULT '',
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		CONSTRAINT [PK_BodyMeasurementData] PRIMARY KEY CLUSTERED (
			[BodyMeasurementDataId] ASC
		) ON [PRIMARY],
		CONSTRAINT [FK_BodyMeasurementData_BodyMeasurements] FOREIGN KEY ([BodyMeasurementId])
			REFERENCES [dbo].[BodyMeasurements] ([BodyMeasurementId])
			ON DELETE CASCADE,
		CONSTRAINT [FK_BodyMeasurementData_BodyMeasures] FOREIGN KEY ([BodyMeasureId])
			REFERENCES [dbo].[BodyMeasures] ([BodyMeasureId])
			ON DELETE CASCADE
	) ON [PRIMARY]
END
GO

GRANT SELECT ON [dbo].[BodyMeasurementData] TO [Kostüm-Daten lesen]
GRANT SELECT ON [dbo].[BodyMeasurementData] TO KostümDatenSchreiben
GRANT DELETE ON [dbo].[BodyMeasurementData] TO KostümDatenSchreiben
GRANT INSERT ON [dbo].[BodyMeasurementData] TO KostümDatenSchreiben
GRANT UPDATE ON [dbo].[BodyMeasurementData] TO KostümDatenSchreiben
GO


IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Stand' and o.id = OBJECT_ID(N'[dbo].PersMasse'))
BEGIN
	ALTER TABLE PersMasse ADD Stand  DATETIME NULL
END
go
-- Daten für Körpermaße
IF NOT EXISTS (SELECT * FROM BodyMeasureCategories)
BEGIN
	SET  IDENTITY_INSERT  BodyMeasureCategories ON
	INSERT INTO BodyMeasureCategories (BodyMeasureCategoryId, Sort, Name, LM ,UM, LC ,UC) VALUES (1, 1, 'Allgemeine Maße', GetDate(), 0, GetDate(), 0)
	SET  IDENTITY_INSERT  BodyMeasureCategories OFF

	SET  IDENTITY_INSERT  BodyMeasures ON	
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (1, 1, 1, 'Kopfweite', null, 1, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (2,1, 2, 'Halsweite', null, 2, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (3,1, 3, 'Brustbreite', null, 3, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (4,1, 4, 'Rückenbreite', null, 4, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (5,1, 5, 'Rückenlänge', null, 5, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (6,1, 6, 'Taillenweite', null, 6, 1 , GetDate(), 0, GetDate(), 0)			  
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (7,1, 7, 'Seitenhöhe', null, 7, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (8,1, 8, 'Schulter-Ärmellänge', null, 8, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (9,1, 9, 'Oberarmweite', null, 9, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (10,1, 10, 'Unterarmweite', null, 10, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (11,1, 11, 'Handgelenkweite', null, 11, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (12,1, 12, 'Gesäßweite', null, 12, 1 , GetDate(), 0, GetDate(), 0) 
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (13,1, 13, 'Schritt-Sohle', null, 13, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (14,1, 14, 'Oberschenkelweite', null, 14, 1 , GetDate(), 0, GetDate(), 0) 
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (15,1, 15, 'Wadenweite', null, 15, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (16,1, 16, 'Wadenlänge', null, 16, 1 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (17,1, 17, 'Schuhgröße', null, 17, 51 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (18,1, 18, 'Konfektion', null, 18, 51 , GetDate(), 0, GetDate(), 0)
	INSERT INTO BodyMeasures (BodyMeasureId, BodyMeasureCategoryId, Sort, Name, GenderFilter, TheasoftBodyMeasureId, Module, LM ,UM, LC ,UC) VALUES (19,1, 19, 'Körpergröße', null, 19, 1 , GetDate(), 0, GetDate(), 0)				  
	SET  IDENTITY_INSERT  BodyMeasures OFF		
				  
	SET  IDENTITY_INSERT  BodyMeasurements ON				  
	INSERT INTO BodyMeasurements (BodyMeasurementId, PersonId, MeasuredAt, Note, LM, UM, LC ,UC )SELECT Persnr,Persnr,CASE WHEN Stand IS NULL THEN '19000101' ELSE Stand END, MemoMasse, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END FROM PersMasse 
	SET  IDENTITY_INSERT  BodyMeasurements OFF
	             
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC) SELECT Persnr,1, Kopf, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Kopf IS NULL AND Kopf <> 0
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC) SELECT Persnr,2, Kragen, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Kragen IS NULL AND Kragen <> 0
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC) SELECT Persnr,3, Brust, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Brust IS NULL AND Brust <> 0
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,4, Rueckenbreite, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Rueckenbreite IS NULL AND Rueckenbreite <> 0
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,5, Rueckenlaenge, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Rueckenlaenge IS NULL AND Rueckenlaenge <> 0
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,6, Taille, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Taille IS NULL AND Taille <> 0
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,7, Seite, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Seite IS NULL AND Seite <> 0
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,8, Arm, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Arm IS NULL AND Arm <> 0
	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id  WHERE c.name = 'Oberarmweite' and o.id = OBJECT_ID(N'[dbo].PersMasse')) 
		exec ('INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,9, Oberarmweite, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Oberarmweite IS NULL AND Oberarmweite <> 0 ')

	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id  WHERE c.name = 'Unterarmweite' and o.id = OBJECT_ID(N'[dbo].PersMasse'))
		exec ('INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,10, Unterarmweite, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Unterarmweite IS NULL AND Unterarmweite <> 0')
	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id  WHERE c.name = 'Handgelenkweite' and o.id = OBJECT_ID(N'[dbo].PersMasse'))
		exec ('INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,11, Handgelenkweite, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Handgelenkweite IS NULL AND Handgelenkweite <> 0')
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,12, Po, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Po IS NULL AND Po <> 0
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,13, Schritt, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Schritt IS NULL AND Schritt <> 0
	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id  WHERE c.name = 'Oberschenkelweite' and o.id = OBJECT_ID(N'[dbo].PersMasse'))
		exec ('INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,14, Oberschenkelweite, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Oberschenkelweite IS NULL AND Oberschenkelweite <> 0	')
	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id  WHERE c.name = 'Wadenweite' and o.id = OBJECT_ID(N'[dbo].PersMasse'))
		exec ('INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,15, Wadenweite, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Wadenweite IS NULL AND Wadenweite <> 0')
	IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id  WHERE c.name = 'Wadenlaenge' and o.id = OBJECT_ID(N'[dbo].PersMasse'))
		exec ('INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,16, Wadenlaenge, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Wadenlaenge IS NULL AND Wadenlaenge <> 0')
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,17, Schuh, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Schuh IS NULL AND Schuh <> 0
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,18, Konfektion, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Konfektion IS NULL AND Konfektion <> 0
	INSERT INTO BodyMeasurementData (BodyMeasurementId, BodyMeasureId, MeasuredValue, LM ,UM ,LC ,UC)SELECT Persnr,19, Groesse, CASE WHEN LM IS NULL THEN GetDate() ELSE LM END, CASE WHEN UM IS NULL THEN 0 ELSE UM END,CASE WHEN LM IS NULL THEN GetDate() ELSE LM END,CASE WHEN UC IS NULL THEN 0 ELSE UC END  FROM PersMasse  WHERE NOT Groesse IS NULL AND Groesse <> 0
END
GO
        
     
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'NoRegularWorkingTime' and o.id = OBJECT_ID(N'[dbo].[Zeitkonten]'))
BEGIN
	ALTER TABLE dbo.Zeitkonten ADD 	NoRegularWorkingTime BIT NOT NULL  Default 0
END

GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Visibility' and o.id = OBJECT_ID(N'[dbo].[DienstplanArtenKopf]'))
BEGIN
	ALTER TABLE dbo.[DienstplanArtenKopf] ADD [Visibility] INT NOT NULL DEFAULT 1
END
GO
--######################################## 2 0 0 9 #################################################


----------------------
-- Tabelle WageType --
----------------------
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[WageType]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[WageType](
		[WageTypeId] int IDENTITY(1,1) NOT NULL,
		[WageTypeNo] varchar(10) NOT NULL,
		[WageTypeDescription] varchar (50) NOT NULL,
		[WageTypeCategory] int NULL,
		[Module] int NOT NULL,
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
		CONSTRAINT [PK_WageType] PRIMARY KEY CLUSTERED (
			[WageTypeId] ASC
		) ON [PRIMARY]
	) ON [PRIMARY]
END

GRANT SELECT ON [dbo].[WageType] TO Public
GRANT DELETE ON [dbo].[WageType] TO [Stammdaten ändern]
GRANT INSERT ON [dbo].[WageType] TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].[WageType] TO [Stammdaten ändern]

GO

------------------------
-- Tabelle CostCenter --
------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CostCenter]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CostCenter](
		[CostCenterId] int IDENTITY(1,1) NOT NULL,
		[CostCenterNo] varchar(10) NOT NULL,
		[CostCenterDescription] varchar (50) NOT NULL,
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
		CONSTRAINT [PK_CostCenter] PRIMARY KEY CLUSTERED (
			[CostCenterId] ASC
		) ON [PRIMARY]
	) ON [PRIMARY]
END

GRANT SELECT ON [dbo].[CostCenter] TO Public
GRANT DELETE ON [dbo].[CostCenter] TO [Stammdaten ändern]
GRANT INSERT ON [dbo].[CostCenter] TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].[CostCenter] TO [Stammdaten ändern]

GO

------------------------
-- Tabelle CostUnit --
------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CostUnit]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CostUnit](
		[CostUnitId] int IDENTITY(1,1) NOT NULL,
		[CostUnitNo] varchar(10) NOT NULL,
		[CostUnitDescription] varchar(50) NOT NULL,
		[ProductionId] int NULL,
		[CostUnitType] int NOT NULL DEFAULT (0),
		[BookableFrom] Datetime NULL,
		[BookableTo] Datetime NULL,
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
		CONSTRAINT [PK_CostUnit] PRIMARY KEY CLUSTERED ([CostUnitId] ASC) ON [PRIMARY],
		CONSTRAINT [FK_CostUnit_Stücke] FOREIGN KEY([ProductionId]) REFERENCES [dbo].[Stücke] ([SNr])
	) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX [IX_CostUnit_ProductionId] ON [dbo].[CostUnit] ([ProductionId])
END

GRANT SELECT ON [dbo].[CostUnit] TO Public
GRANT DELETE ON [dbo].[CostUnit] TO [Stammdaten ändern]
GRANT INSERT ON [dbo].[CostUnit] TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].[CostUnit] TO [Stammdaten ändern]

GO

-------------------------
-- Tabelle BudgetItem --
-------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[BudgetItem]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BudgetItem](
		[BudgetItemId] int IDENTITY(1,1) NOT NULL,
		[ParentBudgetItemId] int NULL,		
		[BudgetItemNo] varchar(12) NOT NULL,
		[BudgetItemDescription] varchar(50) NULL,		
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
		CONSTRAINT [PK_BudgetItem] PRIMARY KEY CLUSTERED ([BudgetItemId] ASC) ON [PRIMARY],
		CONSTRAINT [FK_BudgetItem_BudgetItem] FOREIGN KEY([ParentBudgetItemId]) REFERENCES [dbo].[BudgetItem] ([BudgetItemId])
	) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX [IX_BudgetItem_ParentBudgetItemId] ON [dbo].[BudgetItem] ([ParentBudgetItemId])
END

GRANT SELECT ON [dbo].[BudgetItem] TO Public
GRANT DELETE ON [dbo].[BudgetItem] TO [Stammdaten ändern]
GRANT INSERT ON [dbo].[BudgetItem] TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].[BudgetItem] TO [Stammdaten ändern]

GO

-------------------------
-- Tabelle CashCommand --
-------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CashCommand]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
  CREATE TABLE [dbo].[CashCommand](
    [CashCommandId] int IDENTITY(1,1) NOT NULL,
	[PersonId] int NOT NULL,
	[BankAccountID] int NULL,
	[AddressId] int NULL,
	[AgencyId] int NULL,
	[MainStageId] int NULL,
	[CashDate] datetime NOT NULL,
	[LM] datetime NOT NULL,
	[UM] int NOT NULL,
	[LC] datetime NOT NULL,
	[UC] int NOT NULL,
	CONSTRAINT [PK_CashCommand] PRIMARY KEY CLUSTERED (
		[CashCommandId] ASC
	) ON [PRIMARY],
	CONSTRAINT [FK_CashCommand_PersH_PersonId] FOREIGN KEY([PersonId]) REFERENCES [dbo].[PersH] ([PersNr]),
	CONSTRAINT [FK_CashCommand_PersH_AgencyId] FOREIGN KEY([AgencyId]) REFERENCES [dbo].[PersH] ([PersNr]),
	CONSTRAINT [FK_CashCommand_PersAdresse] FOREIGN KEY([AddressId]) REFERENCES [dbo].[PersAdresse] ([AdressID]),
	CONSTRAINT [FK_CashCommand_ZR] FOREIGN KEY([MainStageId]) REFERENCES [dbo].[ZR] ([ZRNR])
  ) ON [PRIMARY]
  
  CREATE NONCLUSTERED INDEX [IX_CashCommand_PersonId] ON [dbo].[CashCommand] ([PersonId])
  CREATE NONCLUSTERED INDEX [IX_CashCommand_CashDate] ON [dbo].[CashCommand] ([CashDate])
END

GO

----------------------------
-- Tabelle CashCommandPos --
----------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CashCommandPos]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CashCommandPos](
		[CashCommandPosId] int IDENTITY(1,1) NOT NULL,
		[CashCommandId] int NOT NULL,
		[BudgetItemId] int NOT NULL,		
		[Sort] int NOT NULL CONSTRAINT [DF_CashCommandPos_Sort] DEFAULT (0),
		[CashValue] money NOT NULL CONSTRAINT [DF_CashCommandPos_CashValue]DEFAULT (0),
		[Quantity] int NOT NULL CONSTRAINT [DF_CashCommandPos_Quantity] DEFAULT (1),
		[CostCenterId] int NOT NULL,
		[CostUnitId] int NOT NULL,
		[WageTypeId] int NULL,
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
	 CONSTRAINT [PK_CashCommandPos] PRIMARY KEY CLUSTERED ([CashCommandPosId] ASC) ON [PRIMARY],
	 CONSTRAINT [FK_CashCommandPos_CashCommand] FOREIGN KEY([CashCommandId])REFERENCES [dbo].[CashCommand]  ([CashCommandId])ON DELETE CASCADE,
	 CONSTRAINT [FK_CashCommandPos_CostCenter]	FOREIGN KEY([CostCenterId])	REFERENCES [dbo].[CostCenter]	([CostCenterId]),
	 CONSTRAINT [FK_CashCommandPos_CostUnit]	FOREIGN KEY([CostUnitId])	REFERENCES [dbo].[CostUnit]		([CostUnitId]),
	 CONSTRAINT [FK_CashCommandPos_WageType]	FOREIGN KEY([WageTypeId])	REFERENCES [dbo].[WageType]		([WageTypeId]),
	 CONSTRAINT [FK_CashCommandPos_BudgetItem]	FOREIGN KEY([BudgetItemId])	REFERENCES [dbo].[BudgetItem]	([BudgetITemId])
	) ON [PRIMARY]
	
	CREATE NONCLUSTERED INDEX [IX_CashCommandPos_CashCommandId] ON [dbo].[CashCommandPos] ([CashCommandId])
END
	

GO
-----------------------------
-- Tabelle CashCommandPos_Cast --
-----------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CashCommandPos_Cast]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CashCommandPos_Cast](
		[CashCommandPosCastId] int IDENTITY(1,1) NOT NULL,
		[CashCommandPosId] int NOT NULL,
		[CastId] int NOT NULL,
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
	 CONSTRAINT [PK_CashCommandPosCast] PRIMARY KEY CLUSTERED  ([CashCommandPosCastId] ASC) ON [PRIMARY],
	 CONSTRAINT [FK_CashCommandPosCast_CashCommandPos] FOREIGN KEY([CashCommandPosId]) REFERENCES [dbo].[CashCommandPos] ([CashCommandPosId]) ON DELETE CASCADE,
	 CONSTRAINT [FK_CashCommandPosCast_Cast] FOREIGN KEY([CastId]) REFERENCES [dbo].[BesetzungTabelle] ([Id]) ON DELETE CASCADE
	) ON [PRIMARY]
	
	CREATE NONCLUSTERED INDEX [IX_CashCommandPosCast_CashCommandPosId] ON [dbo].[CashCommandPos_Cast] ([CashCommandPosId])		
END

GRANT SELECT ON [dbo].[CashCommandPos_Cast] TO public

GO



IF (SELECT count(*) FROM CostUnit) = 0 
BEGIN
	INSERT INTO CostUnit (CostUnitNo,ProductionId, CostUnitDescription,CostUnitType,uc,um,lc,lm) 
	SELECT KstNr, Stücke.Snr, Titel + ' ' + ISNULL(inszenierung,'') , 0,0,0,'19000101','19000101'
	FROM Stücke INNER JOIN StückeDetails as sd ON Stücke.Snr=sd.Snr 
	WHERE NOT KstNr IS NULL AND KstNr <> ''
END
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Settings' and o.id = OBJECT_ID(N'[dbo].[PlanSort]'))
BEGIN
	ALTER TABLE dbo.PlanSort ADD Settings TEXT NULL
	ALTER TABLE dbo.[Plan] ADD Settings TEXT NULL
END
go

DELETE FROM Kosten_Aufführg WHERE Auffnr IN (
	SELECT ka.auffnr FROM Kosten_Aufführg as ka LEFT JOIN AufführgTabelle as at ON ka.Auffnr=at.Auffnr WHERE at.Auffnr IS NULL)
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_CostActivities_Activities]') AND type = 'F')
ALTER TABLE [dbo].[Kosten_Aufführg]  WITH CHECK ADD  CONSTRAINT [FK_CostActivities_Activities] FOREIGN KEY([AuffNr])
REFERENCES [dbo].[AufführgTabelle] ([AuffNr]) ON DELETE CASCADE
GO
UPDATE Vertrag SET VorlagenID = 0 FROM Vertrag WHERE  Vertragsnr IN (SELECT  c.Vertragsnr FROM Vertrag c LEFT JOIN VertragsVorlagen vv on c.VorlagenID = vv.VorlagenID WHERE vv.VorlagenID IS NULL)
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Contract_ContractType]') AND type = 'F')
ALTER TABLE [dbo].[Vertrag]  WITH CHECK ADD  CONSTRAINT [FK_Contract_ContractType] FOREIGN KEY([VorlagenID])
REFERENCES [dbo].[VertragsVorlagen] ([VorlagenID]) 


go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ReportTemplate]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
ALTER TABLE [dbo].[Vorlagen] ADD IsBookmarkType Bit NOT NULL Default(0)

CREATE TABLE [dbo].[ReportTemplate](
		[ReportTemplateId] int IDENTITY(1,1) NOT NULL,
		[TemplateId] int NOT NULL,
		[ReportType] int NOT NULL,
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
	 CONSTRAINT [UQ_ReportType_TemplateId] UNIQUE NONCLUSTERED ([TemplateId] ASC,[ReportType] ASC) ON [PRIMARY],
	 CONSTRAINT [PK_ReportTemplate] PRIMARY KEY CLUSTERED  ([ReportTemplateId] ASC) ON [PRIMARY],
	 CONSTRAINT [FK_ReportTemplate_Template] FOREIGN KEY([TemplateId]) REFERENCES [dbo].[Vorlagen] ([VorlagenId]) ON DELETE CASCADE
	) ON [PRIMARY]
	
	GRANT SELECT ON [dbo].[ReportTemplate] TO Public
	GRANT DELETE ON [dbo].[ReportTemplate] TO [Stammdaten ändern]
	GRANT INSERT ON [dbo].[ReportTemplate] TO [Stammdaten ändern]
	GRANT UPDATE ON [dbo].[ReportTemplate] TO [Stammdaten ändern]
	--exec ('INSERT INTO Vorlagen (DokName,Bez ) VALUES (''Castlist(Multipart).dot'',''Besetzungszettel'')')
	--exec ('INSERT INTO Vorlagen (DokName,Bez ) VALUES (''Castlist(Singlepart).dot'',''Besetzungszettel(Mehrteiler)'')')
	
	
	exec ('UPDATE Vorlagen SET IsBookmarkType = 1')
	
	exec ('INSERT INTO  ReportTemplate (ReportType, TemplateId, LM, UM, LC, UC) SELECT 1, VorlagenID, LM, UM, LC, UC FROM Vorlagen')
	
	
END
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'SalaryBracket' and o.id = OBJECT_ID(N'[dbo].[VertragPerso]'))
BEGIN
	ALTER TABLE dbo.VertragPerso ADD SalaryBracket VARCHAR(10) NULL
	INSERT INTO  UserGruppe (GruppeID,UserID,Schreiben,LM,UM,LC,UC,BerechtigungsbereichID) SELECT GruppeID,UserID,Schreiben,LM,UM,LC,UC,4 FROM UserGruppe WHERE BerechtigungsbereichID = 2
END

--
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Description' and o.id = OBJECT_ID(N'[dbo].[CashCommandPos]'))
BEGIN
	ALTER TABLE dbo.CashCommandPos ADD Description VARCHAR(100) NULL
END
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'OvertimePremiumIsFixValue' and o.id = OBJECT_ID(N'[dbo].[PersoParameter]'))
BEGIN
	ALTER TABLE dbo.PersoParameter ADD OvertimePremiumIsFixValue BIT NOT NULL DEFAULT(0)
END

go

--2009-01-21
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BlockNo' and o.id = OBJECT_ID(N'[dbo].[AB]'))
BEGIN
	ALTER TABLE dbo.AB ADD BlockNo INT NOT NULL DEFAULT(0)
END


IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ContentPath' and o.id = OBJECT_ID(N'[dbo].[AdressAusgabe]'))
BEGIN
	ALTER TABLE dbo.AdressAusgabe ADD ContentPath VARCHAR(250) 
END
go
UPDATE AdressAusgabe SET ContentPath = 
CASE 
	WHEN Ausgabefeld = 1 AND  Abs(Produktionsteam) = 1 THEN 'person.mobilephone' 
	WHEN Ausgabefeld = 2 AND  Abs(Produktionsteam) = 1 THEN 'person.gender'  
	WHEN Ausgabefeld = 4 AND  Abs(Produktionsteam) = 1 THEN 'person.searchname'  
	WHEN Ausgabefeld = 5 AND  Abs(Produktionsteam) = 1 THEN 'person.title'  
	WHEN Ausgabefeld = 6 AND  Abs(Produktionsteam) = 1 THEN 'person.firstname'  
	WHEN Ausgabefeld = 7 AND  Abs(Produktionsteam) = 1 THEN 'person.lastname'  
	WHEN Ausgabefeld = 8 AND  Abs(Produktionsteam) = 1 THEN 'person.country'  
	WHEN Ausgabefeld = 10 AND  Abs(Produktionsteam) = 1 THEN 'person.dateofbirth' 
	WHEN Ausgabefeld = 11 AND  Abs(Produktionsteam) = 1 THEN 'person.currentcontract.start' 
	WHEN Ausgabefeld = 12 AND  Abs(Produktionsteam) = 1 THEN 'person.currentcontract.end' 
	WHEN Ausgabefeld = 13 AND  Abs(Produktionsteam) = 1 THEN 'person.notes' 
	WHEN Ausgabefeld = 14 AND  Abs(Produktionsteam) = 1 THEN 'person.isGuest' 
	WHEN Ausgabefeld = 15 AND  Abs(Produktionsteam) = 1 THEN 'person.phonecom' 
	WHEN Ausgabefeld = 16 AND  Abs(Produktionsteam) = 1 THEN 'person.firstnameshort' 
	WHEN Ausgabefeld = 17 AND  Abs(Produktionsteam) = 1 THEN 'person.co' 
	WHEN Ausgabefeld = 18 AND  Abs(Produktionsteam) = 1 THEN 'person.inactiv' 
	WHEN Ausgabefeld = 19 AND  Abs(Produktionsteam) = 1 THEN 'person.email' 
	WHEN Ausgabefeld = 20 AND  Abs(Produktionsteam) = 1 THEN 'person.city' 
	WHEN Ausgabefeld = 21 AND  Abs(Produktionsteam) = 1 THEN 'person.phone' 
	WHEN Ausgabefeld = 22 AND  Abs(Produktionsteam) = 1 THEN 'person.fax' 
	WHEN Ausgabefeld = 23 AND  Abs(Produktionsteam) = 1 THEN 'person.street' 
	WHEN Ausgabefeld = 24 AND  Abs(Produktionsteam) = 1 THEN 'person.postalcode' 
	WHEN Ausgabefeld = 25 AND  Abs(Produktionsteam) = 1 THEN 'person.homepage' 
	WHEN Ausgabefeld = 26 AND  Abs(Produktionsteam) = 1 THEN 'person.agency.name' 
	WHEN Ausgabefeld = 31 AND  Abs(Produktionsteam) = 1 THEN 'person.agency.phone' 
	WHEN Ausgabefeld = 34 AND  Abs(Produktionsteam) = 1 THEN 'person.hotel.name' 
	WHEN Ausgabefeld = 39 AND  Abs(Produktionsteam) = 1 THEN 'person.hotel.phone' 
	WHEN Ausgabefeld = 40 AND  Abs(Produktionsteam) = 1 THEN 'person.hotel.fax'
	WHEN Ausgabefeld = 42 AND  Abs(Produktionsteam) = 1 THEN 'person.theater.name' 
	WHEN Ausgabefeld = 47 AND  Abs(Produktionsteam) = 1 THEN 'person.theater.phone' 
	WHEN Ausgabefeld = 49 AND  Abs(Produktionsteam) = 1 THEN 'person.contactcategory' 
	WHEN Ausgabefeld = 50 AND  Abs(Produktionsteam) = 1 THEN 'basiccast.role' 
	WHEN Ausgabefeld = 52 AND  Abs(Produktionsteam) = 1 THEN 'person.contactcategory' 
	WHEN Ausgabefeld = 54 AND  Abs(Produktionsteam) = 1 THEN 'person.dateofbirth' 
--	WHEN Ausgabefeld = 55 AND  Abs(Produktionsteam) = 1 THEN 'person.functions.' 
--	WHEN Ausgabefeld = 56 AND  Abs(Produktionsteam) = 1 THEN 'a' 
--	WHEN Ausgabefeld = 57 AND  Abs(Produktionsteam) = 1 THEN 'a' 
--	WHEN Ausgabefeld = 58 AND  Abs(Produktionsteam) = 1 THEN 'a' 
--	WHEN Ausgabefeld = 59 AND  Abs(Produktionsteam) = 1 THEN 'a' 
--	WHEN Ausgabefeld = 60 AND  Abs(Produktionsteam) = 1 THEN 'a' 
--	WHEN Ausgabefeld = 65 AND  Abs(Produktionsteam) = 1 THEN 'a' 
--	WHEN Ausgabefeld = 66 AND  Abs(Produktionsteam) = 1 THEN 'a' 
--	WHEN Ausgabefeld = 67 AND  Abs(Produktionsteam) = 1 THEN 'a' 
--	WHEN Ausgabefeld = 68 AND  Abs(Produktionsteam) = 1 THEN 'a' 
	WHEN Ausgabefeld = 1 AND  Abs(Produktionsteam) <> 1 THEN 'mobilephone' 
	WHEN Ausgabefeld = 2 AND  Abs(Produktionsteam) <> 1 THEN 'gender' 
	WHEN Ausgabefeld = 4 AND  Abs(Produktionsteam) <> 1 THEN 'searchname' 
	WHEN Ausgabefeld = 5 AND  Abs(Produktionsteam) <> 1 THEN 'title' 
	WHEN Ausgabefeld = 6 AND  Abs(Produktionsteam) <> 1 THEN 'firstname' 
	WHEN Ausgabefeld = 7 AND  Abs(Produktionsteam) <> 1 THEN 'lastname' 
	WHEN Ausgabefeld = 8 AND  Abs(Produktionsteam) <> 1 THEN 'country' 
	WHEN Ausgabefeld = 10 AND  Abs(Produktionsteam) <> 1 THEN 'dateofbirth' 
	WHEN Ausgabefeld = 11 AND  Abs(Produktionsteam) <> 1 THEN 'currentcontract.start'  
	WHEN Ausgabefeld = 12 AND  Abs(Produktionsteam) <> 1 THEN 'currentcontract.end'  
	WHEN Ausgabefeld = 13 AND  Abs(Produktionsteam) <> 1 THEN 'notes' 
	WHEN Ausgabefeld = 14 AND  Abs(Produktionsteam) <> 1 THEN 'isGuest' 
	WHEN Ausgabefeld = 15 AND  Abs(Produktionsteam) <> 1 THEN 'phonecom' 
	WHEN Ausgabefeld = 16 AND  Abs(Produktionsteam) <> 1 THEN 'firstnameshort' 
	WHEN Ausgabefeld = 17 AND  Abs(Produktionsteam) <> 1 THEN 'co' 
	WHEN Ausgabefeld = 18 AND  Abs(Produktionsteam) <> 1 THEN 'inactiv' 
	WHEN Ausgabefeld = 19 AND  Abs(Produktionsteam) <> 1 THEN 'email' 
	WHEN Ausgabefeld = 20 AND  Abs(Produktionsteam) <> 1 THEN 'city' 
	WHEN Ausgabefeld = 21 AND  Abs(Produktionsteam) <> 1 THEN 'phone' 
	WHEN Ausgabefeld = 22 AND  Abs(Produktionsteam) <> 1 THEN 'fax' 
	WHEN Ausgabefeld = 23 AND  Abs(Produktionsteam) <> 1 THEN 'street' 
	WHEN Ausgabefeld = 24 AND  Abs(Produktionsteam) <> 1 THEN 'postalcode' 
	WHEN Ausgabefeld = 25 AND  Abs(Produktionsteam) <> 1 THEN 'homepage' 
	WHEN Ausgabefeld = 26 AND  Abs(Produktionsteam) <> 1 THEN 'agency.name' 
	WHEN Ausgabefeld = 31 AND  Abs(Produktionsteam) <> 1 THEN 'agency.phone' 
	WHEN Ausgabefeld = 34 AND  Abs(Produktionsteam) <> 1 THEN 'hotel.name' 
	WHEN Ausgabefeld = 39 AND  Abs(Produktionsteam) <> 1 THEN 'hotel.phone' 
	WHEN Ausgabefeld = 40 AND  Abs(Produktionsteam) <> 1 THEN 'hotel.fax'
	WHEN Ausgabefeld = 42 AND  Abs(Produktionsteam) <> 1 THEN 'theater.name' 
	WHEN Ausgabefeld = 47 AND  Abs(Produktionsteam) <> 1 THEN 'theater.phone'
	WHEN Ausgabefeld = 49 AND  Abs(Produktionsteam) <> 1 THEN 'contactcategory'
	WHEN Ausgabefeld = 50 AND  Abs(Produktionsteam) <> 1 THEN 'basiccast.role' 
	WHEN Ausgabefeld = 52 AND  Abs(Produktionsteam) <> 1 THEN 'contactcategory' 
	WHEN Ausgabefeld = 54 AND  Abs(Produktionsteam) <> 1 THEN 'dateofbirth' 
--	WHEN Ausgabefeld = 55 AND  Produktionsteam > 1 THEN 'a' 
--	WHEN Ausgabefeld = 56 AND  Produktionsteam > 1 THEN 'a' 
--	WHEN Ausgabefeld = 57 AND  Produktionsteam > 1 THEN 'a' 
--	WHEN Ausgabefeld = 58 AND  Produktionsteam > 1 THEN 'a' 
--	WHEN Ausgabefeld = 59 AND  Produktionsteam > 1 THEN 'a' 
--	WHEN Ausgabefeld = 60 AND  Produktionsteam > 1 THEN 'a' 
--	WHEN Ausgabefeld = 65 AND  Produktionsteam > 1 THEN 'a' 
--	WHEN Ausgabefeld = 66 AND  Produktionsteam > 1 THEN 'a' 
--	WHEN Ausgabefeld = 67 AND  Produktionsteam > 1 THEN 'a' 
--	WHEN Ausgabefeld = 68 AND  Produktionsteam > 1 THEN 'a' 
END 
FROM AdressAusgabe 
INNER JOIN  AdressSpalte ON AdressAusgabe.AdressSpalteID = AdressSpalte.AdressSpalteID
INNER JOIN  AdressPlan ON AdressSpalte.AdressPlanID = AdressPlan.AdressPlanID
WHERE ContentPath IS NULL
go

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[CastActiveties]'))
BEGIN
	DROP VIEW [dbo].[CastActiveties]
END
go
CREATE VIEW [dbo].[CastActiveties]
AS
SELECT      ac.AuffNr, ac.Datum, ac.UhrBeg, ac.UhrEnde, ac.SNr, ac.ZRNr, ac.Art, ac.Bem,
			ca.PersNr, ca.DiffVon, ca.DiffBis, ca.CastStatusID, ca.Gesperrt, ca.ID, ca.IsCanceled, ca.RolleID,
			at.KatNr, ca.IsCover, ac.status, ca.Creditable
FROM		   AufführgTabelle 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 U	ON us.UserId =u.UserId
	INNER JOIN Besetzungtabelle	AS ca	ON ac.Auffnr =ca.auffnr
WHERE    
	u.UserName  = CURRENT_USER

go
GRANT SELECT ON [dbo].[CastActiveties] TO [Spielplan alles lesen]
GRANT SELECT ON [dbo].[CastActiveties] TO [Spielplan alles lesen]
go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[CastActivetiesPublic]'))
BEGIN
	DROP VIEW[dbo].[CastActivetiesPublic]
END
go
CREATE VIEW [dbo].[CastActivetiesPublic]
AS
SELECT      ac.AuffNr, ac.Datum, ac.UhrBeg, ac.UhrEnde, ac.SNr, ac.ZRNr, ac.Art, ac.Bem,
			ca.PersNr, ca.DiffVon, ca.DiffBis, ca.CastStatusID, ca.Gesperrt, ca.ID, ca.IsCanceled, ca.RolleID,
			at.KatNr, ca.IsCover, ac.status, ca.Creditable
FROM		   AufführgTabelle 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 U	ON us.UserId =u.UserId
	INNER JOIN Besetzungtabelle	AS ca	ON ac.Auffnr =ca.auffnr
WHERE    
		u.UserName  = CURRENT_USER 
	AND ac.Gesperrt = 0 
	AND ca.Gesperrt = 0 
go
GRANT SELECT ON [dbo].[CastActivetiesPublic] TO public
GRANT SELECT ON [dbo].[CastActivetiesPublic] TO public
go	 
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Composite' and o.id = OBJECT_ID(N'[dbo].[AdressAusgabe]'))
BEGIN
	ALTER TABLE dbo.AdressAusgabe ADD Composite VARCHAR(250) 
END
go
UPDATE AdressAusgabe SET Composite = 
	REPLICATE('\n', ISNULL(ReturnVor, 0))+
	ISNULL(ZeichenVor, '')+
	'[Value]'+
	ISNULL(Zeichen, '')+
	REPLICATE('\t', ISNULL(Tab, 0))+
	REPLICATE(' ', ISNULL(LeerZ, 0))+
	REPLICATE('\n', ISNULL(Cr, 0))
FROM AdressAusgabe
WHERE Composite IS NULL
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ContentSettings' and o.id = OBJECT_ID(N'[dbo].[AdressAusgabe]'))
BEGIN
	ALTER TABLE dbo.AdressAusgabe ADD ContentSettings TEXT
END
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PlanSettings' and o.id = OBJECT_ID(N'[dbo].[AdressPlan]'))
BEGIN
	ALTER TABLE dbo.AdressPlan ADD PlanSettings TEXT
END
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ParentCostCenterId' and o.id = OBJECT_ID(N'[dbo].[CostCenter]'))
BEGIN
	ALTER TABLE dbo.CostCenter ADD ParentCostCenterId INT NULL
	ALTER TABLE dbo.CostCenter ADD CostCenterNote varChar(100)
	ALTER TABLE dbo.CostCenter ADD IsClosed BIT NOT NULL DEFAULT(0)
	
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'UsedInProgramFunctions' and o.id = OBJECT_ID(N'[dbo].[CostCenter]'))
BEGIN
	ALTER TABLE dbo.CostCenter ADD UsedInProgramFunctions INT NOT NULL DEFAULT(0)
	ALTER TABLE dbo.BudgetItem ADD UsedInProgramFunctions INT NOT NULL DEFAULT(0)
END								  
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'UsedInProgramFunctions' and o.id = OBJECT_ID(N'[dbo].[WageType]'))
BEGIN
	ALTER TABLE dbo.WageType ADD UsedInProgramFunctions INT NOT NULL DEFAULT(0)
END	
go
--2009-01-29
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsCommercial' and o.id = OBJECT_ID(N'[dbo].[PersKomTyp]'))
BEGIN
	ALTER TABLE dbo.PersKomTyp ADD IsCommercial BIT NOT NULL DEFAULT(0)
	exec ('UPDATE PersKomTyp SET IsCommercial = 1 WHERE PersKTypID = 1')
	exec ('UPDATE PersKomTyp SET Bezeichnung = ''Tel gesch.'' WHERE PersKTypID = 1 AND Bezeichnung = ''Hausruf''')
	exec ('INSERT INTO [dbo].[PersKomTyp] (Bezeichnung,Sort,KDefault,KTyp,IsCommercial) VALUES (''Fax gesch.'',3,0,20,1)')
	exec ('INSERT INTO [dbo].[PersKomTyp] (Bezeichnung,Sort,KDefault,KTyp,IsCommercial) VALUES (''Email gesch.'',4,0,50,1)')
END
go


IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'L10' AND o.id = OBJECT_ID(N'[dbo].StückeDetails') AND c.prec < 255)
BEGIN
ALTER TABLE StückeDetails ALTER COLUMN L10 VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN L20 VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN L30 VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN L40 VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN L50 VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN L60 VARCHAR(255)

ALTER TABLE StückeDetails ALTER COLUMN F10 VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN F20 VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN F30 VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN F40 VARCHAR(255)

ALTER TABLE StückeDetails ALTER COLUMN K10 VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN K20 VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN K30 VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN K40 VARCHAR(255)

ALTER TABLE StückeDetails ALTER COLUMN KRechts VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN LRechts VARCHAR(255)
ALTER TABLE StückeDetails ALTER COLUMN InternetLink VARCHAR(100)
ALTER TABLE StückeDetails ALTER COLUMN Komponist VARCHAR(255)

END


IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BJBGenPos' AND o.id = OBJECT_ID(N'[dbo].PersonalDetails') AND c.prec < 50)
BEGIN
	ALTER TABLE PersonalDetails ALTER COLUMN BJBGenPos VARCHAR(50)
END


IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'MemoExtern' AND o.id = OBJECT_ID(N'[dbo].PersonalDetails') AND c.xtype<>99)
BEGIN
	ALTER TABLE PersonalDetails ADD MemoExternTemp NTEXT
	EXEC('UPDATE PersonalDetails SET MemoExternTemp = MemoExtern')
	ALTER TABLE PersonalDetails DROP COLUMN MemoExtern
	ALTER TABLE PersonalDetails ADD  MemoExtern NTEXT
	EXEC('UPDATE PersonalDetails SET MemoExtern = MemoExternTemp')
	EXEC ('ALTER TABLE PersonalDetails DROP COLUMN MemoExternTemp')
END
GO

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'MemoExtern_en' AND o.id = OBJECT_ID(N'[dbo].PersonalDetails') AND c.xtype<>99)
BEGIN
	ALTER TABLE PersonalDetails ADD MemoExtern_enTemp NTEXT
	EXEC('UPDATE PersonalDetails SET MemoExtern_enTemp = MemoExtern_en')
	ALTER TABLE PersonalDetails DROP COLUMN MemoExtern_en
	ALTER TABLE PersonalDetails ADD  MemoExtern_en NTEXT
	EXEC('UPDATE PersonalDetails SET MemoExtern_en = MemoExtern_enTemp')
	EXEC ('ALTER TABLE PersonalDetails DROP COLUMN MemoExtern_enTemp')
END
GO

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[AdressAusgabe]')  AND name = 'AdressSpalteID_Ausgabefeld')
	DROP Index AdressAusgabe.[AdressSpalteID_Ausgabefeld]
go



IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[ActivitiesPublic]'))
BEGIN
	DROP VIEW [dbo].ActivitiesPublic
END
GO
CREATE VIEW [dbo].ActivitiesPublic
AS
SELECT			act.*
FROM			AufführgTabelle act
	INNER JOIN	Spielzeittabelle AS s	ON act.Datum <= s.SpzEnde AND act.Datum >= s.SpzStart
	INNER JOIN	UserForAccess	AS us	ON s.spznr		= us.spznr
	INNER JOIN	UserPW			AS U	ON us.UserId	= u.UserId
WHERE    
	u.UserName  = CURRENT_USER AND act.Gesperrt = 0 
go
GRANT SELECT ON [dbo].[ActivitiesPublic] TO Public


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


GO
CREATE VIEW [dbo].ActivitiesProtected
AS
SELECT			act.*
FROM			AufführgTabelle act
	INNER JOIN	Spielzeittabelle AS s	ON act.Datum <= s.SpzEnde AND act.Datum >= s.SpzStart
	INNER JOIN	UserForAccess	AS us	ON s.spznr		= us.spznr
	INNER JOIN	UserPW			AS U	ON us.UserId	= u.UserId
	
WHERE    
	u.UserName  = CURRENT_USER
go
GRANT SELECT ON [dbo].[ActivitiesProtected] TO [Spielplan alles lesen]
GRANT SELECT ON [dbo].[ActivitiesProtected] TO [Spielplan ändern]
go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].SetActivetyDetails'))
BEGIN
	DROP PROCEDURE dbo.SetActivetyDetails
END
go
CREATE PROCEDURE [dbo].[SetActivetyDetails]
	@ActivetyId INT,
	@Places INT,
	@PriceId INT
AS
	UPDATE AufführgTabelle 
	SET		PreisNr = @PriceId,
			Pl		= @Places
		
	WHERE AuffNR	= @ActivetyId

go
GRANT EXECUTE ON [dbo].[SetActivetyDetails] TO [Vorverkauf ändern]

go
GRANT SELECT ON [dbo].[oAufführg] TO Public
go

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[CollectiveStatus]'))
BEGIN
	DROP VIEW [dbo].CollectiveStatus
END
GO
CREATE VIEW [dbo].CollectiveStatus
AS
SELECT			st.*,
				pk.AdressArt,
				P.Nachname, P.Suchname
FROM			StatusZeitR st
	INNER JOIN  PersH			AS P	ON st.PersNr = P.PersNr
	INNER JOIN  PersKat			AS pk	ON P.PersKatNr = pk.PersKatNr
WHERE    
	pk.AdressArt BETWEEN 100 AND 200
GO
GRANT SELECT ON [dbo].[CollectiveStatus] TO Public

go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PersEmployee]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PersEmployee](
		PersonId int NOT NULL,
		DefaultCostCenterId int NULL,
		ManagementDomainNo varchar(20) NULL,
		CapacityOffset REAL NOT NULL DEFAULT(0),
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
	 CONSTRAINT [PK_PersEmployee] PRIMARY KEY CLUSTERED  (PersonId ASC) ON [PRIMARY],
	 CONSTRAINT [FK_PersEmployee_Persh] FOREIGN KEY([PersonId]) REFERENCES [dbo].[Persh] ([Persnr]) ON DELETE CASCADE
	) ON [PRIMARY]
	exec ('INSERT INTO PersEmployee (PersonId,CapacityOffset,lm,um,lc,uc) SELECT pnr, Plan_Person, GetDate(),0, GetDate(),0 FROM PersonalDetails WHERE NOT Plan_Person IS NULL')
END	
	GRANT SELECT ON [dbo].[PersEmployee] TO Public
	GRANT DELETE ON [dbo].[PersEmployee] TO [Soli-Daten ändern]
	GRANT INSERT ON [dbo].[PersEmployee] TO [Soli-Daten ändern]
	GRANT UPDATE ON [dbo].[PersEmployee] TO [Soli-Daten ändern]
	
	GRANT DELETE ON [dbo].[AufR] TO [Vorverkauf ändern]
	GRANT INSERT ON [dbo].[AufR] TO [Vorverkauf ändern]
	GRANT UPDATE ON [dbo].[AufR] TO [Vorverkauf ändern]
go

-- 2009-02-23

-- Verweis von ZulagenDienstplan auf CostUnit
IF NOT 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].ZulagenDienstplan'))
BEGIN
	ALTER TABLE [ZulagenDienstplan] ADD [CostUnitId] [int] NULL
	ALTER TABLE [dbo].[ZulagenDienstplan]  WITH CHECK ADD  CONSTRAINT [FK_ZulagenDienstplan_CostUnit] FOREIGN KEY([CostUnitId])
	REFERENCES [dbo].[CostUnit] ([CostUnitId])
END
GO

-- 2009-02-24

-- Erweiterung der Zulagen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsCostUnitAsignable' AND o.id = OBJECT_ID(N'[dbo].Zulagen'))
BEGIN
	ALTER TABLE [Zulagen] ADD [IsCostUnitAsignable] [bit] NULL DEFAULT 0
	ALTER TABLE [Zulagen] ADD [IsPresenceBonus] [bit] NULL DEFAULT 1
END
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'LayoutSettings' AND o.id = OBJECT_ID(N'[dbo].VorlageDP'))
BEGIN
	ALTER TABLE VorlageDP ADD LayoutSettings Text NULL
END	
go
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PersKom]')  AND name = 'PersNr_Sort_PersKTypID')
	DROP Index PersKom.[PersNr_Sort_PersKTypID]
go
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].PersKom')  AND name = 'IX_PersId_Sort_PersKTypID')
BEGIN
CREATE NONCLUSTERED INDEX IX_PersId_Sort_PersKTypID ON dbo.PersKom
	(PersNr,PersKTypID,Sort) ON [PRIMARY]
	
	UPDATE BesetzungStd SET StdVs = 0 WHERE StdVs IS NULL
	ALTER TABLE BesetzungStd ADD DEFAULT ((0)) FOR StdVs
	ALTER TABLE BesetzungStd ALTER COLUMN StdVs tinyint NOT NULL
END



go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ContentPath' and o.id = OBJECT_ID(N'[dbo].[PlanSort]'))
BEGIN
	ALTER TABLE dbo.PlanSort ADD ContentPath VARCHAR(250)
END								  
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ContentFormat' and o.id = OBJECT_ID(N'[dbo].[PlanSort]'))
BEGIN
	ALTER TABLE dbo.PlanSort ADD ContentFormat VARCHAR(250) 
END								  
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ContentSettings' and o.id = OBJECT_ID(N'[dbo].[PlanSort]'))
BEGIN
	ALTER TABLE dbo.PlanSort ADD ContentSettings TEXT 
END								  
go
IF EXISTS (
	SELECT * FROM sysColumns c
	INNER JOIN sysobjects o on c.id = o.id
	INNER JOIN systypes t on t.xtype = c.xtype 
	WHERE c.name = 'ContentSettings'
	and o.id = OBJECT_ID(N'[dbo].[PlanSort]')
	and not t.name = 'text')
BEGIN
	ALTER TABLE dbo.PlanSort ALTER COLUMN ContentSettings TEXT	
END  
go

UPDATE PlanSort SET PlanSort.ContentFormat = '[Value]', ContentPath = 
CASE 
	WHEN TextID = 113 AND  ZeileAuff = 1 THEN 'subscription' 
	WHEN TextID = 3 AND  ZeileAuff = 1 THEN 'subscription'  
	WHEN TextID = 4 AND  ZeileAuff  = 1 THEN 'subscription'  
	WHEN TextID = 42 AND  ZeileAuff  = 1 THEN 'typeshort'  
	WHEN TextID = 98 AND  ZeileAuff  = 1 THEN 'typelong'  
	WHEN TextID = 10 AND  ZeileAuff  = 1 THEN 'numberInternal'  
	WHEN TextID = 99 AND  ZeileAuff  = 1 THEN 'numberInternal'  
	WHEN TextID = 171 AND  ZeileAuff  = 1 THEN 'numberInternal' 
	WHEN TextID = 176 AND  ZeileAuff  = 1 THEN 'numberExternal' 
	WHEN TextID = 9 AND  ZeileAuff  = 1 THEN 'note' 
	WHEN TextID = 26 AND  ZeileAuff  = 1 THEN 'noteLong' 
	WHEN TextID = 25 AND  ZeileAuff  = 1 THEN 'noteTechnical' 
	WHEN TextID = 61 AND  ZeileAuff  = 1 THEN 'cast' 
	WHEN TextID = 62 AND  ZeileAuff  = 1 THEN 'cast' 
	WHEN TextID = 63 AND  ZeileAuff  = 1 THEN 'cast' 
	WHEN TextID = 60 AND  ZeileAuff  = 1 THEN 'cast'
	WHEN TextID = 153 AND  ZeileAuff  = 1 THEN 'cast'
	WHEN TextID = 152 AND  ZeileAuff  = 1 THEN 'cast'
	WHEN TextID = 111 AND  ZeileAuff  = 1 THEN 'cast'
	WHEN TextID = 112 AND  ZeileAuff  = 1 THEN 'cast'
	WHEN TextID = 54 AND  ZeileAuff  = 1 THEN 'cast'
	WHEN TextID = 70 AND  ZeileAuff  = 1 THEN 'end'
	WHEN TextID = 91 AND  ZeileAuff  = 1 THEN 'stage.rehearsalNo'
	WHEN TextID = 160 AND  ZeileAuff  = 1 THEN 'stage.address'
	WHEN TextID = 161 AND  ZeileAuff  = 1 THEN 'stage.address'
	WHEN TextID = 169 AND  ZeileAuff  = 1 THEN 'stage.eMail'
	WHEN TextID = 168 AND  ZeileAuff  = 1 THEN 'stage.fax'
	WHEN TextID = 167 AND  ZeileAuff  = 1 THEN 'stage.mobil'
	WHEN TextID = 170 AND  ZeileAuff  = 1 THEN 'stage.homepage'
	WHEN TextID = 47 AND  ZeileAuff  = 1 THEN 'stage.nameShort'
	WHEN TextID = 1 AND  ZeileAuff  = 1 THEN 'stage.nameLong'
	WHEN TextID = 166 AND  ZeileAuff  = 1 THEN 'stage.telCom'
	WHEN TextID = 165 AND  ZeileAuff  = 1 THEN 'stage.tel'
	WHEN TextID = 2 AND  ZeileAuff  = 1 THEN 'date'
	WHEN TextID = 38 AND  ZeileAuff  = 1 THEN 'holiday'
	WHEN TextID = 90 AND  ZeileAuff  = 1 THEN 'productionNo'
	WHEN TextID = 89 AND  ZeileAuff  = 1 THEN 'productionNo'
	WHEN TextID = 88 AND  ZeileAuff  = 1 THEN 'anniversary'
	WHEN TextID = 87 AND  ZeileAuff  = 1 THEN 'anniversary'
	WHEN TextID = 12 AND  ZeileAuff  = 1 THEN 'K1'
	WHEN TextID = 14 AND  ZeileAuff  = 1 THEN 'K2'
	WHEN TextID = 16 AND  ZeileAuff  = 1 THEN 'K3'
	WHEN TextID = 18 AND  ZeileAuff  = 1 THEN 'K4'
	WHEN TextID = 115 AND  ZeileAuff  = 1 THEN 'author'
	WHEN TextID = 11 AND  ZeileAuff  = 1 THEN 'L1'
	WHEN TextID = 13 AND  ZeileAuff  = 1 THEN 'L2'
	WHEN TextID = 15 AND  ZeileAuff  = 1 THEN 'L3'
	WHEN TextID = 17 AND  ZeileAuff  = 1 THEN 'L4'
	WHEN TextID = 19 AND  ZeileAuff  = 1 THEN 'L5'
	WHEN TextID = 20 AND  ZeileAuff  = 1 THEN 'L6'
	WHEN TextID = 40 AND  ZeileAuff  = 1 THEN 'titleOrg'
	WHEN TextID = 174 AND  ZeileAuff  = 1 THEN 'SpecialPrice'
	WHEN TextID = 23 AND  ZeileAuff  = 1 THEN 'PriceGroup'
	WHEN TextID = 175 AND  ZeileAuff  = 1 THEN 'PriceGroupSpecial'
	WHEN TextID = 7 AND  ZeileAuff  = 1 THEN 'K5'
	WHEN TextID = 6 AND  ZeileAuff  = 1 THEN 'L7'
	WHEN TextID = 121 AND  ZeileAuff  = 1 THEN 'branch'
	WHEN TextID = 177 AND  ZeileAuff  = 1 THEN 'state'
	WHEN TextID = 49 AND  ZeileAuff  = 1 THEN 'dayCode'
	WHEN TextID = 48 AND  ZeileAuff  = 1 THEN 'dayNote'
	WHEN TextID = 41 AND  ZeileAuff  = 1 THEN 'title'
	WHEN TextID = 173 AND  ZeileAuff  = 1 THEN 'presaleStart'
	WHEN TextID = 172 AND  ZeileAuff  = 1 THEN 'presaleState'
	WHEN TextID = 22 AND  ZeileAuff  = 1 THEN 'start'
	WHEN TextID = 50 AND  ZeileAuff  = 1 THEN 'productionNote'
	WHEN TextID = 120 AND  ZeileAuff  = 1 THEN 'genre'
	WHEN TextID = 8 AND  ZeileAuff  = 1 THEN 'times'
END 
FROM PlanSort 
INNER JOIN  [PlanSpalte] ON PlanSort.SpalteID = PlanSpalte.SpalteID
INNER JOIN  [Plan] ON [PlanSpalte].PlanID = [Plan].PlanID
WHERE ContentPath IS NULL AND ContentFormat IS NULL
go



/****** Object:  StoredProcedure [dbo].[sp_ProductionActivityCount]    Script Date: 02/27/2009 18:33:38 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ProductionActivityCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ProductionActivityCount]
GO

CREATE PROCEDURE [dbo].[sp_ProductionActivityCount]
	@productionId int,
	@date  Datetime, 
	@startTime  Datetime, 
	@seasonStart  Datetime,
	@categoryId 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 = @categoryId AND --Kat = Performance
	(a.[status] Between 0 AND 99) AND
	((a.Datum < @date AND a.Datum >= @seasonStart ) or 
	(a.Datum = @date AND CONVERT(char(5), a.UhrBeg,8) <= CONVERT(char(5), @startTime,8)))
GO
GRANT EXECUTE ON sp_ProductionActivityCount TO Public
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 Status Between 0 AND 99
	  AND Art = @lArt 
	  AND ((Datum < @DDatum  AND Datum>= @dspzStart) 
		  OR  (Datum = @DDatum AND CONVERT(varchar(5), uhrbeg, 8)<= CONVERT(varchar(5), @dvon, 8)))
GO

IF NOT EXISTS (SELECT * FROM Stücke WHERE Snr = -1) 
BEGIN
SET IDENTITY_INSERT Stücke ON
INSERT INTO Stücke (SNr,Titel,Alt,OriginalTitel,[Begin],Dauer,TypID,sparte) VALUES (-1,'#sp#',0,'#sp#','19000101','19000101',0,0)
SET IDENTITY_INSERT Stücke OFF
END

--------------------------------------------------------------------------------------------------------------

IF  EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'[dbo].[GetCurrentPermission]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].GetCurrentPermission
GO
CREATE FUNCTION dbo.GetCurrentPermission(@Group INT, @PermissionFor INT) RETURNS INT
-- Rückgabewerte:
-- Keine Rechte		= 0 
-- Keine Lesen		= 1
-- Keine Schreiben  = 2 
AS
BEGIN
	DECLARE @Right INT 
	SET @Right = 0
	IF (CURRENT_USER = 'dbo') RETURN 2

	SELECT @Right = UserGruppe.Schreiben + 1
	FROM UserGruppe INNER JOIN UserPw ON UserGruppe.UserID = UserPw.UserID
	WHERE	UserPw.UserName			= CURRENT_USER  AND 
			BerechtigungsbereichID	= @PermissionFor AND
			GruppeId				= @Group 
	RETURN @Right
END

go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DeleteRole'))
BEGIN
	DROP PROCEDURE dbo.DeleteRole
END
go
CREATE PROCEDURE [dbo].[DeleteRole] 
	@RoleId INT
AS
BEGIN
SET NOCOUNT ON

DECLARE @UserGroup int

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

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

			END
		END
END

go
GRANT EXECUTE ON GetCurrentPermission TO Public


/****** Object:  Table [dbo].[DayNoteCategories]    Script Date: 03/12/2009 18:14:51 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects o WHERE o.id = OBJECT_ID(N'[dbo].[DayNoteCategories]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[DayNoteCategories](
		[DayNoteCategoryId] [int] IDENTITY(1,1) NOT NULL,
		[DepartmentId] [int] NOT NULL,
		[Name] [varchar](20) NOT NULL,
		[Sort] [int] NULL CONSTRAINT [DF_DayNoteCategories_Sort] DEFAULT (0),
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		CONSTRAINT [PK_DayNoteCategories] PRIMARY KEY CLUSTERED (
			[DayNoteCategoryId] ASC
		) ON [PRIMARY],
		CONSTRAINT [FK_DayNoteCategories_DienstplanArtenTabelle] FOREIGN KEY ([DepartmentId])
		REFERENCES [dbo].[DienstplanArtenTabelle] ([DienstplanArtenID])
		ON DELETE CASCADE		
	) ON [PRIMARY]
END
GO

GRANT SELECT ON [dbo].[DayNoteCategories] TO Public
GRANT DELETE ON [dbo].[DayNoteCategories] TO Public
GRANT INSERT ON [dbo].[DayNoteCategories] TO Public
GRANT UPDATE ON [dbo].[DayNoteCategories] TO Public
GO

/****** Object:  Table [dbo].[DayNotes]    Script Date: 03/12/2009 18:29:22 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects o WHERE o.id = OBJECT_ID(N'[dbo].[DayNotes]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[DayNotes](
		[DayNoteId] [int] IDENTITY(1,1) NOT NULL,
		[DayNoteCategoryId] [int] NOT NULL,
		[Day] [datetime] NOT NULL,
		[Note] [varchar](50) NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		CONSTRAINT [PK_DayNotes] PRIMARY KEY CLUSTERED (
			[DayNoteId] ASC
		) ON [PRIMARY],
		CONSTRAINT [FK_DayNotes_DayNoteCategories] FOREIGN KEY ([DayNoteCategoryId])
		REFERENCES [dbo].[DayNoteCategories] ([DayNoteCategoryId])
		ON DELETE CASCADE		
	) ON [PRIMARY]
END
GO

GRANT SELECT ON [dbo].[DayNotes] TO Public
GRANT DELETE ON [dbo].[DayNotes] TO Public
GRANT INSERT ON [dbo].[DayNotes] TO Public
GRANT UPDATE ON [dbo].[DayNotes] TO Public
GO


IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].RoleQualifications_Update'))
BEGIN
	DROP VIEW RoleQualifications_Update
END
go
CREATE VIEW [dbo].[RoleQualifications_Update] 
	AS
SELECT BesRepertoire.* FROM BesRepertoire WHERE BesRepertoire.RolleID IN 
(
	SELECT   BesetzungStd.ID
	FROM     BesetzungStd  WHERE Besitzer IN (SELECT UserGruppe.GruppeID
						FROM UserGruppe INNER JOIN UserPw ON UserGruppe.UserID = UserPw.UserID
						WHERE Schreiben = 1 AND UserPw.UserName = CURRENT_USER  AND BerechtigungsbereichID = 4) 
							
	OR CURRENT_USER = 'dbo'
)
WITH CHECK OPTION
--CREATE VIEW [dbo].RoleQualifications_Update 
--	AS
--SELECT BesRepertoire.* FROM BesRepertoire WHERE BesRepertoire.RolleID IN 
--(
--	SELECT   BesetzungStd.ID
--	FROM     BesetzungStd 
--		INNER JOIN (SELECT DISTINCT UserGruppe.GruppeID, UserGruppe.Schreiben
--						FROM UserGruppe 
--							INNER JOIN UserPw ON UserGruppe.UserID = UserPw.UserID
--						WHERE UserPw.UserName = CURRENT_USER  AND BerechtigungsbereichID = 4) AS UG 
--							ON ISNULL(BesetzungStd.Besitzer,1) = UG.GruppeID
--	WHERE UG.Schreiben = 1 OR CURRENT_USER = 'dbo'
--)
--WITH CHECK OPTION
GO
GRANT SELECT ON [dbo].[RoleQualifications_Update] TO Public
GRANT DELETE ON [dbo].[RoleQualifications_Update] TO Public
GRANT INSERT ON [dbo].[RoleQualifications_Update] TO Public
GRANT UPDATE ON [dbo].[RoleQualifications_Update] TO Public
go


IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'proVst' AND o.id = OBJECT_ID(N'[dbo].Kosten') AND c.xtype <> 56)
BEGIN	
	ALTER TABLE Kosten ALTER COLUMN proVst INT NOT NULL
	ALTER TABLE Kosten ADD DEFAULT (0) FOR proVst
	Print 'WertText geändert'
END

go

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'SalaryLevelId' and o.id = OBJECT_ID(N'[dbo].VertragRolle'))
BEGIN
	ALTER TABLE VertragRolle ADD SalaryLevelId INT NULL 
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SalaryLevel]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SalaryLevel](
		SalaryLevelId INT IDENTITY(1,1) NOT NULL,
		SalaryLevelShortName varchar(10) NOT NULL,
		SalaryLevelName varchar(50) NULL,
		ManagementDomainNo varchar(20) NULL,
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
	 CONSTRAINT [PK_SalaryLevel] PRIMARY KEY CLUSTERED  (SalaryLevelId ASC) ON [PRIMARY]
	-- CONSTRAINT [FK_SalaryLevel_Contract] FOREIGN KEY([SalaryLevelId]) REFERENCES [dbo].[VertragRolle] ([SalaryLevelId]) --ON DELETE CASCADE
	) ON [PRIMARY]
END	

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractRole_SalaryLevel]') AND type = 'F')
ALTER TABLE [dbo].[VertragRolle] WITH NOCHECK ADD  CONSTRAINT FK_ContractRole_SalaryLevel FOREIGN KEY([SalaryLevelId])
REFERENCES [dbo].[SalaryLevel] ([SalaryLevelId])
GO
ALTER TABLE [dbo].[VertragRolle] CHECK CONSTRAINT [FK_ContractRole_SalaryLevel]


GRANT SELECT ON [dbo].SalaryLevel TO Public
GRANT DELETE ON [dbo].SalaryLevel TO PersoContractWrite
GRANT INSERT ON [dbo].SalaryLevel TO PersoContractWrite
GRANT UPDATE ON [dbo].SalaryLevel TO PersoContractWrite


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SalaryLevelData]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SalaryLevelData](
		SalaryLevelDataId INT IDENTITY(1,1) NOT NULL,
		SalaryLevelId INT NOT NULL,
		ValidFrom datetime NOT NULL,
		ValidTo datetime NOT NULL,
		HourlyRate real NOT NULL DEFAULT (0),
		DailyRate real NOT NULL DEFAULT (0),
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
	 CONSTRAINT [PK_SalaryLevelData] PRIMARY KEY CLUSTERED  (SalaryLevelDataId ASC) ON [PRIMARY],
	 CONSTRAINT [FK_SalaryLevelData_SalaryLevel] FOREIGN KEY([SalaryLevelId]) REFERENCES [dbo].SalaryLevel ([SalaryLevelId]) ON DELETE CASCADE
	) ON [PRIMARY]
END	
 	
GRANT SELECT ON [dbo].[SalaryLevelData] TO Public
GRANT DELETE ON [dbo].[SalaryLevelData] TO PersoContractWrite
GRANT INSERT ON [dbo].[SalaryLevelData] TO PersoContractWrite
GRANT UPDATE ON [dbo].[SalaryLevelData] TO PersoContractWrite

go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Module' and o.id = OBJECT_ID(N'[dbo].Vorlagen'))
BEGIN
	ALTER TABLE Vorlagen ADD Module INT NOT NULL DEFAULT (0)
END
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ExportClass' and o.id = OBJECT_ID(N'[dbo].PlanExport'))
BEGIN
	ALTER TABLE PlanExport ADD ExportClass VARCHAR(200)
	exec ('UPDATE PlanExport SET ExportClass = ''Theasoft flex v1.0''')  
END

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Pause3AfterMinutes' and o.id = OBJECT_ID(N'[dbo].PersoParameter'))
BEGIN
	ALTER TABLE PersoParameter ADD Pause3AfterMinutes INT NOT NULL Default(0)
	ALTER TABLE PersoParameter ADD Pause3DurationMinutes INT NOT NULL Default(0)
END

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ExportPeriodStart' and o.id = OBJECT_ID(N'[dbo].PlanExport'))
BEGIN
	ALTER TABLE PlanExport ADD ExportPeriodStart DATETIME NULL
	ALTER TABLE PlanExport ADD ExportPeriodEnd DATETIME NULL
	EXEC('UPDATE PlanExport
		  SET ExportPeriodStart=p.von, ExportPeriodEnd=p.bis
		  FROM PlanExport AS pe INNER JOIN [Plan] AS p ON pe.PlanExportID = p.PlanExportID
		  WHERE Bem = ''Theasoft.DataClasses.Dispo.ts_DataAuff''')		
END	

go

GRANT SELECT ON [dbo].[Status]   TO Public
GRANT SELECT ON [dbo].[BesetzungTabelle]   TO [Spielplan alles lesen]
GRANT SELECT ON [dbo].[BesetzungTabelle]   TO [Spielplan ändern]
go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[ActivityType_Update]'))
BEGIN
	DROP VIEW [dbo].[ActivityType_Update]
END
go
CREATE VIEW [dbo].[ActivityType_Update]
AS
SELECT a.*
	FROM AuffTypen AS a
	WHERE EXISTS  
		(SELECT g.Modul FROM  Gruppe AS g 
			INNER JOIN UserGruppe AS ug ON g.GruppeID = ug.GruppeID
			INNER JOIN UserPw AS u ON ug.UserID = u.UserID
			
			WHERE ModulGruppeIDWrite & g.Modul = g.Modul and ug.BerechtigungsbereichID = 2 AND u.UserName = CURRENT_USER
		)
		OR 	(SELECT PERMISSIONS(OBJECT_ID('Aufführg'))&2) = 2
		OR  ModulGruppeIDWrite = 0
WITH CHECK OPTION
go

GRANT SELECT ON [dbo].[ActivityType_Update]   TO Public
GRANT DELETE ON [dbo].[ActivityType_Update]   TO [Stammdaten ändern]
GRANT INSERT ON [dbo].[ActivityType_Update]   TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].[ActivityType_Update]   TO [Stammdaten ändern]

GRANT DELETE ON [dbo].[ActivityType_Update]   TO [PersoBasicDataWrite]
GRANT INSERT ON [dbo].[ActivityType_Update]   TO [PersoBasicDataWrite]
GRANT UPDATE ON [dbo].[ActivityType_Update]   TO [PersoBasicDataWrite]

GRANT DELETE ON [dbo].[ActivityType_Update]   TO [PersoAdmin]
GRANT INSERT ON [dbo].[ActivityType_Update]   TO [PersoAdmin]
GRANT UPDATE ON [dbo].[ActivityType_Update]   TO [PersoAdmin]
go

-- 02.04.2009 PlanSpalte bekommt eine neue Spalte für XML-ZusatzSpalten
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ColumnSettings' and o.id = OBJECT_ID(N'[dbo].PlanSpalte'))
BEGIN
	ALTER TABLE PlanSpalte ADD ColumnSettings TEXT 
END	

-- 22.04.2009 RapportSpalte bekommt eine neue Spalte für einen WageType
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'WageTypeId' and o.id = OBJECT_ID(N'[dbo].RapportSpalte'))
BEGIN
	ALTER TABLE RapportSpalte ADD WageTypeId INT
	ALTER TABLE RapportSpalte WITH CHECK ADD  CONSTRAINT FK_RapportSpalte_WageType FOREIGN KEY(WageTypeId)
	REFERENCES WageType (WageTypeId)
	ALTER TABLE WageType ADD InfoType VARCHAR(10)
END	
-- 30.04.2009 Typ bekommt eine neue Spalte für die Format-Settings
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'FormatSettings' and o.id = OBJECT_ID(N'[dbo].Typ'))
BEGIN
	ALTER TABLE Typ ADD FormatSettings TEXT
END	
-- 13.05.2009 Neues Stück für Tagesaufgaben
IF NOT EXISTS (SELECT * FROM Stücke WHERE Snr = -2) 
BEGIN
	SET IDENTITY_INSERT Stücke ON
	INSERT INTO Stücke (SNr,Titel,Alt,OriginalTitel,[Begin],Dauer,TypID,Sparte) VALUES (-2,'#DAILYTASK#',0,'#DAILYTASK#','19000101','19000101',0,0)
	SET IDENTITY_INSERT Stücke OFF
END
IF NOT EXISTS (SELECT * FROM StückeTeil WHERE StückeTeil.Snr = -2)
BEGIN
	INSERT INTO StückeTeil (Snr, SnrTeil) VALUES (-2, -2)
END
-- 18.05.2009 Neuer ActivityType bzw. AuffTyp
IF NOT EXISTS (SELECT * FROM AuffTypen WHERE AuffTNr = -1)
BEGIN
	SET IDENTITY_INSERT AuffTypen ON
	INSERT INTO AuffTypen (AuffTNr, KatNr, ModulGruppeIDWrite) VALUES(-1, 99, 4)
	SET IDENTITY_INSERT AuffTypen OFF
END
-- 20.05.2009 Neue Spalte für IsTimeSpan in der Tabelle AufführgTabelle
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsTimeSpan' and o.id = OBJECT_ID(N'[dbo].AufführgTabelle'))
BEGIN
	ALTER TABLE AufführgTabelle ADD IsTimeSpan BIT DEFAULT 0
END	
-- 22.05.2009 Neue Spalte für IsTimeSpan in der Tabelle AufführgTabelle
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IntendedDuration' and o.id = OBJECT_ID(N'[dbo].AuffTechAufgabe'))
BEGIN
	ALTER TABLE AuffTechAufgabe ADD IntendedDuration INT
END	
-- 28.05.2009 Neue Spalte für 4Zeichen Kürzel in Ab-Groupe
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ShortName' and o.id = OBJECT_ID(N'[dbo].ABGruppe'))
BEGIN
	ALTER TABLE ABGruppe ADD ShortName VARCHAR(6) NULL
END	

go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IncomeBestCase' and o.id = OBJECT_ID(N'[dbo].AufführgDetails'))
BEGIN
	ALTER TABLE AufführgDetails ADD IncomeBestCase MONEY NULL
END	

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IncomeWorstCase' and o.id = OBJECT_ID(N'[dbo].AufführgDetails'))
BEGIN
	ALTER TABLE AufführgDetails ADD IncomeWorstCase MONEY NULL
END	

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IncomeMax' and o.id = OBJECT_ID(N'[dbo].Preise'))
BEGIN
	ALTER TABLE Preise ADD IncomeMax MONEY NOT NULL DEFAULT(0)
END	
-- 28.05.2009 - Executerechte für DeleteRole setzen
GRANT EXECUTE ON DeleteRole TO Public

-- 03.04.2009 - Beim Besetzen wird ggf. das Repertoire der PErson ergänzt
GRANT INSERT ON [dbo].[BesRepertoire]   TO [Spielplan ändern]

--10.06.2009 - Covergage hinzufügen
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CoverFee' and o.id = OBJECT_ID(N'[dbo].VertragRolle'))
BEGIN
	ALTER TABLE VertragRolle ADD CoverFee MONEY NOT NULL DEFAULT(0)
END	
go
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Besbem' AND o.id = OBJECT_ID(N'[dbo].xhdelBesetzung') AND c.prec < 50)
BEGIN
	ALTER TABLE xhdelBesetzung ALTER COLUMN Besbem VARCHAR(50)
	Print 'WertText geändert'
END

-- 2009-06-16
-- TemplateId in Plan
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TemplateId' AND o.id = OBJECT_ID(N'[dbo].Plan'))
BEGIN
	ALTER TABLE [Plan] ADD [TemplateId] INT NULL
END

-- TemplateId in Vertragsvorlagen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TemplateId' AND o.id = OBJECT_ID(N'[dbo].VertragsVorlagen'))
BEGIN
	ALTER TABLE [VertragsVorlagen] ADD [TemplateId] INT NULL
END

-- 2009-06-18
-- neue Felder für Kassenanordnung
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ContractNote' AND o.id = OBJECT_ID(N'[dbo].CashCommand'))
BEGIN
	ALTER TABLE [CashCommand] ADD [ContractNote] VARCHAR(120)
	ALTER TABLE [CashCommand] ADD [NoteForAccounting] VARCHAR(120)
	ALTER TABLE [CashCommand] ADD [BookingYear] INT
END

-- 2009-06-24
-- Löschweitergabe für VertragsBesetzungsHonorar
IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_VertragsBesetzungsHonorar_VertragRolle]') AND type = 'F')
ALTER TABLE [VertragsBesetzungsHonorar] DROP CONSTRAINT [FK_VertragsBesetzungsHonorar_VertragRolle]
GO

ALTER TABLE [VertragsBesetzungsHonorar]  WITH CHECK ADD  CONSTRAINT [FK_VertragsBesetzungsHonorar_VertragRolle] FOREIGN KEY([VRID])
REFERENCES [VertragRolle] ([VRID])
ON DELETE CASCADE
GO

ALTER TABLE [VertragsBesetzungsHonorar] CHECK CONSTRAINT [FK_VertragsBesetzungsHonorar_VertragRolle]
GO



IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DeleteActivityRelations'))
BEGIN
	DROP PROCEDURE dbo.DeleteActivityRelations
END
go
CREATE PROCEDURE dbo.DeleteActivityRelations 
	@ActivityId INT
AS
BEGIN
SET NOCOUNT ON
	IF EXISTS (SELECT * FROM ActivitiesUpdate WHERE AuffNr= @ActivityId)
	BEGIN
		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)
		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
		UPDATE AufführgTabelle SET ZuAuffNr = NULL WHERE ZuAuffNr = @ActivityId
	END	
END	
go
GRANT EXECUTE ON DeleteActivityRelations TO public
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsInactive' AND o.id = OBJECT_ID(N'[dbo].UserPw'))
BEGIN
	ALTER TABLE [UserPw] ADD [IsInactive] BIT NOT NULL DEFAULT(0)
END

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

CREATE PROCEDURE dbo.AllocateFee
	@Start DATETIME,
	@End DATETIME,
	@WithReheral BIT
	AS
	BEGIN
		SET NOCOUNT ON;
		--Honorare von stornierten Verträgen entfernen
		DELETE FROM VertragsBesetzungsHonorar WHERE VRID in (
			SELECT vr.VRID FROM AbVertragRolle vr INNER JOIN Vertrag v ON v.VertragsNr = vr.VertragsNr
			WHERE v.IsCanceled = 1)
		
		
		--Honorare die nicht in den Vertragszeitraum fallen löschen
		DELETE FROM VertragsBesetzungsHonorar WHERE id in (
		SELECT vbh.ID
		FROM		   VertragRolle			AS vr
			INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
			INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
			INNER JOIN BesetzungTabelle		AS b	ON vr.Rolleid = b.Rolleid AND v.PersNr=b.persnr
			INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr
			INNER JOIN Aufftypen			AS at	ON a.art = at.AufftNr
			INNER JOIN VertragsBesetzungsHonorar AS vbh ON b.ID = vbh.BesID  AND vbh.VRID = vr.VRID --ergänzt and  vrid
		WHERE 
			vv.Vart = 0
			AND at.KatNr=0
			AND a.Status BETWEEN 0 AND 99
			AND vr.AbrechnungVs = 0
			AND (a.Datum < ISNULL(vr.vrVon, v.vvon) OR a.Datum > ISNULL(vr.vrbis, v.vbis))
			AND vbh.KostenArt = 0)
		
		
		--Rollengagen pro Vst updaten
		UPDATE VertragsBesetzungsHonorar SET Betrag = CASE WHEN b.IsCover=1 THEN vr.CoverFee ELSE ISNULL(vr.Honorar,0) END
		FROM		   VertragRolle			AS vr
			INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
			INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
			INNER JOIN BesetzungTabelle		AS b	ON vr.Rolleid = b.Rolleid AND v.PersNr=b.persnr
			INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr
			INNER JOIN Aufftypen			AS at	ON a.art = at.AufftNr
			INNER JOIN VertragsBesetzungsHonorar AS vbh ON b.ID = vbh.BesID  AND vbh.VRID = vr.VRID --ergänzt and  vrid
		WHERE 
			vv.Vart = 0
			AND at.KatNr = 0
			AND a.Status BETWEEN 0 AND 99
			AND vr.AbrechnungVs = 0
			AND a.Datum BETWEEN  @Start AND @End 
			AND (a.Datum >= vr.vrvon OR vr.vrvon IS NULL) AND (a.Datum >= v.vvon OR v.vvon IS NULL)
			AND (a.Datum <= vr.vrbis OR vr.vrbis IS NULL) AND (a.Datum <= v.vbis OR v.vbis IS NULL)
			AND vbh.KostenArt = 0
			AND b.IsCanceled = 0
			AND v.IsCanceled = 0
			AND ISNULL(vbh.Betrag,0) <> CASE WHEN b.IsCover=1 THEN vr.CoverFee ELSE ISNULL(vr.Honorar,0) END
		
		-- Rollengagen pro Vst Insert NO COVER
		INSERT INTO VertragsBesetzungsHonorar (BesID,VRID,Betrag,KostenArt)
		SELECT  b.ID, MIN(vr.vrid), MIN(ISNULL(vr.Honorar,0)), 0
		FROM		   VertragRolle			AS vr
			INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
			INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
			INNER JOIN BesetzungTabelle		AS b	ON vr.Rolleid = b.Rolleid AND v.PersNr=b.persnr
			INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr
			INNER JOIN Aufftypen			AS at	ON a.art = at.AufftNr
			LEFT JOIN VertragsBesetzungsHonorar AS vbh ON b.ID = vbh.BesID
		WHERE 
			vv.Vart = 0
			AND at.KatNr=0
			AND a.Status BETWEEN 0 AND 99
			AND vr.AbrechnungVs = 0
			AND a.Datum BETWEEN  @Start AND @End 
			AND (a.Datum >= vr.vrvon OR vr.vrvon IS NULL) AND (a.Datum >= v.vvon OR v.vvon IS NULL)
			AND (a.Datum <= vr.vrbis OR vr.vrbis IS NULL) AND (a.Datum <= v.vbis OR v.vbis IS NULL)
			AND vbh.id IS NULL
			AND b.IsCanceled = 0
			AND v.IsCanceled = 0
			AND b.IsCover = 0
			GROUP BY  b.ID 
			
			-- Rollengagen pro Vst Insert
		INSERT INTO VertragsBesetzungsHonorar (BesID,VRID,Betrag,KostenArt)
		SELECT  b.ID, MIN(vr.vrid), MIN(ISNULL(vr.CoverFee,0)), 0
		FROM		   VertragRolle			AS vr
			INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
			INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
			INNER JOIN BesetzungTabelle		AS b	ON vr.Rolleid = b.Rolleid AND v.PersNr=b.persnr
			INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr
			INNER JOIN Aufftypen			AS at	ON a.art = at.AufftNr
			LEFT JOIN VertragsBesetzungsHonorar AS vbh ON b.ID = vbh.BesID
		WHERE 
			vv.Vart = 0
			AND at.KatNr = 0
			AND a.Status BETWEEN 0 AND 99
			AND vr.AbrechnungVs = 0
			AND a.Datum BETWEEN  @Start AND @End 
			AND (a.Datum >= vr.vrvon OR vr.vrvon IS NULL) AND (a.Datum >= v.vvon OR v.vvon IS NULL)
			AND (a.Datum <= vr.vrbis OR vr.vrbis IS NULL) AND (a.Datum <= v.vbis OR v.vbis IS NULL)
			AND vbh.id IS NULL
			AND b.IsCanceled = 0
			AND v.IsCanceled = 0
			AND b.IsCover = 1
			GROUP BY  b.ID 
			--Wenn mehrere Rollengagen vornaden sind keine zuordnund
			--HAVING COUNT(*) = 1
			
		--Spielzeitgagen pro Vst Update 
		--wenn keine Rollengage vorhanden ist
			
			UPDATE VertragsBesetzungsHonorar SET Betrag = CASE WHEN b.IsCover=1 THEN vr.CoverFee ELSE ISNULL(vr.Honorar,0) END
		FROM		   VertragRolle			AS vr
			INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
			INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
			INNER JOIN BesetzungTabelle		AS b	ON vr.Rolleid = 0 AND v.PersNr=b.persnr
			INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr
			INNER JOIN Aufftypen			AS at	ON a.art = at.AufftNr
			INNER JOIN VertragsBesetzungsHonorar AS vbh ON b.ID = vbh.BesID AND vbh.VRID = vr.VRID --ergänzt and  vrid
		WHERE 
			vv.Vart = 0
			AND at.KatNr = 0
			AND a.Status BETWEEN 0 AND 99
			AND vr.AbrechnungVs = 0
			AND a.Datum BETWEEN  @Start AND @End 
			AND (a.Datum >= vr.vrvon OR vr.vrvon IS NULL) AND (a.Datum >= v.vvon OR v.vvon IS NULL)
			AND (a.Datum <= vr.vrbis OR vr.vrbis IS NULL) AND (a.Datum <= v.vbis OR v.vbis IS NULL)
			AND vbh.KostenArt = 0
			AND b.IsCanceled = 0
			AND v.IsCanceled = 0
			AND ISNULL(vbh.Betrag,0) <> CASE WHEN b.IsCover=1 THEN vr.CoverFee ELSE ISNULL(vr.Honorar,0) END
			AND b.id NOT IN 
			(
				SELECT  b.ID
				FROM		   VertragRolle			AS vr
					INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
					INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
					INNER JOIN BesetzungTabelle		AS b	ON vr.Rolleid = b.Rolleid AND v.PersNr=b.persnr
					INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr
					INNER JOIN Aufftypen			AS at	ON a.art = at.AufftNr
				WHERE 
					vv.Vart = 0
					AND at.KatNr = 0
					AND a.Status Between 0 AND 99
					AND vr.AbrechnungVs = 0
					AND a.Datum BETWEEN  @Start AND @End 
					AND (a.Datum >= vr.vrvon OR vr.vrvon IS NULL) AND (a.Datum >= v.vvon OR v.vvon IS NULL)
					AND (a.Datum <= vr.vrbis OR vr.vrbis IS NULL) AND (a.Datum <= v.vbis OR v.vbis IS NULL)
					AND b.IsCanceled = 0
					AND v.IsCanceled = 0
			)
			
		--Spielzeitgagen pro Vst Insert NO COVER
		--wenn keine Rollengage vorhanden ist
		INSERT INTO VertragsBesetzungsHonorar (BesID,VRID,Betrag,KostenArt)
		SELECT  b.ID, MIN(vr.vrid), MIN(ISNULL(vr.Honorar,0)), 0
		FROM	VertragRolle					AS vr
			INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
			INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
			INNER JOIN BesetzungTabelle		AS b	ON vr.Rolleid = 0 AND v.PersNr=b.persnr
			INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr
			INNER JOIN Aufftypen			AS at	ON a.art = at.AufftNr
			LEFT JOIN VertragsBesetzungsHonorar AS vbh ON b.ID = vbh.BesID
		WHERE 
			vv.Vart = 0
			AND at.KatNr = 0
			AND a.Status BETWEEN 0 AND 99
			AND vr.AbrechnungVs = 0
			AND a.Datum BETWEEN  @Start AND @End 
			AND (a.Datum >= vr.vrvon OR vr.vrvon IS NULL) AND (a.Datum >= v.vvon OR v.vvon IS NULL)
			AND (a.Datum <= vr.vrbis OR vr.vrbis IS NULL) AND (a.Datum <= v.vbis OR v.vbis IS NULL)
			AND vbh.id IS NULL
			AND b.IsCanceled = 0
			AND v.IsCanceled = 0
			AND b.IsCover = 0
			GROUP BY  b.ID
			--Wenn mehrere Spielzeitgagen vorhanden, sind keine zuordnund
			HAVING COUNT(*) = 1
			AND b.id NOT IN 
			(
				SELECT  b.ID
				FROM		   VertragRolle			AS vr
					INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
					INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
					INNER JOIN BesetzungTabelle		AS b	ON vr.Rolleid = b.Rolleid AND v.PersNr=b.persnr
					INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr
					INNER JOIN Aufftypen			AS at	ON a.art = at.AufftNr
				WHERE 
					vv.Vart = 0
					AND at.KatNr = 0
					AND a.Status BETWEEN 0 AND 99
					AND vr.AbrechnungVs = 0
					AND a.Datum BETWEEN  @Start AND @End 
					AND (a.Datum >= vr.vrvon OR vr.vrvon IS NULL) AND (a.Datum >= v.vvon OR v.vvon IS NULL)
					AND (a.Datum <= vr.vrbis OR vr.vrbis IS NULL) AND (a.Datum <= v.vbis OR v.vbis IS NULL)
					AND b.IsCanceled = 0
					AND v.IsCanceled = 0
			)
			--Spielzeitgagen pro Vst Insert COVER
		--wenn keine Rollengage vorhanden ist
		INSERT INTO VertragsBesetzungsHonorar (BesID,VRID,Betrag,KostenArt)
		SELECT  b.ID, MIN(vr.vrid), MIN(vr.CoverFee), 0
		FROM	VertragRolle					AS vr
			INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
			INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
			INNER JOIN BesetzungTabelle		AS b	ON vr.Rolleid = 0 AND v.PersNr=b.persnr
			INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr
			INNER JOIN Aufftypen			AS at	ON a.art = at.AufftNr
			LEFT JOIN VertragsBesetzungsHonorar AS vbh ON b.ID = vbh.BesID
		WHERE 
			vv.Vart = 0
			AND at.KatNr = 0
			AND a.Status BETWEEN 0 AND 99
			AND vr.AbrechnungVs = 0
			AND a.Datum BETWEEN  @Start AND @End 
			AND (a.Datum >= vr.vrvon OR vr.vrvon IS NULL) AND (a.Datum >= v.vvon OR v.vvon IS NULL)
			AND (a.Datum <= vr.vrbis OR vr.vrbis IS NULL) AND (a.Datum <= v.vbis OR v.vbis IS NULL)
			AND vbh.id IS NULL
			AND b.IsCanceled=0
			AND v.IsCanceled=0
			AND b.IsCover=1
			GROUP BY  b.ID
			--Wenn mehrere Spielzeitgagen vornaden sind keine zuordnund
			HAVING COUNT(*) = 1
			AND b.id NOT IN 
			(
				SELECT  b.ID
				FROM		   VertragRolle			AS vr
					INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
					INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
					INNER JOIN BesetzungTabelle		AS b	ON vr.Rolleid = b.Rolleid AND v.PersNr=b.persnr
					INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr
					INNER JOIN Aufftypen			AS at	ON a.art = at.AufftNr
				WHERE 
					vv.Vart = 0
					AND at.KatNr = 0
					AND a.Status BETWEEN 0 AND 99
					AND vr.AbrechnungVs = 0
					AND a.Datum BETWEEN  @Start AND @End 
					AND (a.Datum >= vr.vrvon OR vr.vrvon IS NULL) AND (a.Datum >= v.vvon OR v.vvon IS NULL)
					AND (a.Datum <= vr.vrbis OR vr.vrbis IS NULL) AND (a.Datum <= v.vbis OR v.vbis IS NULL)
					AND b.IsCanceled = 0
					AND v.IsCanceled  =0
			)
			
	END		
GO
GRANT EXECUTE ON AllocateFee TO Public
go
--2008 06 26 Arbeitsgruppe
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CopyShiftFromContractId' AND o.id = OBJECT_ID(N'[dbo].VertragPerso'))
BEGIN
	ALTER TABLE [VertragPerso] ADD [CopyShiftFromContractId] INT NULL 
END
go
UPDATE BesetzungStd SET Besitzer=1 WHERE Besitzer IS NULL  OR Besitzer = 0
go



go

IF NOT EXISTS (SELECT * FROM UserGruppe WHERE BerechtigungsbereichID=5)
BEGIN
-- Für jede Abteilung eine Berechtigungsgruppe anlegen
	SET IDENTITY_INSERT Gruppe ON 
	INSERT  INTO Gruppe (GruppeId, GruppeBez, Sort, Modul) 
			SELECT DienstplanArtenId+200, DienstplanBez, DienstplanArtenId%100000, 4 
			FROM DienstplanArtenTabelle WHERE DienstplanArtenID > 0 AND ModulGruppeID = 200
			
	SET IDENTITY_INSERT Gruppe OFF 	
	
	--Gruppe der Abteilung zuordnen	
	UPDATE DienstplanArtenTabelle SET ModulGruppeID = DienstplanArtenId+200 WHERE DienstplanArtenId > 0	 AND ModulGruppeID = 200
	
	--Besitzer der PersH nach Vertrag umschreiben
	UPDATE PersH SET Besitzer = AB.DienstplanArtenID+200 
		FROM AB 
			INNER JOIN VertragPerso AS vp ON AB.ABId=vp.ABId
			INNER JOIN Vertrag		AS v  ON vp.VertragsNr=v.VertragsNr
			INNER JOIN PersH		AS p  ON v.PersNr=p.PersNr
			INNER JOIN Gruppe		AS g  ON  AB.DienstplanArtenID+200 = g.GruppeID	
		WHERE p.Besitzer=200 AND v.ModulGruppeID=200
		
	--Besitzer der Verträge umschreiben 
	UPDATE Vertrag SET ModulGruppeID = AB.DienstplanArtenID+200 
		FROM AB 
			INNER JOIN VertragPerso AS vp ON AB.ABId=vp.ABId
			INNER JOIN Vertrag		AS v  ON vp.VertragsNr=v.VertragsNr
			INNER JOIN PersH		AS p  ON v.PersNr=p.PersNr
			INNER JOIN Gruppe		AS g  ON  AB.DienstplanArtenID+200 = g.GruppeID	
		WHERE v.ModulGruppeID=200 		
		
	-- Berechtigung zu schreiben der Dienstpläne erstellen	
	--INSERT INTO UserGruppe (GruppeId, UserID, BerechtigungsbereichID, Schreiben, OptionsFlag, lm, um, lc, uc)
	--	SELECT	DienstplanArtenID+200, u.UserID, 5, u.Schreiben, ISNULL(u.Auswerten,0), u.lm, u.um, u.lc, u.uc  FROM DienstplanUser as u inner join Gruppe as g on u.DienstplanArtenID+200=g.GruppeID
		
		-- Berechtigung für die Vertragsdaten aus Gruppe "Perso" übernehmen (nur Schreibrechte)
	INSERT INTO UserGruppe (GruppeId, UserID, BerechtigungsbereichID, Schreiben, lm, um, lc, uc)
			SELECT gg.GruppeId, UserID, UserGruppe.BerechtigungsbereichId ,UserGruppe.Schreiben ,lm, um, lc, uc  
			FROM UserGruppe,(SELECT GruppeId FROM Gruppe WHERE Modul = 4 AND  GruppeId <> 200) as gg
			WHERE Schreiben = 1 AND UserGruppe.GruppeId = 200 AND BerechtigungsbereichId = 1
			
	-- Berechtigung für die Kontaktdaten aus Gruppe "Perso" übernehmen 
	INSERT INTO UserGruppe (GruppeId, UserID, BerechtigungsbereichID, Schreiben, lm, um, lc, uc)
			SELECT gg.GruppeId, UserID, UserGruppe.BerechtigungsbereichId ,UserGruppe.Schreiben ,lm, um, lc, uc  
			FROM UserGruppe,(SELECT GruppeId FROM Gruppe WHERE Modul = 4 AND  GruppeId <> 200) as gg
			WHERE UserGruppe.GruppeId = 200 AND BerechtigungsbereichId = 0
			
		UPDATE UserGruppe SET OptionsFlag = 1 WHERE UserGruppe.UserGruppeID IN (
			SELECT  Kontakt.UserGruppeID
			FROM UserGruppe as geheim INNER JOIN UserGruppe AS Kontakt ON geheim.UserID =  Kontakt.UserID AND geheim.GruppeID=Kontakt.GruppeID
			WHERE geheim.BerechtigungsbereichId = 3 AND Kontakt.BerechtigungsbereichID = 0
			)
			
				
END


go
--IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
--	WHERE c.name = 'DayScheduleFixedSectionId' and o.id = OBJECT_ID(N'[dbo].AuffTypen'))
--BEGIN
--	ALTER TABLE AuffTypen ADD "DayScheduleFixedSectionId" INT NOT NULL DEFAULT (0) 
--END	

-- 2009-07-13
-- Neue Spalten für CashCommand
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AgencyFee' AND o.id = OBJECT_ID(N'[dbo].CashCommand'))
BEGIN
	ALTER TABLE [CashCommand] ADD [AgencyFee] REAL NOT NULL CONSTRAINT [DF_CashCommand_AgencyFee] DEFAULT (0.0)
	ALTER TABLE [CashCommand] ADD [BillingPeriodStart] DATETIME NULL
	ALTER TABLE [CashCommand] ADD [BillingPeriodEnd]  DATETIME NULL	
END
go
-- BillingPeriod setzen für bestehnde Daten
UPDATE CashCommand SET BillingPeriodStart = sub.periodstart, BillingPeriodEnd = sub.periodend
FROM CashCommand INNER JOIN (
	SELECT Min(A.datum) AS periodstart
		, MAX(a.datum) AS periodend
		, cc.CashCommandId AS id
	FROM CashCommand AS cc 
	INNER JOIN CashCommandPos AS cp ON cc.CashCommandId = cp.CashCommandId
	INNER JOIN CashCommandPos_Cast AS cpc ON cpc.CashCommandPosId = cp.CashCommandPosId
	INNER JOIN BesetzungTabelle AS b ON b.ID = cpc.CastId
	INNER JOIN AufführgTabelle AS a ON a.AuffNr = b.AuffNr
	GROUP BY cc.CashCommandId
) AS sub ON CashCommand.CashCommandId = sub.id
WHERE CashCommand.BillingPeriodStart IS NULL  
--#########################################################################################
go

-- 2009 07 14 Schriftfarbe für CastStatus und ContractDateStatus
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ForeColor' AND o.id = OBJECT_ID(N'[dbo].CastStatus'))
BEGIN
	ALTER TABLE [CastStatus] ADD [ForeColor] INT NULL 
	ALTER TABLE [ContractDateStatus] ADD [ForeColor] INT NULL 
	
	exec ('UPDATE CastStatus SET [ForeColor] = CASE  CastStatusTyp WHEN 4 THEN -23296 WHEN 6 THEN -23296 ELSE -16777216 END  FROM CastStatus')
	exec ('UPDATE [ContractDateStatus] SET [ForeColor] = CASE  CDStatusTyp WHEN 0 THEN NULL  ELSE -16744448 END  FROM CastStatus')
END
go


IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[BesetzungStd_Update]'))
BEGIN
	DROP VIEW [dbo].[BesetzungStd_Update]
END
go
--Geändert am 30.04.2010 da die ALte Version nicht mit dem SQL 2000 funktioniert hat

CREATE VIEW [dbo].[BesetzungStd_Update] 
	AS
SELECT BesetzungStd.* FROM BesetzungStd WHERE Besitzer IN (
	SELECT  UserGruppe.GruppeID
	FROM UserGruppe INNER JOIN UserPw ON UserGruppe.UserID = UserPw.UserID
	WHERE UserGruppe.Schreiben = 1 and UserPw.UserName = CURRENT_USER  	AND (BerechtigungsbereichID = 2 OR BerechtigungsbereichID = 4)
) 
WITH CHECK OPTION
go
GRANT SELECT ON BesetzungStd_Update TO Public
GRANT DELETE ON BesetzungStd_Update TO Public
GRANT INSERT ON BesetzungStd_Update TO Public
GRANT UPDATE ON BesetzungStd_Update TO Public
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.Status BETWEEN 0 AND 99) 
	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 VIEW [dbo].[AufführgDeleted]
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

WHERE	UserName = CURRENT_USER 
	AND  (a.Status < 100) 
	AND  (a.Gesperrt = 0 
		OR (SELECT IS_MEMBER('Spielplan alles lesen'))=1
		OR (SELECT PERMISSIONS(OBJECT_ID('Aufführg'))&2)=2 
) 
WITH CHECK OPTION
go


IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Settings' AND o.id = OBJECT_ID(N'[dbo].Zeitkonten'))
BEGIN
	ALTER TABLE Zeitkonten ADD [Settings] TEXT NULL
END
   
go
--2009-08-03 Bugfix
REVOKE SELECT ON [dbo].[BesetzungTabelle] TO [public]   
go
--2009-08-04 Geburtstage
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[Birthdays]'))
BEGIN
	DROP VIEW [dbo].Birthdays
END
go
CREATE VIEW [dbo].[Birthdays] AS
	SELECT PNr AS PersNr, Month(GebDatum) AS BirthMonth, Day(GebDatum) AS Birthday FROM PersonalDetails WHERE NOT GebDatum IS NULL

go
GRANT SELECT ON [dbo].[Birthdays] TO Public
go

DELETE RapportSpalte WHERE RSpalteID IN ( SELECT RSpalteID FROM RapportSpalte LEFT JOIN Zeitkonten ON RapportSpalte.Ausgabe=Zeitkonten.ZeitktoNr WHERE Zeitkonten.ZeitktoNr IS NULL)
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_RapportSpalte_Zeitkonten]') AND type = 'F')
ALTER TABLE dbo.RapportSpalte ADD CONSTRAINT	FK_RapportSpalte_Zeitkonten FOREIGN KEY	([Ausgabe])
REFERENCES dbo.Zeitkonten ([ZeitktoNr]) 
GO
ALTER TABLE [dbo].RapportSpalte CHECK CONSTRAINT FK_RapportSpalte_Zeitkonten
GO

DELETE Urlaubsberechnung WHERE UrlaubsberechnungsModellID IN 
( SELECT Urlaubsberechnung.UrlaubsberechnungsModellID FROM Urlaubsberechnung LEFT JOIN UrlaubsberechnungsModell ON Urlaubsberechnung.UrlaubsberechnungsModellID=UrlaubsberechnungsModell.UrlaubsberechnungsModellID WHERE UrlaubsberechnungsModell.UrlaubsberechnungsModellID IS NULL)
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Urlaubsberechnung_UrlaubsberechnungsModell]') AND type = 'F')
ALTER TABLE dbo.Urlaubsberechnung ADD CONSTRAINT	FK_Urlaubsberechnung_UrlaubsberechnungsModell FOREIGN KEY	([UrlaubsberechnungsModellID])
REFERENCES dbo.UrlaubsberechnungsModell ([UrlaubsberechnungsModellID])  ON DELETE CASCADE
GO
ALTER TABLE [dbo].Urlaubsberechnung CHECK CONSTRAINT FK_Urlaubsberechnung_UrlaubsberechnungsModell
GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TimeAccountUsage]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[TimeAccountUsage](
		TimeAccountUsageId INT IDENTITY(1,1) NOT NULL,
		ContractId INT NOT NULL,
		TimeAccountId INT NOT NULL,
		payFrom real NOT NULL DEFAULT(0),
		payTo real NULL,
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
	 CONSTRAINT [PK_TimeAccountUsageId] PRIMARY KEY CLUSTERED  (TimeAccountUsageId ASC) ON [PRIMARY],
	 CONSTRAINT [FK_TimeAccountUsage_VertragPerso] FOREIGN KEY([ContractId]) REFERENCES [dbo].VertragPerso ([VertragsNr]) ON DELETE CASCADE,
	 CONSTRAINT [FK_TimeAccountUsage_Zeitkonten] FOREIGN KEY([TimeAccountId]) REFERENCES [dbo].Zeitkonten ([ZeitktoNr]) ON DELETE CASCADE
	) ON [PRIMARY]
END	
 go
GRANT SELECT ON [dbo].TimeAccountUsage TO Public

GRANT DELETE ON [dbo].TimeAccountUsage   TO [PersoAdmin]
GRANT INSERT ON [dbo].TimeAccountUsage   TO [PersoAdmin]
GRANT UPDATE ON [dbo].TimeAccountUsage   TO [PersoAdmin]

go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'HandicappedLeaveDays' and o.id = OBJECT_ID(N'[dbo].VertragPerso'))
BEGIN
	ALTER TABLE VertragPerso ADD HandicappedLeaveDays INT NOT NULL DEFAULT(0)
END
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TimeAccountId' and o.id = OBJECT_ID(N'[dbo].UrlaubsberechnungsModell'))
BEGIN
	ALTER TABLE UrlaubsberechnungsModell ADD TimeAccountId INT NOT NULL DEFAULT(0)
	ALTER TABLE UrlaubsberechnungsModell ADD MaxDays INT NULL
	exec('UPDATE UrlaubsberechnungsModell SET TimeAccountId = 10 WHERE TimeAccountId =0 ')
END


go
--2009-08-20 Fehlende Beziehung erstellt
UPDATE ContractDates SET CDStatusId = 0  FROM ContractDates AS CD LEFT JOIN ContractDateStatus AS cds ON cd.CDStatusId = cds.CDStatusId WHERE cds.CDStatusId IS NULL

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractDateStatus_ContractDates]') AND type = 'F')
ALTER TABLE dbo.ContractDates ADD CONSTRAINT	FK_ContractDateStatus_ContractDates FOREIGN KEY	([CDStatusId])
REFERENCES dbo.ContractDateStatus ([CDStatusId]) 
GO
ALTER TABLE dbo.ContractDates CHECK CONSTRAINT FK_ContractDateStatus_ContractDates
GO
GRANT UPDATE ON [dbo].Produktionsplan   TO Public
GRANT INSERT ON [dbo].Produktionsplan   TO Public
GRANT DELETE ON [dbo].Produktionsplan   TO Public

go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Module' and o.id = OBJECT_ID(N'[dbo].[Zulagen]'))
BEGIN
	ALTER TABLE dbo.Zulagen ADD Module INT NOT NULL Default 0 
	exec ('UPDATE Zulagen SET Module = 2 WHERE NOT Art IS NULL OR Art > 0')
	exec ('UPDATE Zulagen SET Module = 4 WHERE Art = 0 OR  Art IS NULL')
END
go
--UPDATE VertragPerso SET zyklus = NULL FROM  VertragPerso AS v LEFT JOIN Zyklen AS z ON v.zyklus = z.ZyklusNr  WHERE z.ZyklusNr IS NULL



IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_VertragPerso_Zyklen]') AND type = 'F') 
BEGIN
ALTER TABLE VertragPerso ALTER COLUMN Zyklus INT  NULL
UPDATE VertragPerso SET Zyklus = NULL FROM VertragPerso AS V LEFT JOIN Zyklen AS Z ON v.Zyklus=Z.ZyklusNr WHERE z.ZyklusNr IS NULL
ALTER TABLE dbo.VertragPerso ADD CONSTRAINT FK_VertragPerso_Zyklen FOREIGN KEY	([Zyklus]) REFERENCES dbo.Zyklen ([ZyklusNr]) 
END
GO
ALTER TABLE [dbo].VertragPerso CHECK CONSTRAINT FK_VertragPerso_Zyklen
GO

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ShowForward' and o.id = OBJECT_ID(N'[dbo].RapportSpalte'))
BEGIN
	ALTER TABLE RapportSpalte ADD ShowForward BIT NOT NULL DEFAULT (0)
	exec ('UPDATE RapportSpalte SET ShowForward = 1 WHERE Ausgabe IN (10,41,52)')
END
GO


-- 2009-09-08 Neuer View zum prüfen der RelatedDatas für Role
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[GetRelatedDataOfRole]'))
BEGIN
	DROP PROCEDURE [dbo].[GetRelatedDataOfRole] 
END
go
CREATE PROCEDURE [dbo].[GetRelatedDataOfRole] 
	@RoleId INT
AS
BEGIN
SET NOCOUNT ON

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

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

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

GRANT EXECUTE ON [dbo].[GetRelatedDataOfRole]  TO [public]
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[HasRoleRelatedData]'))
BEGIN
	DROP PROCEDURE [dbo].[HasRoleRelatedData] 
END
GO
--Zurücksetzen von verweisten Referenzen
UPDATE AufführgTabelle SET CreateCountDownId = NULL FROM AufführgTabelle as a LEFT JOIN CountDown AS C ON a.CreateCountDownId=c.CountDownID WHERE c.CountDownID IS NULL and NOT a.CreateCountDownId IS NULL
GO

DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))

IF (@sql_server_version > 8)  BEGIN
 --Referenz zwischen aufführg und Countdown erstellen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_AufführgTabelle_Countdown]') AND type = 'F')
exec ('ALTER TABLE [dbo].[AufführgTabelle]  WITH CHECK ADD  CONSTRAINT [FK_AufführgTabelle_Countdown] FOREIGN KEY([CreateCountDownId])
REFERENCES [dbo].[CountDown] ([CountDownId]) ON DELETE SET NULL')
END
GO
--2009-09-11 Bezeichnung für Darsterller geändert
UPDATE RollenLtg SET Rolle = 'Darsteller' WHERE RollenLtgID = 0 AND Rolle = '*Solist'
UPDATE RollenLtg SET RolleKurz = 'Darst.' WHERE RollenLtgID = 0 AND RolleKurz = '*'
Go
	
--2009 09 15 
ALTER VIEW [dbo].[Spielzeit]
AS
SELECT DISTINCT spz.*
FROM  Spielzeittabelle AS spz 
	LEFT JOIN UserForAccess AS us ON spz.SpzNr = us.SpzNr
	LEFT JOIN UserPW AS pw ON us.userid=pw.userid
WHERE  CURRENT_USER = UserName 
	OR spz.spznr = 0	
go
	

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Besitzer' AND o.id = OBJECT_ID(N'[dbo].PersonalNotizen') AND c.xtype <> 56)
BEGIN
	ALTER TABLE PersonalNotizen ALTER COLUMN Besitzer INT NOT NULL
	Print 'WertText geändert'
END
go	
DeleteConstraint 'VertragPerso', 'Zyklus'
go

--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Scenario]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
--BEGIN
--CREATE TABLE [dbo].[Scenario](
--		ScenarioId INT IDENTITY(1,1) NOT NULL,
--		RoleId INT NOT NULL,
--		TimeAccountId INT NOT NULL,
--		payFrom real NOT NULL DEFAULT(0),
--		payTo real NULL,
--		[LM] datetime NOT NULL,
--		[UM] int NOT NULL,
--		[LC] datetime NOT NULL,
--		[UC] int NOT NULL,
--	 CONSTRAINT [PK_ScenarioId] PRIMARY KEY CLUSTERED  (ScenarioId ASC) ON [PRIMARY],
--	 CONSTRAINT [FK_Scenario_BesetzungStd] FOREIGN KEY([RoleId]) REFERENCES [dbo].BesetzungStd ([Id]) ON DELETE CASCADE,
--	 CONSTRAINT [FK_TimeAccountUsage_Zeitkonten] FOREIGN KEY([TimeAccountId]) REFERENCES [dbo].Zeitkonten ([ZeitktoNr]) ON DELETE CASCADE
--	) ON [PRIMARY]
--END	
--GO

-- 2009-09-17
-- Nachtschicht
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'EndOfEvening' and o.id = OBJECT_ID(N'[dbo].DienstplanArtenTabelle'))
BEGIN
	ALTER TABLE DienstplanArtenTabelle ADD EndOfEvening DATETIME NULL
	ALTER TABLE DienstplanArtenTabelle ADD EndOfNight DATETIME NULL
	ALTER TABLE DienstplanArtenTabelle ADD NightShiftBackgroundColor INT NULL
	ALTER TABLE DienstplanArtenTabelle ADD NightShiftForegroundColor INT NULL
	EXEC ('UPDATE DienstplanArtenTabelle SET EndOfEvening = ''1900-1-1 00:00:00.000'', EndOfNight = ''1900-1-1 00:00:00.000''')
END
GO

-- Spielplangruppierung
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'GroupGuestPerformingStages' and o.id = OBJECT_ID(N'[dbo].DienstplanArtenTabelle'))
BEGIN
	ALTER TABLE DienstplanArtenTabelle ADD GroupGuestPerformingStages BIT NULL
END
GO

-- Export Besetzungszeitraum
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CastExportPeriodStart' and o.id = OBJECT_ID(N'[dbo].PlanExport'))
BEGIN
	ALTER TABLE PlanExport ADD CastExportPeriodStart DATETIME NULL
	ALTER TABLE PlanExport ADD CastExportPeriodEnd DATETIME NULL
END
GO

 --Referenz zwischen BesetzungTabelle und AuffTechAufgabe erstellen
IF NOT EXISTS (
	SELECT * 
	FROM dbo.sysobjects 
	WHERE id = OBJECT_ID(N'[dbo].[FK_BesetzungTabelle_AuffTechAufgabe]') AND type = 'F')
BEGIN
ALTER TABLE BesetzungTabelle ADD AuffTechAufgabeID INT NULL

exec ('Update BesetzungTabelle
SET AuffTechAufgabeID = (
	SELECT TOP 1 AuffTechAufgabeID 
	FROM AuffTechAufgabe AS ATA  
	WHERE ATA.RolleID = BesetzungTabelle.RolleID 
		AND ATA.AuffNr = BesetzungTabelle.AuffNr)')

exec ('ALTER TABLE [dbo].[BesetzungTabelle]  WITH CHECK ADD  CONSTRAINT [FK_BesetzungTabelle_AuffTechAufgabe] FOREIGN KEY([AuffTechAufgabeID])
REFERENCES [dbo].[AuffTechAufgabe] ([AuffTechAufgabeID])')

END
GO
--2009-09-11 Bezeichnung für Darsterller geändert
UPDATE RollenLtg SET Rolle = 'Darsteller' WHERE RollenLtgID = 0 AND Rolle = '*Solist'
UPDATE RollenLtg SET RolleKurz = 'Darst.' WHERE RollenLtgID = 0 AND RolleKurz = '*'
Go
	
IF (SELECT c.cdefault FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id
	WHERE c.name = 'RolleId' AND o.id = OBJECT_ID(N'dbo.BesetzungTabelle')) <> 0
EXECUTE sp_unbindefault N'dbo.BesetzungTabelle.RolleId'
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PrintName' and o.id = OBJECT_ID(N'[dbo].AZTypen'))
BEGIN
	ALTER TABLE AZTypen ADD PrintName VARCHAR(15) 
END
go

--2009-09-29
--Umstellung der Bühnenfilter auf neuen "ObjectName" der aus einem Bugfix resultiert
UPDATE VerteilerFeld SET ObjectName = 'zr.zrNr' where ObjectName = 'zrNr' AND ControlContainerName='ts_DataAuff'

--	denominator 
-- 	numerator 

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[RoleBonus]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[RoleBonus](
		RoleBonusId INT IDENTITY(1,1) NOT NULL,
		RoleId INT NOT NULL,
		BonusId INT NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
	 CONSTRAINT [PK_RoleBonusId] PRIMARY KEY CLUSTERED  (RoleBonusId ASC) ON [PRIMARY],
	 CONSTRAINT [FK_RoleBonus_BesetzungStd] FOREIGN KEY([RoleId]) REFERENCES [dbo].BesetzungStd ([Id]) ON DELETE CASCADE,
	 CONSTRAINT [FK_RoleBonus_Zulagen] FOREIGN KEY([BonusId]) REFERENCES [dbo].Zulagen ([ZulagenNr]) ON DELETE CASCADE
	) ON [PRIMARY]
END	
go
DropColumn  'RoleBonus', 'Denominator'
go
DropColumn  'RoleBonus', 'Numerator'
go
GRANT SELECT ON RoleBonus TO public
GRANT DELETE ON RoleBonus TO ChorAdmin
GRANT INSERT ON RoleBonus TO ChorAdmin
GRANT UPDATE ON RoleBonus TO ChorAdmin
go

UPDATE Stücke SET [Begin] = '18991230 ' + CONVERT(varchar(5), [Begin], 108) WHERE NOT [Begin]  IS NULL
UPDATE Stücke SET Dauer = '18991230 ' + CONVERT(varchar(5), [Dauer], 108) WHERE NOT Dauer  IS NULL
UPDATE StatusZeitR SET UhrBeginn = '18991230 ' + CONVERT(varchar(5), [UhrBeginn], 108) WHERE NOT UhrBeginn IS NULL
UPDATE StatusZeitR SET UhrEnde = '18991230 ' + CONVERT(varchar(5), [UhrEnde], 108) WHERE NOT UhrEnde IS NULL
UPDATE Aufführgtabelle SET UhrBeg = '18991230 ' + CONVERT(varchar(5), [UhrBeg], 108)
UPDATE Aufführgtabelle SET UhrEnde = '18991230 ' + CONVERT(varchar(5), [UhrEnde], 108) WHERE UhrEnde <= '19000101'
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Module' and o.id = OBJECT_ID(N'[dbo].ABGruppe'))
BEGIN
	ALTER TABLE ABGruppe ADD Module INT NOT NULL DEFAULT (0)
END
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'UnderstudyPosition' and o.id = OBJECT_ID(N'[dbo].BesetzungStdSoliTabelle'))
BEGIN
	ALTER TABLE BesetzungStdSoliTabelle ADD UnderstudyPosition INT NOT NULL DEFAULT (0)
END
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'RoleCode' and o.id = OBJECT_ID(N'[dbo].BesetzungStd'))
BEGIN
	ALTER TABLE BesetzungStd ADD RoleCode VARCHAR(3) 
END
go
--2009-10-07
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DayFee' and o.id = OBJECT_ID(N'[dbo].VertragRolle'))
BEGIN
	ALTER TABLE VertragRolle ADD DayFee MONEY NOT NULL DEFAULT(0)
END
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Module' and o.id = OBJECT_ID(N'[dbo].SalaryLevel'))
BEGIN
	ALTER TABLE SalaryLevel ADD Module INT NOT NULL DEFAULT (0)
END
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'RowHigh' and o.id = OBJECT_ID(N'[dbo].DayNoteCategories'))
BEGIN
	ALTER TABLE DayNoteCategories ADD RowHigh INT  NULL 
END
go
--IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
--	WHERE c.name = 'VersionDate' and o.id = OBJECT_ID(N'[dbo].Instrumenbestand'))
--BEGIN
--	ALTER TABLE Instrumenbestand ADD VersionDate DATETIME NULL	
--END
 
go
--IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
--	WHERE c.name = 'Denominator' and o.id = OBJECT_ID(N'[dbo].Zulagen'))
--BEGIN
--	ALTER TABLE Zulagen ADD Denominator INT NOT NULL DEFAULT(1) 
--	ALTER TABLE Zulagen ADD Numerator REAL NOT NULL DEFAULT(0)
--END
go

-- 2009-10-20
-- Spalte Sort in Tabelle Qualification hinzufügen
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'[dbo].Qualification'))
BEGIN
	ALTER TABLE Qualification ADD Sort INT NOT NULL	DEFAULT 99
END
go
--2009 10 20
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'NumberOfDays' and o.id = OBJECT_ID(N'[dbo].RapportSpalte'))
BEGIN
	ALTER TABLE RapportSpalte ADD NumberOfDays BIT NOT NULL DEFAULT (0)
END
GO

--IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
--	WHERE c.name = 'BackColor' and o.id = OBJECT_ID(N'[dbo].OrchBesetzung'))
--BEGIN
--	ALTER TABLE OrchBesetzung ADD BackColor INT NULL
--END
go

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[DienstplanArtenKopf]')  AND name = 'iDepartmentStage')
CREATE UNIQUE INDEX iDepartmentStage ON dbo.DienstplanArtenKopf
	(DienstplanArtenID, ZrNr) ON [PRIMARY]

go
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'CostsWrite')
BEGIN
	EXEC sp_addrole @rolename = N'CostsWrite'
	EXEC sp_addrole @rolename = N'CostsRead'
END
go

GRANT SELECT ON Kosten_Aufführg TO CostsRead

GRANT SELECT ON Kosten_Aufführg TO CostsWrite
GRANT DELETE ON Kosten_Aufführg TO CostsWrite
GRANT INSERT ON Kosten_Aufführg TO CostsWrite
GRANT UPDATE ON Kosten_Aufführg TO CostsWrite

GRANT SELECT ON Kosten_Stück TO CostsRead

GRANT SELECT ON Kosten_Stück TO CostsWrite
GRANT DELETE ON Kosten_Stück TO CostsWrite
GRANT INSERT ON Kosten_Stück TO CostsWrite
GRANT UPDATE ON Kosten_Stück TO CostsWrite

GRANT SELECT ON AufführgDetails TO CostsRead

GRANT SELECT ON AufführgDetails TO CostsWrite
GRANT DELETE ON AufführgDetails TO CostsWrite
GRANT INSERT ON AufführgDetails TO CostsWrite
GRANT UPDATE ON AufführgDetails TO CostsWrite
go

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'SalesTaxesId' and o.id = OBJECT_ID(N'[dbo].[SalesTaxes]'))
BEGIN
	DROP TABLE SalesTaxes
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Taxes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Taxes](
	TaxId INT IDENTITY(1,1) NOT NULL,
	ValidFrom datetime NOT NULL,
	ValidTo datetime NOT NULL,
	TaxValue REAL NOT NULL CONSTRAINT [DF_Taxes_TaxValue] DEFAULT (0),
	TaxType INT NOT NULL CONSTRAINT [DF_Taxes_TaxType] DEFAULT (1),
	[LM] DATETIME NOT NULL,
	[UM] INT NOT NULL,
	[LC] DATETIME NOT NULL,
	[UC] INT NOT NULL,
	CONSTRAINT [PK_TaxId] PRIMARY KEY CLUSTERED (TaxId ASC) ON [PRIMARY],
) ON [PRIMARY]
END	
GO

GRANT SELECT ON Taxes TO Public
GRANT DELETE ON Taxes TO Konfigurieren
GRANT INSERT ON Taxes TO Konfigurieren
GRANT UPDATE ON Taxes TO Konfigurieren
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Note' and o.id = OBJECT_ID(N'[dbo].[BodyMeasurementData]'))
BEGIN
	ALTER TABLE dbo.BodyMeasurementData ADD Note VARCHAR(30) NULL
END	

GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Priority' and o.id = OBJECT_ID(N'[dbo].[Zeitkonten]'))
BEGIN
	ALTER TABLE dbo.Zeitkonten ADD 	Priority INT NULL
	exec ('UPDATE Zeitkonten SET Priority = 1 WHERE Formel >= 1270 AND Formel <1280')
	exec ('UPDATE Zeitkonten SET Priority = 0 WHERE (Formel > 1202 AND Formel < 1203)  OR Formel = 1201')
END	
go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].CountActivetyContractDates'))
BEGIN
	DROP PROCEDURE dbo.CountActivetyContractDates 
END
Go
--20091118
--Anzahl der zugesagte Vertragstermine 
CREATE PROCEDURE dbo.CountActivetyContractDates 
	@ActivetyId INT
AS

SET NOCOUNT ON
BEGIN
	
	SELECT Count(*) 
	FROM ContractDates AS cd 
		INNER JOIN BesetzungTabelle AS c ON cd.CastId=c.ID 
	WHERE cd.IsCanceled = 0 AND c.AuffNr = @ActivetyId 

	
END	
GO
GRANT EXECUTE ON CountActivetyContractDates TO Public
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbBodyMeasurements'))
BEGIN
DROP VIEW [dbo].AbBodyMeasurements
END
go
CREATE VIEW [dbo].AbBodyMeasurements
AS 
SELECT  bs.*  FROM  BodyMeasurements  AS bs WHERE Bs.PersonId IN
	   (SELECT PersH.PersNr 
		FROM PersH 
			INNER JOIN UserGruppe  ON PersH.Besitzer     = UserGruppe.GruppeID
			INNER JOIN UserPW        ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 6)
WITH CHECK OPTION
go
GRANT SELECT ON AbBodyMeasurements TO public
GRANT UPDATE ON AbBodyMeasurements TO public
GRANT DELETE ON AbBodyMeasurements TO public
GRANT INSERT ON AbBodyMeasurements TO public
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbBodyMeasurementData'))
BEGIN
DROP VIEW [dbo].AbBodyMeasurementData
END
go
CREATE VIEW [dbo].AbBodyMeasurementData
AS 
SELECT  bs.*  FROM  BodyMeasurementData  AS bs WHERE Bs.BodyMeasurementId IN
	   (SELECT BodyMeasurements.BodyMeasurementId 
		FROM BodyMeasurements INNER JOIN PersH  ON BodyMeasurements.PersonId=PersH.PersNr
			INNER JOIN UserGruppe  ON PersH.Besitzer     = UserGruppe.GruppeID
			INNER JOIN UserPW        ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 6)
WITH CHECK OPTION
go
GRANT SELECT ON AbBodyMeasurementData TO public
GRANT UPDATE ON AbBodyMeasurementData TO public
GRANT DELETE ON AbBodyMeasurementData TO public
GRANT INSERT ON AbBodyMeasurementData TO public

GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Multiplier' and o.id = OBJECT_ID(N'[dbo].[Zulagen]'))
BEGIN
	ALTER TABLE dbo.Zulagen ADD Multiplier REAL NOT NULL DEFAULT 1
END	
GO
 
--20091202
--Neue Abelle fürFeitertagsAusgl.-Sets die an Tarife gebunden werden können
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[HolidayBalanceSet]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].HolidayBalanceSet(
	[HolidayBalanceSetID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar] (16) NOT NULL,
	[Description] [varchar] (120),
	[LM] DATETIME NOT NULL,
	[UM] INT NOT NULL,
	[LC] DATETIME NOT NULL,
	[UC] INT NOT NULL,
	CONSTRAINT [PK_HolidayBalanceSet] PRIMARY KEY CLUSTERED (
		HolidayBalanceSetID ASC
	)WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON HolidayBalanceSet TO PersoAdmin
GRANT UPDATE ON HolidayBalanceSet TO PersoAdmin
GRANT SELECT ON HolidayBalanceSet TO PersoContractWrite
GRANT UPDATE ON HolidayBalanceSet TO PersoContractWrite
GRANT SELECT ON HolidayBalanceSet TO public

GO

IF NOT EXISTS(SELECT * FROM HolidayBalanceSet WHERE HolidayBalanceSetID = 0)
BEGIN
SET IDENTITY_INSERT HolidayBalanceSet ON
INSERT INTO HolidayBalanceSet (HolidayBalanceSetID, Name, [Description], LC, LM, UC, UM) 
VALUES (0, 'StandardSet' ,'Automatisch erzeugtes Standardset', '19000101','19000101', 0, 0);
SET IDENTITY_INSERT HolidayBalanceSet OFF
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'HolidayBalanceSetID' and o.id = OBJECT_ID(N'[dbo].[FeiertageAusg]'))
BEGIN
	ALTER TABLE dbo.FeiertageAusg ADD HolidayBalanceSetID int NOT NULL CONSTRAINT [DF_FeiertageAusg_HolidayBalanceSetID] DEFAULT (0)
	ALTER TABLE dbo.FeiertageAusg WITH CHECK ADD  CONSTRAINT [FK_FeiertageAusg_HolidayBalanceSet] FOREIGN KEY([HolidayBalanceSetID])
	REFERENCES [dbo].[HolidayBalanceSet] ([HolidayBalanceSetID])
END	
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'HolidayBalanceSetID' and o.id = OBJECT_ID(N'[dbo].[PersoParameter]'))
BEGIN
	ALTER TABLE dbo.PersoParameter ADD HolidayBalanceSetID int NOT NULL CONSTRAINT [DF_PersoParameter_HolidayBalanceSetID] DEFAULT (0)
	ALTER TABLE dbo.PersoParameter WITH CHECK ADD  CONSTRAINT [FK_PersoParameter_HolidayBalanceSet] FOREIGN KEY([HolidayBalanceSetID])
	REFERENCES [dbo].[HolidayBalanceSet] ([HolidayBalanceSetID])
END	

--20091208
--Neues Feld in ABGruppe zur steuerung des Dienstplan-Ausdrucks.

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ScheduleOutput' and o.id = OBJECT_ID(N'[dbo].[ABGruppe]'))
BEGIN
	ALTER TABLE dbo.ABGruppe ADD ScheduleOutput bit NOT NULL DEFAULT 1
END	
	
-- Neues Feld in CountDown 
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ForActivityTypeId' and o.id = OBJECT_ID(N'[dbo].CountDown'))
BEGIN
	ALTER TABLE CountDown ADD ForActivityTypeId INT NULL
END
go
UPDATE AufführgTabelle Set Gesperrt = 0 WHERE Gesperrt IS NULL
UPDATE AufführgTabelle Set Status  = 10 WHERE Status IS NULL
UPDATE BesetzungTabelle Set Gesperrt = 0 WHERE Gesperrt IS NULL
UPDATE PersH Set Gesperrt = 0 WHERE Gesperrt IS NULL

--20091211
-- Neue Felder in PersDetails für Visa-Daten
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'MiddleNames' and o.id = OBJECT_ID(N'[dbo].[PersonalDetails]'))
BEGIN
	ALTER TABLE dbo.PersonalDetails ADD MiddleNames varchar(60) NULL
	ALTER TABLE dbo.PersonalDetails ADD LandOfBirth varchar(30) NULL
	ALTER TABLE dbo.PersonalDetails ADD PreviousNationality varchar(30) NULL
	ALTER TABLE dbo.PersonalDetails ADD NameOfFather varchar(60) NULL
	ALTER TABLE dbo.PersonalDetails ADD IdentityCardNo varchar(30) NULL
	ALTER TABLE dbo.PersonalDetails ADD IdentityCardIssuedOn datetime NULL
	ALTER TABLE dbo.PersonalDetails ADD IdentityCardValidTo datetime NULL
	ALTER TABLE dbo.PersonalDetails ADD IdentityCardIssuedIn varchar(30) NULL
	ALTER TABLE dbo.PersonalDetails ADD ValidResidencePermit varchar(30) NULL
	ALTER TABLE dbo.PersonalDetails ADD Job varchar(30) NULL
	ALTER TABLE dbo.PersonalDetails ADD HealthInsuranceNo varchar(30) NULL
	ALTER TABLE dbo.PersonalDetails ADD HealthInsuranceType int NOT NULL Default -1
	ALTER TABLE dbo.PersonalDetails ADD HealthInsuranceId int NULL
	ALTER TABLE dbo.PersonalDetails WITH CHECK ADD  CONSTRAINT [FK_Person_HealthInsurance] FOREIGN KEY([HealthInsuranceId])
	REFERENCES [dbo].[PersH] ([PersNr])
	ALTER TABLE dbo.PersonalDetails ADD TaxOfficeId int NULL
	ALTER TABLE dbo.PersonalDetails WITH CHECK ADD  CONSTRAINT [FK_Person_TaxOffice] FOREIGN KEY([TaxOfficeId])
	REFERENCES [dbo].[PersH] ([PersNr])
END	
go

-- 2009-12-22
-- Spalte Gesperrt auf DEFAULT 0 setzten
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_AufführgTabelle_Gesperrt]') )
	ALTER TABLE AufführgTabelle ADD CONSTRAINT DF_AufführgTabelle_Gesperrt DEFAULT 0 FOR Gesperrt
GO

-- 2010-01-07
-- StoredProcedure zum Abfragen der Anzahl von Aktivitäten vor dem Löschen einer Produktion
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].GetActivityCountForProduction'))
BEGIN
	DROP PROCEDURE dbo.GetActivityCountForProduction
END
go
CREATE PROCEDURE [dbo].[GetActivityCountForProduction]
	@productionId int
As
	SELECT Count(*)
	FROM AufführgTabelle 
	WHERE snr = @productionId
GO
GRANT EXECUTE ON GetActivityCountForProduction TO Public
GO


--2010-01-11
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_UserForAccess_Season]') AND type = 'F')
BEGIN
DELETE FROM UserForAccess WHERE UserForAccess.UserForAccessID IN (SELECT UserForAccess.UserForAccessID FROM  UserForAccess LEFT JOIN SpielzeitTabelle ON UserForAccess.SpzNr=SpielzeitTabelle.SpzNr 
WHERE SpielzeitTabelle.SpzNr IS NULL)

ALTER TABLE [dbo].[UserForAccess]  WITH CHECK ADD  CONSTRAINT [FK_UserForAccess_Season] FOREIGN KEY([SpzNr])
REFERENCES [dbo].[SpielzeitTabelle] ([SpzNr]) ON DELETE CASCADE
END
GO
ALTER TABLE [dbo].[UserForAccess] CHECK CONSTRAINT [FK_UserForAccess_Season]
go
DELETE FROM FeiertageAusg WHERE FTArt = 0
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'NoPause' and o.id = OBJECT_ID(N'[dbo].Dienstplan'))
BEGIN
	ALTER TABLE Dienstplan ADD NoPause BIT NOT NULL DEFAULT(0)
	ALTER TABLE AZTypen ADD NoPauseDefault BIT NOT NULL DEFAULT(0)
END

GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ContractTypeId' and o.id = OBJECT_ID(N'[dbo].RoleBonus'))
BEGIN
	ALTER TABLE RoleBonus ADD ContractTypeId INT NULL
	
	exec ('UPDATE RoleBonus SET ContractTypeId = (SELECT MIN(VorlagenID) FROM VertragsVorlagen WHERE Module = 16) WHERE ContractTypeId IS NULL')
	exec ('ALTER TABLE RoleBonus ALTER COLUMN ContractTypeId INT NOT NULL')
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ProductionBonus]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ProductionBonus](
		ProductionBonusId INT IDENTITY(1,1) NOT NULL,
		ProductionId INT NOT NULL,
		BonusId INT NOT NULL,
		ContractTypeId INT NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
	 CONSTRAINT [PK_ProductionBonusId] PRIMARY KEY CLUSTERED  (ProductionBonusId ASC) ON [PRIMARY],
	 CONSTRAINT [FK_ProductionBonus_Productions] FOREIGN KEY([ProductionId]) REFERENCES [dbo].Stücke ([Snr]) ON DELETE CASCADE,
	 CONSTRAINT [FK_ProductionBonus_Zulagen] FOREIGN KEY([BonusId]) REFERENCES [dbo].Zulagen ([ZulagenNr]) ON DELETE CASCADE
	) ON [PRIMARY]
END	

GRANT SELECT ON [ProductionBonus] TO public
GRANT DELETE ON [ProductionBonus] TO ChorAdmin
GRANT INSERT ON [ProductionBonus] TO ChorAdmin
GRANT UPDATE ON [ProductionBonus] TO ChorAdmin

GO

--2010-01-14
--Neue Spalte für Gastanteil in CashCommand
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AgencyFeeGuestPart' AND o.id = OBJECT_ID(N'[dbo].CashCommand'))
BEGIN
	ALTER TABLE [CashCommand] ADD [AgencyFeeGuestPart] REAL NOT NULL CONSTRAINT [DF_CashCommand_AgencyFeeGuestPart] DEFAULT (0.0)	
END
go


IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Besetzung__BesSo__2E9C95DD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[BesetzungTabelle] DROP CONSTRAINT [DF__Besetzung__BesSo__2E9C95DD]
END

go


--2010-01-25
--Neue Spalte für XML-Settings in RollenLtg
IF NOT EXISTS (
	SELECT * 
	FROM sysColumns c 
		INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Settings' AND o.id = OBJECT_ID(N'[dbo].RollenLtg'))
BEGIN
	ALTER TABLE RollenLtg ADD [Settings] TEXT NULL
END
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ProductionCode' AND o.id = OBJECT_ID(N'[dbo].Stücke'))
BEGIN
	ALTER TABLE Stücke ADD ProductionCode VARCHAR(10) NULL	
END

go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PersonModulGroupPermission]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].PersonModulGroupPermission(
		[PersonModulGroupPermissionId] INT IDENTITY(1,1) NOT NULL,
		[PersonId] INT NOT NULL,
		[ModulGroupId] INT NOT NULL,
		[PermissionType] INT NOT NULL,
		[HasWritePermission] BIT NOT NULL DEFAULT(0),
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		CONSTRAINT [PK_PersonModulGroupPermission] PRIMARY KEY CLUSTERED (PersonModulGroupPermissionId ASC)WITH FILLFACTOR = 90 ON [PRIMARY],
		CONSTRAINT [FK_PersonModulGroupPermission_Person] FOREIGN KEY([PersonId]) REFERENCES [dbo].PersH ([PersNr]) ON DELETE CASCADE,
		CONSTRAINT [FK_PersonModulGroupPermission_ModulGroup] FOREIGN KEY([ModulGroupId]) REFERENCES [dbo].Gruppe ([GruppeId]) ON DELETE CASCADE
	) ON [PRIMARY]
END
GO

--2014-25-01 sh
--neue spalte in personmodulgrouppermission zum hinterlegen ob zugriff auf geheime kontaktdaten
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'HasAccessToSecretContactData' AND o.id = OBJECT_ID('dbo.PersonModulGroupPermission'))
BEGIN
	ALTER TABLE dbo.PersonModulGroupPermission ADD HasAccessToSecretContactData BIT NOT NULL 
	CONSTRAINT DF_PersonModulGroupPermission_HasAccessToSecretContactData DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PersonModulGroupPermission]')  AND name = 'IX_PersonModulGroupPermission_PersonId_ModulGroupId')
BEGIN
	CREATE UNIQUE NONCLUSTERED INDEX [IX_PersonModulGroupPermission_PersonId_ModulGroupId] ON [dbo].[PersonModulGroupPermission] 
	(	[PersonId] ASC,
		[ModulGroupId] ASC
	) ON [PRIMARY]
END

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

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

GO

GRANT SELECT ON PersonModulGroupPermission TO Public
GRANT SELECT ON PersonModulGroupPermission_Update TO Public
GRANT DELETE ON PersonModulGroupPermission_Update TO Public
GRANT UPDATE ON PersonModulGroupPermission_Update TO Public
GRANT INSERT ON PersonModulGroupPermission_Update TO Public

GO
IF not EXISTS(SELECT * FROM Gruppe WHERE GruppeId = -1) 
BEGIN 
	--Gruppe Public (Jeder) erstellen
	SET IDENTITY_INSERT Gruppe ON
	INSERT INTO [Gruppe] (GruppeiD, [GruppeBez] ,[LM] ,[UM] ,[LC] ,[UC] ,[Sort] ,[Modul]) VALUES (-1, 'Jeder','19000101',0,'19000101',0,-1,0)
	SET IDENTITY_INSERT Gruppe OFF
END
GO

IF (SELECT COUNT(*) FROM PersonModulGroupPermission) = 0 
BEGIN 
	--Öffentliche Kontakte in Public
	INSERT INTO PersonModulGroupPermission ([PersonId],[ModulGroupId],[PermissionType],HasWritePermission,[LM],[UM],[LC],[UC]) 
		SELECT PersNr, -1 ,0,0,'19000101',0,'19000101', 0 
		FROM   PersH AS P 
		WHERE  p.Gesperrt=0 OR p.Gesperrt IS NULL

	INSERT INTO PersonModulGroupPermission ([PersonId],[ModulGroupId],[PermissionType],HasWritePermission,[LM],[UM],[LC],[UC])  
		SELECT PersNr, PersH.Besitzer,0,1,'19000101',0,'19000101', 0 FROM PersH	
END	
GO
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.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

ALTER VIEW [dbo].[AbPersD]
AS
SELECT Ph.PersNr as pnr, AD.str, AD.ort,AD.plz,AD.land,AD.co,
	(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =5 AND PersKom.PersNR=Ph.PersNr) AS Homepage,
	(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =4 AND PersKom.PersNR=Ph.PersNr) AS eMail,
	(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =3 AND PersKom.PersNR=Ph.PersNr) AS Fax,
	(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =2 AND PersKom.PersNR=Ph.PersNr) AS Handy,
	(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =1 AND PersKom.PersNR=Ph.PersNr) AS HausRuf,
	(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =0 AND PersKom.PersNR=Ph.PersNr) AS Tel, 
	sub.schreiben,NULL AS InternetLink, NULL AS PersNrVorh, GebDatum, NULL AS KstAbt, RepetiSoliProSort,  [Memo], [National], GebOrt, MemoExtern, 
	Adressplan,0 as Plan_Person, NULL AS BildVerweis, MemoExtern_en, 0 AS InTrs, InWeb, VersicherungsNr, SteuerNr, Finanzamt, UstID, PassNr, 
	PassAusAmt, PassAusOrt, PassAusDatum, PassAblDatum
 FROM PersH  as Ph 
	LEFT JOIN PersonalDetails on ph.persnr=PersonalDetails.pnr 
	 LEFT JOIN (SELECT * FROM PersAdresse WHERE Sort = 0) as AD on ph.persnr=ad.persNr 
	 INNER  JOIN (	SELECT  pp.PersonId, MAX(CASE WHEN (OptionsFlag & 1 <> 1 OR PP.HasAccessToSecretContactData = 0) THEN 0 ELSE 1 END) AS SecretPermission , MAX(CAST(ug.schreiben as int)) as schreiben 
			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 ph.PersNr = sub.PersonId 
	
go
ALTER VIEW [dbo].[AbPersKontakt]
AS
SELECT Ph.PersNr as pnr, AD.str, AD.ort,AD.plz,AD.land,AD.co,
	(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =5 AND PersKom.PersNR=Ph.PersNr) AS Homepage,
	(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =4 AND PersKom.PersNR=Ph.PersNr) AS eMail,
	(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =3 AND PersKom.PersNR=Ph.PersNr) AS Fax,
	(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =2 AND PersKom.PersNR=Ph.PersNr) AS Handy,
	(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =1 AND PersKom.PersNR=Ph.PersNr) AS HausRuf,
	(SELECT TOP 1 Wert FROM PersKom WHERE  IsSecret=0 AND Sort = 0 AND PersKTypID =0 AND PersKom.PersNR=Ph.PersNr) AS Tel, 
sub.schreiben,NULL AS InternetLink, NULL AS PersNrVorh, NULL AS KstAbt, RepetiSoliProSort, [Memo], MemoExtern, Adressplan, 0 as Plan_Person, NULL AS BildVerweis, MemoExtern_en,0 AS InTrs, InWeb
 FROM PersH  as Ph 
	LEFT JOIN PersonalDetails on ph.persnr=PersonalDetails.pnr 
	 LEFT JOIN (SELECT * FROM PersAdresse WHERE Sort = 0) as AD on ph.persnr=ad.persNr 
	 INNER  JOIN (	SELECT  pp.PersonId, MAX(CASE WHEN (OptionsFlag & 1 <> 1 OR PP.HasAccessToSecretContactData = 0) THEN 0 ELSE 1 END) AS SecretPermission , MAX(CAST(ug.schreiben as int)) as schreiben 
			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 ph.PersNr = sub.PersonId 
	
GO
ALTER VIEW [dbo].[AbPersonalDetails]
AS 
SELECT  PersonalDetails.*  FROM  PersonalDetails WHERE Pnr 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.BerechtigungsbereichID = 0 AND pp.PermissionType=0 AND Username = CURRENT_USER GROUP BY pp.PersonId)

GO
GRANT SELECT ON AbPersonalDetails TO [Soli-Daten lesen]
GRANT DELETE ON AbPersonalDetails TO [Soli-Daten lesen]
GRANT UPDATE ON AbPersonalDetails TO [Soli-Daten lesen]
GRANT INSERT ON AbPersonalDetails TO [Soli-Daten lesen]
go


IF   EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPersonalDetails_Update]'))
BEGIN
DROP View [dbo].[AbPersonalDetails_Update]
END
go
CREATE VIEW [dbo].[AbPersonalDetails_Update]
AS 
SELECT  PersonalDetails.*  FROM  PersonalDetails WHERE Pnr 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 pp.HasWritePermission=1 AND UG.Schreiben=1 AND  ug.BerechtigungsbereichID = 0 AND pp.PermissionType=0 AND Username = CURRENT_USER GROUP BY pp.PersonId)



GO
GRANT SELECT ON [AbPersonalDetails_Update] TO [Soli-Daten ändern]
GRANT DELETE ON [AbPersonalDetails_Update] TO [Soli-Daten ändern]
GRANT UPDATE ON [AbPersonalDetails_Update] TO [Soli-Daten ändern]
GRANT INSERT ON [AbPersonalDetails_Update] TO [Soli-Daten ändern]
go


--2010-02-08
--Neue StoredProcedure zum Kopieren von Rollen

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[CopyRole]'))
BEGIN
DROP PROCEDURE [dbo].[CopyRole]
END
GO
CREATE PROCEDURE [dbo].[CopyRole]
	@productionId int,
	@roleId  int
As
BEGIN
INSERT INTO BesetzungStd (
ABGruppeID, Anzahl, Besitzer, GruppeID, Cover, 
nameDrucken, EndOffset, Exklusiv, RolleFrau, StarRole, Leporello, RolleMann, 
PresseSort, Pos, DruckStd, DruckSteuerung, RoleCode, RollePresse, Rolle, 
RolleKurz, RollenLtgID, StartOffset, StdPro, StdVs, SNr) 
SELECT 
ABGruppeID, Anzahl, Besitzer, GruppeID, Cover, 
nameDrucken, EndOffset, Exklusiv, RolleFrau, StarRole, Leporello, RolleMann, 
PresseSort, Pos, DruckStd, DruckSteuerung, RoleCode, RollePresse, Rolle, 
RolleKurz, RollenLtgID, StartOffset, StdPro, StdVs, @productionId 
FROM BesetzungStd AS RoleSource WHERE RoleSource.ID = @roleId
SELECT CAST(@@IDENTITY as INT)
END
GO
GRANT EXECUTE ON CopyRole TO [Standardbes ändern]
GO
--2010 02 12
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Name' and o.id = OBJECT_ID(N'[dbo].ProductionBonus'))
BEGIN
	ALTER TABLE ProductionBonus ADD Name VARCHAR(30)
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Name' and o.id = OBJECT_ID(N'[dbo].RoleBonus'))
BEGIN
	ALTER TABLE RoleBonus ADD Name VARCHAR(30)
END
--2010 02 16
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TimeAccountId' and o.id = OBJECT_ID(N'[dbo].Status'))
BEGIN
	ALTER TABLE Status ADD TimeAccountId INT
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ReportType' and o.id = OBJECT_ID(N'[dbo].[Vorlagen]'))
BEGIN
	ALTER TABLE dbo.Vorlagen ADD ReportType INT 
	exec ('UPDATE Vorlagen SET ReportType = (SELECT MAX(ReportType) FROM ReportTemplate  WHERE ReportTemplate.TemplateId=Vorlagen.VorlagenID   ) WHERE  ReportType IS NULL')
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ModulGroupId' and o.id = OBJECT_ID(N'[dbo].[CashCommand]'))
BEGIN
	ALTER TABLE dbo.CashCommand ADD ModulGroupId INT 
	exec ('UPDATE CashCommand SET ModulGroupId = 1')
	exec ('ALTER TABLE CashCommand ADD CONSTRAINT DF_CashCommand_ModulGruppeID DEFAULT 0 FOR ModulGroupId')
END
GO
--201002
--Reperatur Sortfeld PersAdresse 
IF NOT EXISTS (SELECT *  FROM dbo.sysobjects 	WHERE id = OBJECT_ID(N'[dbo].[DF_PersAdresse_Sort]'))
BEGIN	
	UPDATE PersAdresse SET Sort = 10 WHERE Sort is null
	DECLARE @PersId INT,@PersIdM INT,  @AdressID INT, @Sort INT
	DECLARE adress CURSOR
	FOR SELECT  PersNr, AdressID FROM PersAdresse ORDER BY PersNr, sort
	OPEN adress
	FETCH NEXT FROM adress INTO  @PersId, @AdressID
	SET @PersIdM =-99
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @PersIdM <> @PersId 
		BEGIN
			SET @PersIdM = @PersId
			SET @Sort = 0
		END
		UPDATE PersAdresse SET Sort = @Sort  WHERE AdressID = @AdressID
		SET @Sort = @Sort + 1
		FETCH NEXT FROM adress INTO  @PersId, @AdressID
	END
	CLOSE adress
	DEALLOCATE adress
	IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PersAdresse]')  AND name = 'PersNr_Sort')
		DROP Index PersAdresse.[PersNr_Sort]
	ALTER TABLE PersAdresse ALTER COLUMN Sort TINYINT NOT NULL
	ALTER TABLE PersAdresse  ADD CONSTRAINT DF_PersAdresse_Sort	DEFAULT 0 FOR Sort
	CREATE UNIQUE NONCLUSTERED INDEX IX_PersNr_Sort ON dbo.PersAdresse(PersNr,	Sort) ON [PRIMARY]
END
go

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbCashCommand'))
BEGIN
	DROP VIEW [dbo].AbCashCommand
END
GO
CREATE VIEW [dbo].[AbCashCommand]
AS 
SELECT  cc.*  FROM  CashCommand  AS cc WHERE cc.ModulGroupId IN
	   (SELECT UserGruppe.GruppeID 
		FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 7)
WITH CHECK OPTION
GO
GRANT SELECT ON [dbo].AbCashCommand TO public
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCashCommand_Update]'))
BEGIN
	DROP VIEW [dbo].AbCashCommand_Update
END
GO
CREATE VIEW [dbo].[AbCashCommand_Update]
AS 
SELECT  cc.*  FROM  CashCommand  AS cc WHERE cc.ModulGroupId IN
	   (SELECT UserGruppe.GruppeID 
		FROM UserGruppe 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 ON [dbo].AbCashCommand_Update TO Public
GRANT DELETE ON [dbo].AbCashCommand_Update TO Public
GRANT INSERT ON [dbo].AbCashCommand_Update TO Public
GRANT UPDATE ON [dbo].AbCashCommand_Update TO Public
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCashCommandPos]'))
BEGIN
	DROP VIEW [dbo].[AbCashCommandPos]
END
GO
CREATE VIEW [dbo].[AbCashCommandPos]
AS 
SELECT  ccp.*  FROM  CashCommandPos  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)
WITH CHECK OPTION
GO
GRANT SELECT ON [dbo].AbCashCommandPos TO public
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCashCommandPos_Update]'))
BEGIN
	DROP VIEW [dbo].[AbCashCommandPos_Update]
END
GO
CREATE VIEW [dbo].[AbCashCommandPos_Update]
AS 
SELECT  ccp.*  FROM  CashCommandPos  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 ON [dbo].AbCashCommandPos_Update TO Public
GRANT DELETE ON [dbo].AbCashCommandPos_Update TO Public
GRANT INSERT ON [dbo].AbCashCommandPos_Update TO Public
GRANT UPDATE ON [dbo].AbCashCommandPos_Update TO Public

GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbPersStatus'))
BEGIN
	DROP VIEW [dbo].AbPersStatus
END
GO
CREATE VIEW [dbo].[AbPersStatus]
AS 
SELECT  sr.*  FROM  StatusZeitR  AS sr INNER JOIN PersH AS p ON sr.PersNr=p.PersNr WHERE p.Besitzer IN
	   (SELECT UserGruppe.GruppeID 
		FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 8)
WITH CHECK OPTION
go
GRANT SELECT ON [dbo].AbPersStatus TO Public
GRANT DELETE ON [dbo].AbPersStatus TO Public
GRANT INSERT ON [dbo].AbPersStatus TO Public
GRANT UPDATE ON [dbo].AbPersStatus TO Public
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbPersStatus_Update'))
BEGIN
	DROP VIEW [dbo].AbPersStatus_Update
END
GO
CREATE VIEW [dbo].AbPersStatus_Update
AS 
SELECT  sr.*  FROM  StatusZeitR  AS sr  WHERE sr.Persnr IN
	   (SELECT p.PersNr
		FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid INNER JOIN PersH AS p ON UserGruppe.GruppeID = p.Besitzer
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 8 AND UserGruppe.Schreiben=1)
WITH CHECK OPTION
Go
GRANT SELECT ON [dbo].AbPersStatus_Update TO Public
GRANT DELETE ON [dbo].AbPersStatus_Update TO Public
GRANT INSERT ON [dbo].AbPersStatus_Update TO Public
GRANT UPDATE ON [dbo].AbPersStatus_Update TO Public
GO


IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsNotVisible' and o.id = OBJECT_ID(N'[dbo].[AuffDienstplanArten]'))
BEGIN
	ALTER TABLE dbo.AuffDienstplanArten ADD IsNotVisible BIT 
	exec ('UPDATE AuffDienstplanArten SET IsNotVisible = 0')
	exec ('ALTER TABLE AuffDienstplanArten ALTER COLUMN IsNotVisible BIT NOT NULL')
	exec ('ALTER TABLE AuffDienstplanArten ADD CONSTRAINT DF_AuffDienstplanArten_IsNotVisible DEFAULT 0 FOR IsNotVisible')
	
	
	exec ('INSERT INTO UserGruppe (Userid,GruppeID,BerechtigungsbereichID,schreiben)
	SELECT p.Userid,1,8,1 from [dbo].[sysusers] AS u 
					INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
					INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
					INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
				WHERE g.name = ''UrlaubSchreiben''')
				
	exec ('INSERT INTO UserGruppe (Userid,GruppeID,BerechtigungsbereichID,schreiben)
		SELECT p.Userid,1,8,0 from [dbo].[sysusers] AS u 
						INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
						INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
						INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
					WHERE g.name = ''Soli Urlaub L''	AND u.name NOT IN (SELECT  u.name from [dbo].[sysusers] AS u 
						INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
						INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
					WHERE g.name = ''UrlaubSchreiben'')')	 	
					
	exec ('INSERT INTO UserGruppe (Userid,GruppeID,BerechtigungsbereichID,schreiben)
	SELECT p.Userid,400,8,1 from [dbo].[sysusers] AS u 
					INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
					INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
					INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
				WHERE g.name = ''ChorAdmin''')	
				
	exec ('INSERT INTO UserGruppe (Userid,GruppeID,BerechtigungsbereichID,schreiben)
	SELECT p.Userid,1,7,1 from [dbo].[sysusers] AS u 
					INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
					INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
					INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
				WHERE g.name = ''CashCommandWrite''')	
	
				
	exec ('UPDATE AufführgTabelle SET [status] = 10 WHERE [status] IS NULL')
	exec ('ALTER TABLE AufführgTabelle ALTER COLUMN [status] SMALLINT NOT NULL')
	exec ('ALTER TABLE AufführgTabelle ADD CONSTRAINT DF_Activity_Status DEFAULT 10 FOR [status]')
		
	exec ('UPDATE AufführgTabelle SET [gesperrt] = 0 WHERE [gesperrt] IS NULL')
	exec ('ALTER TABLE AufführgTabelle ALTER COLUMN [gesperrt] BIT NOT NULL')	
END
Go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[PublicStatus]'))
BEGIN
	DROP VIEW [dbo].PublicStatus
END
GO
--Kollektive und Anwesende
CREATE VIEW [dbo].PublicStatus
AS
SELECT			st.*,
				pk.AdressArt,
				P.Nachname, P.Suchname
FROM			StatusZeitR st
	INNER JOIN  PersH			AS P	ON st.PersNr = P.PersNr
	INNER JOIN  PersKat			AS pk	ON P.PersKatNr = pk.PersKatNr
	INNER JOIN  [Status]		AS s	ON st.StatusID = s.StatusID
WHERE    
	pk.AdressArt BETWEEN 100 AND 200 OR s.StatusArt>= 20
GO
GRANT SELECT ON [dbo].PublicStatus TO Public
GO
-- 2010-02-25
-- Größe der Auff-Bemerkungen auf 100 (die kurzen)
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BemKurz' AND o.id = OBJECT_ID(N'[dbo].XHDelAufführg') AND c.prec < 100)
BEGIN
	ALTER TABLE XHDelAufführg ALTER COLUMN BemKurz VARCHAR(100)
	Print 'BemKurz geändert'
END
GO

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BemKurz2' AND o.id = OBJECT_ID(N'[dbo].XHDelAufführg') AND c.prec < 100)
BEGIN
	ALTER TABLE XHDelAufführg ALTER COLUMN BemKurz2 VARCHAR(100)
	Print 'BemKurz2 geändert'
END
GO

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BemKurz' AND o.id = OBJECT_ID(N'[dbo].AufführgTabelle') AND c.prec < 100)
BEGIN
	ALTER TABLE AufführgTabelle ALTER COLUMN BemKurz VARCHAR(100)
	Print 'BemKurz geändert'
END
GO

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BesBem' AND o.id = OBJECT_ID(N'[dbo].XHDelBesetzung') AND c.prec < 100)
BEGIN
	ALTER TABLE XHDelBesetzung ALTER COLUMN BesBem VARCHAR(100)
	Print 'BesBem geändert'
END
GO

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BemKurz2' AND o.id = OBJECT_ID(N'[dbo].AufführgTabelle') AND c.prec < 100)
BEGIN
	ALTER TABLE AufführgTabelle ALTER COLUMN BemKurz2 VARCHAR(100)
	Print 'BemKurz2 geändert'
END
GO

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'FtBez' AND o.id = OBJECT_ID(N'[dbo].Feiertage') AND c.prec < 50)
BEGIN
	ALTER TABLE Feiertage ALTER COLUMN FtBez VARCHAR(50)
	Print 'FtBez geändert'
END
GO
-- 2010-03-02 Nicht gesetzte UserGruppen auf Jeder setzen
UPDATE UserPw SET PriGruppeID = -1 WHERE UserPw.PriGruppeID IS NULL OR UserPw.PriGruppeID = 0
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ZRkurz' AND o.id = OBJECT_ID(N'[dbo].zr') AND c.prec < 10)
BEGIN
	UPDATE Zr set zrkurz = ' ' WHERE  zrkurz IS NULL
	ALTER TABLE zr ALTER COLUMN ZRkurz VARCHAR(10) NOT NULL
	Print 'WertText geändert'
END



IF NOT 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]'))
BEGIN
	ALTER TABLE dbo.AufführgDetails ADD CostUnitId INT 
END
go
	DropIndexByTable 'PersH' 
	go
	DropIndexByTable 'AdressSpalte'
	go
	DropIndexByTable 'AuffTypen' 
	go
	DropIndexByTable 'AufR' 
	go
	DropIndexByTable 'BesetzungTabelle'
	go 
	DropIndexByTable 'BesRepertoire' 
	go
	DropIndexByTable 'PersAgentur'
	go
	DropIndexByTable 'Fahrplan'
	go

go
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Suchname' AND o.id = OBJECT_ID(N'[dbo].Persh') AND c.prec < 20)
BEGIN

	UPDATE Persh set Suchname = ISNULL(Left(Nachname,20),PersNR) WHERE  Suchname IS NULL
	ALTER TABLE Persh ALTER COLUMN Suchname VARCHAR(20) NOT NULL
	Print 'WertText geändert'
END
go
CREATE INDEX IX_Besitzer ON dbo.PersH (Besitzer) ON [PRIMARY]
go
CREATE INDEX IX_PersKatNr ON dbo.PersH (PersKatNr) ON [PRIMARY]	
go
CREATE INDEX IX_Suchname ON dbo.PersH (Suchname) ON [PRIMARY]			
GO
CREATE INDEX IX_AdressPlanID ON dbo.AdressSpalte (AdressPlanID) ON [PRIMARY]			
GO
CREATE INDEX IX_KatNr ON dbo.AuffTypen (KatNr) ON [PRIMARY]		
Go
ALTER TABLE dbo.AuffTypen ADD CONSTRAINT [UQ_AuffTBez] UNIQUE NONCLUSTERED (AuffTBez) ON [PRIMARY]
GO
CREATE INDEX IX_AboNr ON dbo.AufR (AboNr) ON [PRIMARY]	
GO
CREATE INDEX IX_AuffNr ON dbo.AufR (AuffNr) ON [PRIMARY]	
GO
CREATE UNIQUE INDEX IX_AuffNr_AboNr ON dbo.AufR (AuffNr,AboNr) ON [PRIMARY]	
go
CREATE INDEX IX_AuffNr ON dbo.BesetzungTabelle (AuffNr) ON [PRIMARY]	
go
CREATE INDEX IX_PersNr ON dbo.BesetzungTabelle (PersNr) ON [PRIMARY]	
go
CREATE INDEX IX_RolleId ON dbo.BesetzungTabelle (RolleId) ON [PRIMARY]	
go
CREATE INDEX IX_PersNr ON dbo.BesRepertoire (PersNr) ON [PRIMARY]	
go
CREATE INDEX IX_RolleId ON dbo.BesRepertoire (RolleId) ON [PRIMARY]	
go
CREATE INDEX IX_RepArt ON dbo.BesRepertoire (RepArt) ON [PRIMARY]	
go
CREATE UNIQUE INDEX IX_PersNr_RolleId ON dbo.BesRepertoire (PersNr,RolleId) ON [PRIMARY]	
go
CREATE INDEX IX_PersNr ON dbo.PersAgentur (PersNr) ON [PRIMARY]	
go
CREATE INDEX IX_ChildPersNr ON dbo.PersAgentur (ChildPersNr) ON [PRIMARY]	
go
DropIndexByTable 'Fahrplan'
go
CREATE INDEX IX_Gruppe ON dbo.Fahrplan (Gruppe) ON [PRIMARY]	
go
CREATE INDEX IX_AuffNr ON dbo.Fahrplan (AuffNr) ON [PRIMARY]
go
DropIndexByTable 'Kosten_Aufführg'
go	
CREATE INDEX IX_AuffNr ON dbo.Kosten_Aufführg (AuffNr) ON [PRIMARY]
go	
CREATE INDEX IX_KostenID ON dbo.Kosten_Aufführg (KostenID) ON [PRIMARY]
go
DropIndexByTable 'Kosten_Stück'
go	
CREATE INDEX IX_Snr ON dbo.Kosten_Stück (Snr) ON [PRIMARY]
go	
CREATE INDEX IX_KostenID ON dbo.Kosten_Stück (KostenID) ON [PRIMARY]
go
DropIndexByTable 'Land'
go
--Doppelte Einträge entfernen
DELETE FROM AnredeInternational WHERE LandID IN (select MAX(Landid) from land group by land having COUNT(*) > 1)
DELETE FROM AnredeInternational WHERE LandID IN (select MAX(Landid) from land group by land having COUNT(*) > 1)
DELETE FROM Land WHERE LandID IN (select MAX(Landid) from land group by land having COUNT(*) > 1)
DELETE FROM Land WHERE LandID IN (select MAX(Landid) from land group by land having COUNT(*) > 1)
Go
ALTER TABLE dbo.Land ADD CONSTRAINT [UQ_Land] UNIQUE NONCLUSTERED (Land) ON [PRIMARY]	


go
DropIndexByTable 'PersonalDetails'
go
DropIndexByTable 'PersonalNotizen'
go	
CREATE INDEX IX_PersNr ON dbo.PersonalNotizen (PersNr) ON [PRIMARY]	
go
DropIndexByTable 'Ring'
go	
CREATE INDEX IX_SpZNr ON dbo.Ring (SpZNr) ON [PRIMARY]	
go	
CREATE INDEX IX_ZuAbo ON dbo.Ring (ZuAbo) ON [PRIMARY]	
go	
CREATE Unique INDEX IX_ZuAbo_spzNr ON dbo.Ring (ZuAbo,SpzNr) ON [PRIMARY]	
go
DropIndexByTable 'ProductionBonus'
go	
CREATE INDEX IX_ProductionId ON dbo.ProductionBonus (ProductionId) ON [PRIMARY]	
go
DropIndexByTable 'RoleBonus'
go	
CREATE INDEX IX_RoleId ON dbo.RoleBonus (RoleId) ON [PRIMARY]	
go	
CREATE INDEX IX_BonusId ON dbo.RoleBonus (BonusId) ON [PRIMARY]	
go	
CREATE INDEX IX_ContractTypeId ON dbo.RoleBonus (ContractTypeId) ON [PRIMARY]
go
DropIndexByTable 'StückeDetails'	
go
DropIndexByTable 'StückeSPZ'
go	
CREATE INDEX IX_Snr ON dbo.StückeSPZ (snr) ON [PRIMARY]	
go	
CREATE INDEX IX_SPZNR ON dbo.StückeSPZ (SPZNR) ON [PRIMARY]	
go	
CREATE UNIQUE INDEX IX_StückeSPZID ON dbo.StückeSPZ (StückeSPZID) ON [PRIMARY]	
go
DropIndexByTable 'StückeTeil'
go	
CREATE INDEX IX_Snr ON dbo.StückeTeil (Snr) ON [PRIMARY]	
go	
CREATE INDEX IX_SnrTeil ON dbo.StückeTeil (SnrTeil) ON [PRIMARY]
go	
DELETE FROM StückeTeil WHERE StückeTeilID IN (SELECT MAX(StückeTeilID) FROM StückeTeil GROUP BY Snr, SnrTeil HAVING Count(*) >1)
DELETE FROM StückeTeil WHERE StückeTeilID IN (SELECT MAX(StückeTeilID) FROM StückeTeil GROUP BY Snr, SnrTeil HAVING Count(*) >1)
DELETE FROM StückeTeil WHERE StückeTeilID IN (SELECT MAX(StückeTeilID) FROM StückeTeil GROUP BY Snr, SnrTeil HAVING Count(*) >1)
go
CREATE UNIQUE INDEX IX_Snr_SnrTeil ON dbo.StückeTeil (Snr,SnrTeil) ON [PRIMARY]
go
DropIndexByTable 'TimeAccountUsage'
go	
CREATE INDEX IX_ContractId ON dbo.TimeAccountUsage (ContractId) ON [PRIMARY]
go	
DropIndexByTable 'Vertrag'
go	
CREATE INDEX IX_PersNr ON dbo.Vertrag (PersNr) ON [PRIMARY]	
go	
CREATE INDEX IX_VorlagenID ON dbo.Vertrag (VorlagenID) ON [PRIMARY]	
go	
CREATE INDEX IX_vVon ON dbo.Vertrag (vVon) ON [PRIMARY]	
go	
CREATE INDEX IX_vBis ON dbo.Vertrag (vBis) ON [PRIMARY]	
go
DropIndexByTable 'StatusZeitR'
go	
CREATE INDEX IX_PersNr ON dbo.StatusZeitR (PersNr) ON [PRIMARY]	
go	
CREATE INDEX IX_StatusID ON dbo.StatusZeitR (StatusID) ON [PRIMARY]	
go	
CREATE INDEX IX_Status ON dbo.StatusZeitR ([Status]) ON [PRIMARY]	
go	
CREATE INDEX IX_Von ON dbo.StatusZeitR (Von) ON [PRIMARY]	
go	
CREATE INDEX IX_Bis ON dbo.StatusZeitR (Bis) ON [PRIMARY]	
go
DropIndexByTable 'ZulagenDienstplan'
go	
CREATE INDEX IX_DienstplanID ON dbo.ZulagenDienstplan (DienstplanID) ON [PRIMARY]	



DELETE FROM PersAgentur WHERE PersAgNr IN (select PersAgNr from PersAgentur as pa LEFT  JOIN PersH as p ON pa.ChildPersNr=p.Persnr   WHERE pa.ChildPersNr is null)
DELETE FROM PersAgentur WHERE PersAgNr IN (select PersAgNr from PersAgentur as pa LEFT  JOIN PersH as p ON pa.Persnr=p.Persnr   WHERE pa.ChildPersNr is null)
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_PersAgentur_Persh]') AND type = 'F')
	ALTER TABLE [dbo].PersAgentur ADD CONSTRAINT FK_PersAgentur_Persh FOREIGN KEY (PersNr)
	REFERENCES dbo.Persh (PersNr) 
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_PersAgentur_Persh_Child]') AND type = 'F')
	ALTER TABLE [dbo].PersAgentur ADD CONSTRAINT FK_PersAgentur_Persh_Child FOREIGN KEY (ChildPersNr)
	REFERENCES dbo.Persh (PersNr) 

go
REVOKE SELECT ON [dbo].StatusZeitR TO [Honorar-Daten ändern]
REVOKE SELECT ON [dbo].StatusZeitR TO [Honorar-Daten lesen]
GO
--2010-01-18
--Gesperrt und BesSort auf NOT NULL gesetzt und einen Defaultwert vergeben

UPDATE BesetzungTabelle SET Gesperrt = 0 WHERE Gesperrt IS NULL
UPDATE BesetzungTabelle SET BesSort = 0 WHERE BesSort IS NULL

go
dbo.DropDefault 'BesetzungTabelle','Bessort'
go
ALTER TABLE BesetzungTabelle ALTER COLUMN BesSort INT NOT NULL
go

go	
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_BesetzungTabelle_BesSort]'))
BEGIN
	ALTER TABLE BesetzungTabelle ADD CONSTRAINT DF_BesetzungTabelle_BesSort DEFAULT 0 FOR BesSort
END
GO


dbo.DropDefault 'BesetzungTabelle','Gesperrt'
ALTER TABLE BesetzungTabelle ALTER COLUMN Gesperrt BIT NOT NULL
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_BesetzungTabelle_Gesperrt]'))
	BEGIN
		ALTER TABLE BesetzungTabelle ADD CONSTRAINT DF_BesetzungTabelle_Gesperrt DEFAULT 0 FOR Gesperrt
	END
go


dbo.DropDefault 'BesetzungStdSoliTabelle','Bessort'
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_BesetzungStdSoliTabelle_Bessort]'))
	BEGIN
		ALTER TABLE BesetzungStdSoliTabelle ADD CONSTRAINT DF_BesetzungStdSoliTabelle_Bessort DEFAULT 0 FOR Bessort
	END
go 


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ShortName' and o.id = OBJECT_ID(N'[dbo].QualificationCategory'))
BEGIN
	ALTER TABLE QualificationCategory ADD ShortName VARCHAR(6) NULL
	ALTER TABLE Qualification ADD ShortName VARCHAR(6) NULL
	ALTER TABLE RollenLtg ADD FixAbId INT NULL
END	
go
-- 2010-04-01
-- Fremdschlüssel für Spalte BankAccountId in CashCommand hinzugefügt (WI #848)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_CashCommand_BankAccount]') AND type = 'F')
ALTER TABLE [dbo].[CashCommand] WITH NOCHECK ADD CONSTRAINT FK_CashCommand_BankAccount FOREIGN KEY([BankAccountId])
REFERENCES [dbo].[BankAccount] ([BankAccountId])
Go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_RollenLtg_Ab]') AND type = 'F')
ALTER TABLE [dbo].[RollenLtg] WITH NOCHECK ADD CONSTRAINT FK_RollenLtg_Ab FOREIGN KEY([FixAbId])
REFERENCES [dbo].[Ab] ([AbId])
GO

--2010-04-06
--Aufräumen der CountDowns
UPDATE BesetzungStd
SET CountDownId = NULL
WHERE CountDownId = 0

DELETE FROM BesetzungTabelle WHERE BesetzungTabelle.AuffTechAufgabeID IN(
SELECT AuffTechAufgabeID FROM AuffTechAufgabe WHERE RolleID IN (
SELECT BesetzungStd.ID FROM BesetzungStd WHERE CountDownId IN(
	SELECT DISTINCT(BS.CountDownId) FROM BesetzungStd AS BS
		LEFT JOIN CountDown AS CD ON BS.CountDownId = CD.CountDownID
	WHERE BS.CountDownId IS NOT NULL AND CD.CountDownID IS NULL)))
	
DELETE FROM AuffTechAufgabe WHERE RolleID IN (
SELECT BesetzungStd.ID FROM BesetzungStd WHERE CountDownId IN(
	SELECT DISTINCT(BS.CountDownId) FROM BesetzungStd AS BS
		LEFT JOIN CountDown AS CD ON BS.CountDownId = CD.CountDownID
	WHERE BS.CountDownId IS NOT NULL AND CD.CountDownID IS NULL))
	
DELETE FROM BesRepertoire WHERE BesRepertoire.RolleID IN(
	SELECT BesetzungStd.ID FROM BesetzungStd WHERE CountDownId IN(
	SELECT DISTINCT(BS.CountDownId) FROM BesetzungStd AS BS
		LEFT JOIN CountDown AS CD ON BS.CountDownId = CD.CountDownID
	WHERE BS.CountDownId IS NOT NULL AND CD.CountDownID IS NULL))
	
DELETE FROM BesetzungTabelle WHERE RolleID IN (
SELECT ID FROM BesetzungStd WHERE CountDownId IN(
	SELECT DISTINCT(BS.CountDownId) FROM BesetzungStd AS BS
		LEFT JOIN CountDown AS CD ON BS.CountDownId = CD.CountDownID
	WHERE BS.CountDownId IS NOT NULL AND CD.CountDownID IS NULL))
	
	
DELETE FROM BesetzungStd WHERE CountDownId IN(
SELECT DISTINCT(BS.CountDownId) FROM BesetzungStd AS BS
		LEFT JOIN CountDown AS CD ON BS.CountDownId = CD.CountDownID
	WHERE BS.CountDownId IS NOT NULL AND CD.CountDownID IS NULL)
	
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_BesetzungStd_CountDown]') AND type = 'F')
ALTER TABLE dbo.BesetzungStd ADD CONSTRAINT	FK_BesetzungStd_CountDown FOREIGN KEY ([CountDownId])
REFERENCES dbo.CountDown ([CountDownId])  


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[AllocationGroup]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].AllocationGroup(
		AllocationGroupId INT IDENTITY(1,1) NOT NULL,
		AllocationGroupNo VarChar(6) NOT NULL,
		AllocationGroupDescription VarChar(30) NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		CONSTRAINT [PK_AllocationGroupId] PRIMARY KEY CLUSTERED (AllocationGroupId ASC)WITH FILLFACTOR = 90 ON [PRIMARY],
	) ON [PRIMARY]
END
go
GRANT SELECT ON [dbo].AllocationGroup TO Public
GRANT DELETE ON [dbo].AllocationGroup TO [Stammdaten ändern]
GRANT INSERT ON [dbo].AllocationGroup TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].AllocationGroup TO [Stammdaten ändern]
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AllocationGroupId' and o.id = OBJECT_ID(N'[dbo].CashCommand'))
BEGIN
	ALTER TABLE CashCommand ADD AllocationGroupId INT NULL
END	

--UPDATE CashCommand SET AllocationGroupId = 4 WHERE CashCommand.ModulGroupId = 1 AND AllocationGroupId IS NULL 
go
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_CashCommand_AllocationGroup]') AND type = 'F')
ALTER TABLE [dbo].[CashCommand] WITH NOCHECK ADD CONSTRAINT FK_CashCommand_AllocationGroup FOREIGN KEY([AllocationGroupId])
REFERENCES [dbo].[AllocationGroup] ([AllocationGroupId])
go

--2010-04-06
--Aufräumen der CountDowns
UPDATE BesetzungStd
SET CountDownId = NULL
WHERE CountDownId = 0

DELETE FROM BesetzungTabelle WHERE BesetzungTabelle.AuffTechAufgabeID IN(
SELECT AuffTechAufgabeID FROM AuffTechAufgabe WHERE RolleID IN (
SELECT BesetzungStd.ID FROM BesetzungStd WHERE CountDownId IN(
	SELECT DISTINCT(BS.CountDownId) FROM BesetzungStd AS BS
		LEFT JOIN CountDown AS CD ON BS.CountDownId = CD.CountDownID
	WHERE BS.CountDownId IS NOT NULL AND CD.CountDownID IS NULL)))
	
DELETE FROM AuffTechAufgabe WHERE RolleID IN (
SELECT BesetzungStd.ID FROM BesetzungStd WHERE CountDownId IN(
	SELECT DISTINCT(BS.CountDownId) FROM BesetzungStd AS BS
		LEFT JOIN CountDown AS CD ON BS.CountDownId = CD.CountDownID
	WHERE BS.CountDownId IS NOT NULL AND CD.CountDownID IS NULL))
	
DELETE FROM BesRepertoire WHERE BesRepertoire.RolleID IN(
	SELECT BesetzungStd.ID FROM BesetzungStd WHERE CountDownId IN(
	SELECT DISTINCT(BS.CountDownId) FROM BesetzungStd AS BS
		LEFT JOIN CountDown AS CD ON BS.CountDownId = CD.CountDownID
	WHERE BS.CountDownId IS NOT NULL AND CD.CountDownID IS NULL))
	
DELETE FROM BesetzungTabelle WHERE RolleID IN (
SELECT ID FROM BesetzungStd WHERE CountDownId IN(
	SELECT DISTINCT(BS.CountDownId) FROM BesetzungStd AS BS
		LEFT JOIN CountDown AS CD ON BS.CountDownId = CD.CountDownID
	WHERE BS.CountDownId IS NOT NULL AND CD.CountDownID IS NULL))
	
	
DELETE FROM BesetzungStd WHERE CountDownId IN(
SELECT DISTINCT(BS.CountDownId) FROM BesetzungStd AS BS
		LEFT JOIN CountDown AS CD ON BS.CountDownId = CD.CountDownID
	WHERE BS.CountDownId IS NOT NULL AND CD.CountDownID IS NULL)
	
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_BesetzungStd_CountDown]') AND type = 'F')
ALTER TABLE dbo.BesetzungStd ADD CONSTRAINT	FK_BesetzungStd_CountDown FOREIGN KEY ([CountDownId])
REFERENCES dbo.CountDown ([CountDownId])  
go

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CastBonus]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].CastBonus(
		CastBonusId INT IDENTITY(1,1) NOT NULL,
		CastId INT NOT NULL,
		BonusId INT NOT NULL,
	--	Value REAL NOT NULL,
		Note VARCHAR(50) NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		CONSTRAINT [PK_CastBonusId] PRIMARY KEY CLUSTERED (CastBonusId ASC)WITH FILLFACTOR = 90 ON [PRIMARY],
		CONSTRAINT [FK_CastBonus_Cast] FOREIGN KEY([CastId]) REFERENCES [dbo].BesetzungTabelle ([Id]) ON DELETE CASCADE,
		CONSTRAINT [FK_CastBonus_Bonus] FOREIGN KEY([BonusId]) REFERENCES [dbo].Zulagen ([ZulagenNr]) 

	) ON [PRIMARY]
END
go
DropColumn  'CastBonus', 'Value'
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BonusValue' and o.id = OBJECT_ID(N'[dbo].CastBonus'))
BEGIN
	ALTER TABLE CastBonus ADD BonusValue MONEY NOT NULL DEFAULT(0)
END


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UQ_CastId_BonusId]') AND xtype = 'UQ')
ALTER TABLE dbo.CastBonus ADD CONSTRAINT [UQ_CastId_BonusId] UNIQUE NONCLUSTERED (CastId,BonusId) ON [PRIMARY]	


go
GRANT SELECT ON [dbo].CastBonus TO [Honorar-Daten ändern]
GRANT DELETE ON [dbo].CastBonus TO [Honorar-Daten ändern]
GRANT INSERT ON [dbo].CastBonus TO [Honorar-Daten ändern]
GRANT UPDATE ON [dbo].CastBonus TO [Honorar-Daten ändern]
GO

GRANT SELECT ON [dbo].CastBonus TO [Honorar-Daten lesen]
go

GRANT SELECT ON [dbo].Zulagen TO [public]
go

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PeriodNotes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].PeriodNotes(
		[PeriodNoteId] INT IDENTITY(1,1) NOT NULL ,
		[Start] DATETIME NOT NULL,
		[End] DATETIME NOT NULL,
		[DepartmentId] INT NULL,
		[Note] TEXT NOT NULL,
		[WorkgroupId] INT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		CONSTRAINT [PK_PeriodNoteId] PRIMARY KEY CLUSTERED ([PeriodNoteId] ASC) ON [PRIMARY],
		CONSTRAINT [FK_PeriodNote_Department] FOREIGN KEY([DepartmentId]) REFERENCES [dbo].DienstplanArtenTabelle ([DienstplanArtenID]) ON DELETE CASCADE,
		CONSTRAINT [FK_PeriodNote_ABGruppe] FOREIGN KEY([WorkgroupId]) REFERENCES [dbo].ABGruppe ([ABGruppeId]) ON DELETE CASCADE,
	) ON [PRIMARY]
END
go
GRANT SELECT ON [dbo].PeriodNotes TO public
GRANT DELETE ON [dbo].PeriodNotes TO public
GRANT INSERT ON [dbo].PeriodNotes TO public
GRANT UPDATE ON [dbo].PeriodNotes TO public
go

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[IntervalTask]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].IntervalTask(
		[IntervalTaskId] INT IDENTITY(1,1) NOT NULL, --ID
		[IntervalName] VARCHAR(50) NOT NULL, -- Name des Intervalls
		[IntervalTyp] INT NOT NULL, --Täglich, Wöchentlich, Monatlich oder Jährlich
		[Interval] INT NOT NULL, --Alle x Tage, Wochen, Monate oder Jahre
		[PlanedStart] DATETIME NOT NULL, --Erste geplante einplanung des Intervalls
		[IntervalBoundTyp] INT NOT NULL, --Bindungs-Typ
		[EndCondition] INT NULL, --Bedingung für das Enden des Intervalls
		[EndConditionValue] VARCHAR(30) NULL,--Wert für das Ende
		[PlaningDuration] INT NOT NULL,
		[TaskId] INT NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		CONSTRAINT [PK_IntervalTaskId] PRIMARY KEY CLUSTERED ([IntervalTaskId] ASC) ON [PRIMARY],
		CONSTRAINT [FK_InteralTask_AuffTechAufgabe] FOREIGN KEY ([TaskId]) REFERENCES [dbo].AuffTechAufgabe ([AuffTechAufgabeID]) ON DELETE CASCADE,
	) ON [PRIMARY]
	ALTER TABLE dbo.AuffTechAufgabe ADD IntervalId INT NULL
	ALTER TABLE dbo.AuffTechAufgabe ADD CONSTRAINT	FK_AuffTechAufgabe_IntervalTask FOREIGN KEY ([IntervalId])
	REFERENCES dbo.IntervalTask ([IntervalTaskId])  
END
go
----2010 05 04 
-- IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CastReplacement]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
--BEGIN
--	CREATE TABLE [dbo].CastReplacement(
--		CastReplacementId INT IDENTITY(1,1) NOT NULL, --ID
--		OldCastId INT NULL,
--		NewCastId INT NULL,
--		Note Text,
--		[LM] DATETIME NOT NULL,
--		[UM] INT NOT NULL,
--		[LC] DATETIME NOT NULL,
--		[UC] INT NOT NULL,
--		CONSTRAINT [PK_CastReplacementId] PRIMARY KEY CLUSTERED ([CastReplacementId] ASC) ON [PRIMARY],
--		CONSTRAINT [FK_CastReplacement_Cast_OldCastId] FOREIGN KEY ([OldCastId]) REFERENCES [dbo].BesetzungTabelle ([Id]),-- ON DELETE CASCADE,
--		CONSTRAINT [FK_CastReplacement_Cast_NewCastId] FOREIGN KEY ([NewCastId]) REFERENCES [dbo].BesetzungTabelle ([Id]) ON DELETE CASCADE,
--	) ON [PRIMARY] 
--END
--go
--GRANT SELECT ON [dbo].CastReplacement TO Public
--GRANT DELETE ON [dbo].CastReplacement TO Public
--GRANT INSERT ON [dbo].CastReplacement TO Public
--GRANT UPDATE ON [dbo].CastReplacement TO Public
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CastReplacement]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE CastReplacement
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Note' and o.id = OBJECT_ID(N'[dbo].VertragsVorlagen'))
BEGIN
	ALTER TABLE VertragsVorlagen ADD Note Text NULL
END 
go
GRANT SELECT ON [dbo].IntervalTask TO public
GRANT DELETE ON [dbo].IntervalTask TO public
GRANT INSERT ON [dbo].IntervalTask TO public
GRANT UPDATE ON [dbo].IntervalTask TO public
go

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'FilterSettings' and o.id = OBJECT_ID(N'[dbo].HDMVorlagen'))
BEGIN
	ALTER TABLE HDMVorlagen ADD FilterSettings Text
END	

-- 2010-05-03 Neuer View für die DailyTask-Aktivitäten
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].IntervalTaskActivities'))
BEGIN
	DROP VIEW [IntervalTaskActivities]
END
GO
			
CREATE VIEW [dbo].[IntervalTaskActivities]
AS
SELECT			act.*
FROM			AufführgTabelle act 
WHERE			act.SNr = -2 AND act.Datum <= '19000101'
GO
GRANT SELECT ON [dbo].[IntervalTaskActivities] TO public
GRANT DELETE ON [dbo].[IntervalTaskActivities] TO public
GRANT INSERT ON [dbo].[IntervalTaskActivities] TO public
GRANT UPDATE ON [dbo].[IntervalTaskActivities] TO public
go


IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'FromDifferentTimeAccountId' and o.id = OBJECT_ID(N'[dbo].ZeitkontenMonat'))
BEGIN
	ALTER TABLE ZeitkontenMonat ADD FromDifferentTimeAccountId INT NULL 
END	
go

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ZeitkontenMonat_ZeitkontenDiff]') AND type = 'F')
ALTER TABLE [dbo].[ZeitkontenMonat] WITH NOCHECK ADD CONSTRAINT FK_ZeitkontenMonat_ZeitkontenDiff FOREIGN KEY([FromDifferentTimeAccountId])
REFERENCES [dbo].[Zeitkonten] ([ZeitKtoNr])

go

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ZeitkontenMonat]')  AND name = 'iVertragsNrDatumDienstplanEintragArtId')
BEGIN

DROP Index ZeitkontenMonat.[iVertragsNrDatumDienstplanEintragArtId]

CREATE UNIQUE NONCLUSTERED INDEX IX_VertragsNr_ZeitktoNr_JahrMonat_ZmType_zmSort_FromDifferentTimeAccountId ON [dbo].[ZeitkontenMonat]
		(VertragsNr,
		ZeitktoNr,
		JahrMonat,
		ZmType,
		zmSort,
		FromDifferentTimeAccountId) ON [PRIMARY]
END		
go
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'OldPersonId' and o.id = OBJECT_ID(N'[dbo].XHDelBesetzung'))
BEGIN
	ALTER TABLE XHDelBesetzung ADD OldPersonId INT NULL 
END	

-- 2010-05-21
-- Spalte für das Anzeigen der Feiertagsausgleichsinformationen hinzufügen
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ShowHoildayBalanceInfo' and o.id = OBJECT_ID(N'[dbo].Rapport'))
BEGIN
	ALTER TABLE Rapport ADD ShowHoildayBalanceInfo BIT NOT NULL CONSTRAINT [DF_Rapport_ShowHoildayBalanceInfo] DEFAULT (0) 
END	
GO
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'JubileeModellId' and o.id = OBJECT_ID(N'[dbo].VertragsVorlagen'))
BEGIN
	ALTER TABLE VertragsVorlagen ADD JubileeModellId INT NULL
END	
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_UrlaubsberechnungsModell_VertragsVorlagen]') AND type = 'F')
ALTER TABLE dbo.VertragsVorlagen ADD CONSTRAINT	FK_UrlaubsberechnungsModell_VertragsVorlagen FOREIGN KEY	([UrlaubsberechnungsModellID])
REFERENCES dbo.UrlaubsberechnungsModell ([UrlaubsberechnungsModellID])  
GO
ALTER TABLE [dbo].VertragsVorlagen CHECK CONSTRAINT FK_UrlaubsberechnungsModell_VertragsVorlagen
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_UrlaubsberechnungsModell_VertragsVorlagen_JubileeModell]') AND type = 'F')
ALTER TABLE dbo.VertragsVorlagen ADD CONSTRAINT	FK_UrlaubsberechnungsModell_VertragsVorlagen_JubileeModell FOREIGN KEY	([JubileeModellId])
REFERENCES dbo.UrlaubsberechnungsModell ([UrlaubsberechnungsModellID])  
GO
ALTER TABLE [dbo].VertragsVorlagen CHECK CONSTRAINT FK_UrlaubsberechnungsModell_VertragsVorlagen_JubileeModell
    

GO
--2010-06-03
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Note' and o.id = OBJECT_ID(N'[dbo].BesetzungStd'))
BEGIN
	ALTER TABLE BesetzungStd ADD Note VARCHAR(250) 
END	
GO

-- 2010-06-07
--Spalte für den bürgelichen Vornamen hinzugefügt
-- Spalte für das Anzeigen der Feiertagsausgleichsinformationen hinzufügen
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CivilFirstName' and o.id = OBJECT_ID(N'[dbo].PersonalDetails'))
BEGIN
	ALTER TABLE PersonalDetails ADD CivilFirstName varchar(60) NULL
END	
GO
IF NOT EXISTS(SELECT * FROM RapportSpalte WHERE Ausgabe = 1)
BEGIN
INSERT INTO RapportSpalte (RID, Ausgabe, sort,LohnBez ) SELECT RID, 1,0, 'Az' FROM  Rapport
END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DeletePersonReference'))
BEGIN
	DROP PROCEDURE dbo.DeletePersonReference 
END
Go
Create PROCEDURE [dbo].[DeletePersonReference] (@personId int, @del int) AS 
DECLARE @conflictCounter int
SELECT @conflictCounter=0

DECLARE @conflictDescription varchar(1000)
SELECT @conflictDescription=''

DECLARE @Temp int
SELECT  @Temp=0
declare @CRLF char(2)
set @CRLF =  '|'/*char(10) + char(13)*/
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


/*  Tabelle Produktionsplan  */
IF (@del > 0) DELETE Produktionsplan  FROM Produktionsplan  WHERE PNr=@personId

/*  Bereich der Tabellen StatusZeitR  */
IF  (SELECT PERMISSIONS(OBJECT_ID('StatusZeitR'))&2)<>2     /*  Keine Updateberechtingung    */
BEGIN
	IF (SELECT Count(*) FROM StatusZeitR  WHERE PersNr=@personId) > 0  
	BEGIN 
		SELECT @conflictCounter=@conflictCounter+1
		SELECT @conflictDescription = @conflictDescription + 'Status'  + @CRLF
	END
END
ELSE
BEGIN
	IF (SELECT Count(*) FROM StatusZeitR  WHERE PersNr=@personId) > 0  
	BEGIN 
		IF (@del > 0)DELETE StatusZeitR  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

/*  Tabelle PersMasse  */
IF (@del > 0)DELETE FROM PersMasse WHERE PersNr=@personId
	
/* ------------------------------------Dispositionsbereich ende -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

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

/*  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  */
IF  (SELECT PERMISSIONS(OBJECT_ID('BesRepertoire'))&2)<>2     /*  Keine Updateberechtingung    */
BEGIN
	IF (SELECT Count(*) FROM BesRepertoire WHERE PersNr=@personId) > 0  
	BEGIN 
		SELECT @conflictCounter=@conflictCounter+1
		SELECT @conflictDescription = @conflictDescription + 'Repertoire '  + @CRLF
	END
END
ELSE
BEGIN
	IF (@del > 0) DELETE FROM BesRepertoire WHERE PersNr=@personId
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  */
IF  (SELECT PERMISSIONS(OBJECT_ID('AbPersonalNotizen_Update'))&2)<>2     /*  Keine Updateberechtingung    */
BEGIN
	IF(Select Count(*) FROM PersonalNotizen WHERE PersNr=@personId) > 0  
		BEGIN 
			SELECT @conflictCounter=@conflictCounter+1
			SELECT @conflictDescription = @conflictDescription + 'Notes'  + @CRLF
		END
END
ELSE
BEGIN
	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
END


/*  Tabelle ABPersKom_Update  */
IF  (SELECT PERMISSIONS(OBJECT_ID('ABPersKom_Update'))&2)<>2     /*  Keine Updateberechtingung    */
BEGIN
	IF(SELECT Count(*) FROM PersKom WHERE PersNr=@personId) > 0  
		BEGIN 
			SELECT @conflictCounter=@conflictCounter+1
			SELECT @conflictDescription = @conflictDescription + 'Contactdata'  + @CRLF
		END
END
ELSE
BEGIN
	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
END

/*  Tabelle ABPersAdresse_Update  */
IF  (SELECT PERMISSIONS(OBJECT_ID('ABPersAdresse_Update'))&2)<>2     /*  Keine Updateberechtingung    */
BEGIN
	IF(Select Count(*) FROM PersAdresse WHERE PersNr=@personId) > 0  
		BEGIN 
			SELECT @conflictCounter=@conflictCounter+1
			SELECT @conflictDescription = @conflictDescription + 'Adressdata'  + @CRLF
		END
END
ELSE
BEGIN
	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
END

/*  Tabelle AbPersZusatzDaten_Update  */
IF  (SELECT PERMISSIONS(OBJECT_ID('AbPersZusatzDaten_Update'))&2)<>2     /*  Keine Updateberechtingung    */
BEGIN
	IF(Select Count(*) FROM PersZusatzDaten WHERE PersNr=@personId) > 0  
		BEGIN 
			SELECT @conflictCounter=@conflictCounter+1
			SELECT @conflictDescription = @conflictDescription + 'Personal attribute'  + @CRLF
		END
END
ELSE
BEGIN
	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
END

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

SELECT @conflictCounter as ConflictCount,  @conflictDescription as ConflictDescription
RETURN @conflictCounter
GO

GRANT EXECUTE ON DeletePersonReference TO Public
GO

-- 2010-06-16
-- Rechte auf die XHDelBesetzung auf Public damit Balet diese ändern kann
-- TODO: Rechte sollten durch einen View geregelt werden 
GRANT DELETE ON XHDelBesetzung TO public
GRANT UPDATE ON XHDelBesetzung TO public
GRANT INSERT ON XHDelBesetzung TO public

GRANT DELETE ON BudgetItem TO CostsWrite
GRANT UPDATE ON BudgetItem TO CostsWrite
GRANT INSERT ON BudgetItem TO CostsWrite


GRANT DELETE ON CostUnit TO CostsWrite
GRANT UPDATE ON CostUnit TO CostsWrite
GRANT INSERT ON CostUnit TO CostsWrite

GRANT DELETE ON CostCenter TO CostsWrite
GRANT UPDATE ON CostCenter TO CostsWrite
GRANT INSERT ON CostCenter TO CostsWrite

-- 2010-07-05
-- Tabelle UserLicense für Lizenzverwaltung
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UserLicenses]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[UserLicenses](
	[UserLicenseId] [int] IDENTITY(1,1) NOT NULL,
	[UserId] [int] NOT NULL,
	[Product] [int] NOT NULL,
	[LicenseType] [int] NOT NULL,
	[LM] [datetime] NOT NULL,
	[UM] [int] NOT NULL,
	[LC] [datetime] NOT NULL,
	[UC] [int] NOT NULL,
	CONSTRAINT [PK_UserLicenses] PRIMARY KEY CLUSTERED ([UserLicenseId] ASC) ON [PRIMARY],
	CONSTRAINT [FK_UserLicenses_UserPw] FOREIGN KEY([UserId]) REFERENCES [dbo].[UserPw] ([UserID])		
) ON [PRIMARY]
END
GRANT SELECT ON UserLicenses TO Public
GRANT UPDATE ON UserLicenses TO SecurityAdmin
GRANT INSERT ON UserLicenses TO SecurityAdmin
GRANT DELETE ON UserLicenses TO SecurityAdmin
GO

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[UserLicenses]')  AND name = 'IX_UserLicenses_UserId_Product')
BEGIN
CREATE UNIQUE NONCLUSTERED INDEX [IX_UserLicenses_UserId_Product] ON [dbo].[UserLicenses] (
	[Product] ASC,
	[UserId] ASC
)ON [PRIMARY]
END
GO


-- 2010-06-24
-- Füllen der Spalte Sparte mit Standard-Wertn falls noch kein wert gewählt ist und
-- Setzen auf Not null
UPDATE Stücke Set Sparte = (SELECT min(id) FROM TagSparteSort WHERE id <> 0 and id <> 10) WHERE Sparte IS NULL
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Stücke_TagSparteSort]') AND type = 'F')
BEGIN
	UPDATE Stücke SET [Sparte] = (SELECT MAX(id) FROM TagSparteSort) WHERE [Sparte] NOT IN (SELECT id FROM TagSparteSort)
	ALTER TABLE dbo.Stücke ADD CONSTRAINT FK_Stücke_TagSparteSort FOREIGN KEY ([Sparte]) REFERENCES dbo.TagSparteSort ([Id]) 
	ALTER TABLE dbo.Stücke ALTER COLUMN [Sparte] INT NOT NULL
END		
GO
ALTER TABLE [dbo].Stücke CHECK CONSTRAINT FK_Stücke_TagSparteSort
Go
--Vorstellungs u. Probenplan hat keine Planart vergeben...
  UPDATE [Plan] SET PlanArt = 30 WHERE Planart IS NULL

GO
DropIndexByTable 'BesetzungStdSoliTabelle'
go
CREATE INDEX IX_RoleId ON dbo.BesetzungStdSoliTabelle (RolleId) ON [PRIMARY]	
go
CREATE INDEX IX_SeasonId ON dbo.BesetzungStdSoliTabelle (SpzNr) ON [PRIMARY]	
go
CREATE INDEX IX_PersId1 ON dbo.BesetzungStdSoliTabelle (Persnr1) ON [PRIMARY]	
go
CREATE INDEX IX_PersId2 ON dbo.BesetzungStdSoliTabelle (Persnr2) ON [PRIMARY]	
go
CREATE INDEX IX_PersId3 ON dbo.BesetzungStdSoliTabelle (Persnr3) ON [PRIMARY]	
go
CREATE INDEX IX_PersId4 ON dbo.BesetzungStdSoliTabelle (Persnr4) ON [PRIMARY]	
go
IF  EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'[dbo].[ISOYearWeek]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].ISOYearWeek
go
CREATE FUNCTION dbo.ISOYearWeek(@dtDate as DATETIME) RETURNS Char(7)
/*
** Return the ISO week of the year regardless of the DATEFIRST session setting.
*/
AS
BEGIN

DECLARE @intISOWeekdayNumber INT
DECLARE @dtThisThursday DATETIME
DECLARE @dtFirstOfThisThursdaysYear DATETIME
DECLARE @intISOWeekdayNumberOfFirstOfThisThursdaysYear INT
DECLARE @dtFirstThursdayOfYear DATETIME
DECLARE @intISOWeekNumber INT

   -- Get the ISO week day number (Monday = 1) for our date.
   SET @intISOWeekdayNumber = (((DATEPART(dw, @dtDate) - 1) + (@@DATEFIRST - 1)) % 7) + 1

   -- Get the date of the Thursday in this ISO week.
   SET @dtThisThursday = DATEADD(d,(4 - @intISOWeekdayNumber),@dtDate)

   -- Get the date of the 1st January for 'this Thursdays' year.
   SET @dtFirstOfThisThursdaysYear = CAST(CAST(YEAR(@dtThisThursday) AS CHAR(4)) + '-01-01' AS DATETIME)

   SET @intISOWeekdayNumberOfFirstOfThisThursdaysYear = (((DATEPART(dw, @dtFirstOfThisThursdaysYear) - 1) + (@@DATEFIRST - 1)) % 7) + 1

   -- Get the date of the first Thursday in 'this Thursdays' year.
   -- The year of which the ISO week is a part is the year of this date.     
   IF (@intISOWeekdayNumberOfFirstOfThisThursdaysYear in (1,2,3,4))
      SET @dtFirstThursdayOfYear = DATEADD(d,(4 - @intISOWeekdayNumberOfFirstOfThisThursdaysYear),@dtFirstOfThisThursdaysYear)
   ELSE
      SET @dtFirstThursdayOfYear = DATEADD(d,(4 - @intISOWeekdayNumberOfFirstOfThisThursdaysYear + 7),@dtFirstOfThisThursdaysYear)

   -- Work out how many weeks from the first Thursday to this Thursday.
   SET @intISOWeekNumber = DATEDIFF(d,@dtFirstThursdayOfYear,@dtThisThursday)/7+1
   
   RETURN cast(YEAR(@dtFirstOfThisThursdaysYear) as char(4))  + ' ' +  right(cast('0' as char(1)) + cast(@intISOWeekNumber as varchar(2)),2)

END
go
GRANT EXECUTE ON ISOYearWeek TO Public
go
GRANT DELETE ON BesetzungStdSoli TO ChorAdmin
GRANT UPDATE ON BesetzungStdSoli TO ChorAdmin
GRANT INSERT ON BesetzungStdSoli TO ChorAdmin

GO
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'OnlyRehersals' and o.id = OBJECT_ID(N'[dbo].StückeSPZ'))
BEGIN
	ALTER TABLE StückeSPZ ADD OnlyRehersals BIT NOT NULL DEFAULT(0)
END	
Go
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'co' AND o.id = OBJECT_ID(N'[dbo].PersAdresse') AND c.prec < 80)
BEGIN
	ALTER TABLE PersAdresse ALTER COLUMN co VARCHAR(80)
	Print 'WertText geändert'
END
go

IF NOT  EXISTS (SELECT * FROM BesetzungStd	WHERE ID = -1)
BEGIN
SET IDENTITY_INSERT BesetzungStd  ON
	INSERT INTO BesetzungStd (id, SNr,Rolle,Pos,Leporello,PresseSort,nameDrucken,StdVs,StdPro,RollenLtgID,GruppeID,DruckSteuerung,DruckStd ,Besitzer,Anzahl ) 
	VALUES  (-1,-1,'Repetitor',0,0,0,0,0,0,0,null,0,0,1,1)
	SET IDENTITY_INSERT BesetzungStd  OFF
END	
go

DropIndexByTable 'BesetzungStd'
GO

CREATE INDEX IX_Snr ON dbo.BesetzungStd (Snr) ON [PRIMARY]	
CREATE INDEX IX_Besitzer ON dbo.BesetzungStd (Besitzer) ON [PRIMARY]	
CREATE INDEX IX_RollenLtgID ON dbo.BesetzungStd (RollenLtgID) ON [PRIMARY]	
Go

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Pos' AND o.id = OBJECT_ID(N'[dbo].BesetzungStd') AND c.xtype <> 56)
BEGIN	
	EXECUTE sp_unbindefault N'dbo.BesetzungStd.Pos'
	 --ALTER TABLE [dbo].[BesetzungStd]  DROP CONSTRAINT DF_BesetzungStd_Pos
	DROP INDEX BesetzungStd.pos
	UPDATE BesetzungStd SET Pos = 0 WHERE Pos IS NULL
	ALTER TABLE BesetzungStd ALTER COLUMN Pos INT NOT NULL
	ALTER TABLE [dbo].BesetzungStd ADD CONSTRAINT DF_BesetzungStd_Pos DEFAULT (0) FOR [Pos]
	CREATE NONCLUSTERED INDEX [Pos] ON [dbo].[BesetzungStd]([Pos] ASC)
	Print 'WertText geändert'
END
GO


IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[BasicCastPublic]'))
BEGIN
	DROP VIEW [dbo].BasicCastPublic
END
GO
CREATE VIEW [dbo].BasicCastPublic
AS
SELECT  *
FROM    dbo.BesetzungStdSoliTabelle  
WHERE   ISNULL(Gesperrt,0) = 0
GO
GRANT SELECT ON BasicCastPublic TO Public
GRANT SELECT ON BesetzungStdSoliTabelle TO [Spielplan alles lesen]
GRANT SELECT ON BesetzungStdSoliTabelle TO [Spielplan ändern]
GO

--2010 04 15 Loggen der letzten Anmeldung
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'LastLoginDate' and o.id = OBJECT_ID(N'[dbo].UserPw'))
BEGIN
	ALTER TABLE UserPw ADD LastLoginDate DATETIME NULL
END	

IF  EXISTS (SELECT * FROM sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[LogLastLoginDate]')) DROP PROCEDURE [dbo].[LogLastLoginDate]
GO
CREATE PROCEDURE [dbo].[LogLastLoginDate] AS
BEGIN
	UPDATE UserPw SET LastLoginDate = GetDate() WHERE UserName = CURRENT_USER
END	
GO
GRANT EXECUTE ON LogLastLoginDate TO Public
GO
--2010-08-17
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DefaultApproveStatus' and o.id = OBJECT_ID(N'[dbo].Status'))
BEGIN
	ALTER TABLE [Status] ADD FormatSettings TEXT 
	ALTER TABLE [Status] ADD DefaultApproveStatus INT
END	
GO
--2010-08-17 Fehlende Referenz erstelt
UPDATE VertragPerso set StdABGruppeId = null WHERE StdABGruppeId NOT IN  (SELECT ABGruppeID FROM ABGruppe)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_VertragPerso_ABGruppe]') AND type = 'F')
ALTER TABLE [dbo].[VertragPerso]  WITH CHECK ADD  CONSTRAINT [FK_VertragPerso_ABGruppe] FOREIGN KEY([StdABGruppeId])
REFERENCES [dbo].[AbGruppe] ([ABGruppeId])
GO
ALTER TABLE [dbo].[VertragPerso] CHECK CONSTRAINT [FK_VertragPerso_ABGruppe]
GO

----2010-08-17 Jeden User in Gruppe Kontaktdaten Jeder
--INSERT INTO UserGruppe(GruppeID ,UserID,Schreiben,LM,UM,LC,UC,BerechtigungsbereichID,OptionsFlag)
--		SELECT -1, UserPw.UserID,0, '19000101',0,'19000101',0,0,0  FROM UserPw LEFT JOIN (SELECT * FROM UserGruppe WHERE BerechtigungsbereichID=0 AND GruppeID = -1) AS UG on UserPW.UserID=UG.UserID WHERE UG.UserGruppeID IS NULL

go
--2010-08-27 "falsche Daten" löschen 
DELETE FROM VertragRolle WHERE VertragsNr IN (SELECT VertragsNr FROM Vertrag WHERE Vertrag.PersNr = 260 AND Vertrag.VertragsNr <> 0)
DELETE FROM Vertrag WHERE Vertrag.PersNr = 260 AND Vertrag.VertragsNr <> 0
DELETE FROM BesetzungTabelle WHERE PersNr = 260
go
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'WinUser' AND o.id = OBJECT_ID(N'[dbo].updateLog') AND c.prec < 50)
BEGIN
	ALTER TABLE updateLog ALTER COLUMN WinUser VARCHAR(50)
END
go

--2010-09-10
--Anpassung der Theasoft Flex Export Einstellungen an neue Propertynamen
UPDATE [PlanSpalte] SET [Ueberschrift] = 'PrintName' WHERE [PlanSpalte].[SpalteID] IN (
	SELECT [ps].[SpalteId] FROM [PlanSpalte] AS [ps] 
	INNER JOIN [Plan] AS [p] ON [p].[PlanID] = [ps].[planid]
	WHERE [p].[Bem] = 'Theasoft.DataClasses.Dispo.ts_DataAuffTyp' AND [ps].[Ueberschrift] = 'TagBez'
)
GO

UPDATE [PlanSpalte] SET [Ueberschrift] = 'Name' WHERE [PlanSpalte].[SpalteID] IN (
	SELECT [ps].[SpalteId] FROM [PlanSpalte] AS [ps] 
	INNER JOIN [Plan] AS [p] ON [p].[PlanID] = [ps].[planid]
	WHERE [p].[Bem] = 'Theasoft.DataClasses.Dispo.ts_DataBuehne' AND [ps].[Ueberschrift] = 'Bez'
)
GO
GO
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsCleared' and o.id = OBJECT_ID(N'[dbo].CashCommand'))
BEGIN
	ALTER TABLE CashCommand ADD IsCleared BIT 
END	
go

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Module' and o.id = OBJECT_ID(N'[dbo].Rapport'))
BEGIN
	ALTER TABLE Rapport ADD Module INT NOT NULL DEFAULT(4)--Perso
	ALTER TABLE PersoParameter ADD Module INT NOT NULL DEFAULT(4)--Perso
END	

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsDayFeeMultiplier' and o.id = OBJECT_ID(N'[dbo].Zulagen'))
BEGIN
	ALTER TABLE Zulagen ADD IsDayFeeMultiplier BIT NOT NULL DEFAULT(0)
	EXEC ('UPDATE Zulagen SET IsDayFeeMultiplier = 1 WHERE Module=16')
END	
GO
IF  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'FZ' and o.id = OBJECT_ID(N'[dbo].FeiertageAusg'))
BEGIN
	ALTER TABLE dbo.FeiertageAusg DROP COLUMN FZ	
END	
IF  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Url' and o.id = OBJECT_ID(N'[dbo].FeiertageAusg'))
BEGIN
	ALTER TABLE dbo.FeiertageAusg DROP COLUMN Url
END

--2010 09 20 - 
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ContractDescription' and o.id = OBJECT_ID(N'[dbo].Vertrag'))
BEGIN
	ALTER TABLE Vertrag ADD ContractDescription varchar(100) NULL
END	

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ManualDayCount' and o.id = OBJECT_ID(N'[dbo].StatusZeitR'))
BEGIN
	ALTER TABLE StatusZeitR ADD ManualDayCount float NULL
END	
GO
IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'HasPriority' and o.id = OBJECT_ID(N'[dbo].VertragDetails'))
BEGIN
	ALTER TABLE VertragDetails ADD HasPriority BIT NOT NULL DEFAULT(0)
END	
GO

IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DefaultCostCenterId' and o.id = OBJECT_ID(N'[dbo].DienstplanartenTabelle'))
BEGIN
	ALTER TABLE DienstplanartenTabelle ADD DefaultCostCenterId INT 
END	

 ------------------------
-- Tabelle CostUnitWorkingTime --
------------------------
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CostUnitWorkingTime]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.CostUnitWorkingTime(
		CostUnitWorkingTimeId int IDENTITY(1,1) NOT NULL,
		CostUnitId int NOT NULL,
		CostCenterId int NOT NULL,
		ShiftDayId int NOT NULL,
		[Minutes] int NOT NULL,
		LM datetime NOT NULL,
		UM int NOT NULL,
		LC datetime NOT NULL,
		UC int NOT NULL,
		CONSTRAINT PK_CostUnitWorkingTime PRIMARY KEY CLUSTERED (CostUnitWorkingTimeId ASC) ON [PRIMARY],
		CONSTRAINT [FK_CostUnitWorkingTime_CostUnit] FOREIGN KEY(CostUnitId) REFERENCES dbo.CostUnit (CostUnitId)  ON DELETE CASCADE,
		CONSTRAINT [FK_CostUnitWorkingTime_ShiftDay] FOREIGN KEY(ShiftDayId) REFERENCES dbo.Dienstplan (DienstplanId)  ON DELETE CASCADE
	) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX [IX_CostUnit] ON dbo.CostUnitWorkingTime (CostUnitId)
	CREATE NONCLUSTERED INDEX [IX_ShiftDay] ON dbo.CostUnitWorkingTime (ShiftDayId)
	
	
	IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[CostUnitHours]')  AND name = 'IX_DateCostUnitDatePersonal')
	BEGIN
	CREATE UNIQUE NONCLUSTERED INDEX IX_CostUnitShiftDay ON dbo.CostUnitWorkingTime
		(CostUnitId, ShiftDayId) ON [PRIMARY]
	END
END

GRANT SELECT ON [dbo].CostUnitWorkingTime TO Public
GRANT DELETE ON [dbo].CostUnitWorkingTime TO public
GRANT INSERT ON [dbo].CostUnitWorkingTime TO public
GRANT UPDATE ON [dbo].CostUnitWorkingTime TO public
go

IF  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CostCenterId' and o.id = OBJECT_ID(N'[dbo].[CostUnitWorkingTime]'))
BEGIN
	ALTER TABLE CostUnitWorkingTime DROP COLUMN	CostCenterId 
END	
 
go
--2010-10-25
--Tabellenstruktur für Verteilerlisten hinzugefügt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ModuleId' and o.id = OBJECT_ID(N'[dbo].[Verteiler]'))
BEGIN
	--hinzufügen der Neuen Spalte für das Modul
	ALTER TABLE dbo.Verteiler ADD ModuleId INT NULL
	--alle bisherigen Verteiler auf das Modul "Contact" stellen
	EXEC ('UPDATE dbo.Verteiler SET ModuleId = 8 WHERE VerteilerID NOT IN(
SELECT FilterID FROM PlanExport WHERE FilterID IS NOT NULL)')  
END
GO
--Setzen der Schreibberechtigung auf die Verteiler für PersoAdmin und Konfigurieren
GRANT UPDATE ON dbo.Verteiler TO PersoAdmin
GRANT INSERT ON dbo.Verteiler TO PersoAdmin
GRANT DELETE ON dbo.Verteiler TO PersoAdmin
GRANT UPDATE ON dbo.Verteiler TO Konfigurieren
GRANT INSERT ON dbo.Verteiler TO Konfigurieren
GRANT DELETE ON dbo.Verteiler TO Konfigurieren
GO
--Neue Tabelle für Verteilerlisteneinträge
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[MailingListEntries]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MailingListEntries](
	[MailingListEntryId][int] IDENTITY(1,1) NOT NULL,
	[MailingListId] [int] NOT NULL,
	[PersonId] [int] NULL,
	[EntryName] varchar(200),
	[EntryValue] varchar(500),
	[EntryType] [int] NOT NULL,
	[LM] [datetime] NULL,
	[UM] [int] NULL,
	[LC] [datetime] NULL,
	[UC] [int] NULL,
	CONSTRAINT [PK_MailingListEntries] PRIMARY KEY CLUSTERED ([MailingListEntryId] ASC) ON [PRIMARY],
	CONSTRAINT [FK_MailingListEntries_Persons] FOREIGN KEY([PersonId]) REFERENCES [dbo].[PersH] ([PersNr]) ON DELETE CASCADE,
	CONSTRAINT [FK_MailingListEntries_MailingLists] FOREIGN KEY([MailingListId]) REFERENCES [dbo].[Verteiler] ([VerteilerId]) ON DELETE CASCADE
) ON [PRIMARY]
END
GO
--Berechtigungen setzen
GRANT UPDATE ON dbo.[MailingListEntries] TO PersoAdmin
GRANT INSERT ON dbo.[MailingListEntries] TO PersoAdmin
GRANT DELETE ON dbo.[MailingListEntries] TO PersoAdmin
GRANT UPDATE ON dbo.[MailingListEntries] TO Konfigurieren
GRANT INSERT ON dbo.[MailingListEntries] TO Konfigurieren
GRANT DELETE ON dbo.[MailingListEntries] TO Konfigurieren
GRANT SELECT ON dbo.[MailingListEntries] TO Public 
GO
--Feld für die zuweisung von Verteilern zu Vorlagen hinzufügen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'MailingListId' and o.id = OBJECT_ID(N'[dbo].[Vorlagen]'))
BEGIN
ALTER TABLE [dbo].[Vorlagen] 
	ADD MailingListId INT NULL,
	CONSTRAINT [PK_TemplateMailingList] FOREIGN KEY([MailingListId]) REFERENCES [dbo].[Verteiler] ([VerteilerId])
END
 
--2010-10-21
--neue Tabelle WageDataExportProfiles
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[WageDataExportProfiles]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[WageDataExportProfiles] (
	[WageDataExportProfileId] INT IDENTITY (1, 1) NOT NULL,
	[Name] VARCHAR(50) NOT NULL ,
	[Description] VARCHAR(255) NULL,
	[ExportProvider] VARCHAR(80) NOT NULL,
	[ExportProviderSettings] TEXT NULL,
	[DefaultExportPath] VARCHAR(255) NULL,
	[SendMailSettings] TEXT NULL,
	[LC] DATETIME NULL,
	[UC] INT NULL,
	[LM] DATETIME NULL,
	[UM] INT NULL,
	CONSTRAINT [PK_WageDataExportProfiles] PRIMARY KEY CLUSTERED ([WageDataExportProfileId] ASC) ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON [WageDataExportProfiles] TO public

GRANT SELECT ON [WageDataExportProfiles] TO PersoAdmin
GRANT DELETE ON [WageDataExportProfiles] TO PersoAdmin
GRANT INSERT ON [WageDataExportProfiles] TO PersoAdmin
GRANT UPDATE ON [WageDataExportProfiles] TO PersoAdmin

GO
--2010 10 26 Qualifikationsdetails
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DateOfQualification' and o.id = OBJECT_ID(N'[dbo].[Qualification_Person]'))
BEGIN
	ALTER TABLE [dbo].[Qualification_Person] ADD DateOfQualification DATETIME NULL
	ALTER TABLE [dbo].[Qualification_Person] ADD [Description] VARCHAR(100) NULL
	ALTER TABLE [dbo].[Qualification_Person] ADD [Note] VARCHAR(500) NULL
END
go
--2010 11 01
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsGroup' and o.id = OBJECT_ID(N'[dbo].[UserPw]'))
BEGIN
	ALTER TABLE [dbo].UserPw ADD IsGroup BIT DEFAULT 0
	ALTER TABLE [dbo].UserGruppe ADD  IsInherited  BIT DEFAULT 0
	ALTER TABLE [dbo].UserForAccess ADD  IsInherited  BIT DEFAULT 0

END
GO
UPDATE UserPw SET IsGroup = 0 WHERE IsGroup IS NULL
UPDATE UserGruppe SET IsInherited = 0 WHERE IsInherited IS NULL
UPDATE UserForAccess SET IsInherited = 0 WHERE IsInherited IS NULL
GO

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

GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[UsersInGroups]'))
BEGIN
	DROP VIEW [dbo].UsersInGroups
END
GO
DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
DECLARE @SQL as varchar(4000) 
IF (@sql_server_version <= 8)  BEGIN

	SET @SQL = 'CREATE VIEW [dbo].UsersInGroups
		AS 
	SELECT 	pwG.UserID AS GroupId,pwU.UserID AS UserId
	FROM			sysmembers m 
			INNER JOIN  (SELECT * FROM sysusers WHERE issqlrole = 0) u	ON m.memberuid = u.uid
			INNER JOIN  (SELECT * FROM sysusers WHERE issqlrole = 1) g	ON  m.groupuid = g.uid
			INNER JOIN  UserPw pwG			ON g.name = pwG.UserName
			INNER JOIN	UserPw pwU			ON u.name = pwU.UserName'
			
	END
ELSE
	BEGIN

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

GO
GRANT SELECT ON [dbo].UsersInGroups TO Public
GO
-- =============================================
-- Author:			Torsten Klier
-- Create date:		2010 11 01
-- Modified date:	2011 01 24
-- (Abteilungs-)Gruppenberechtigungen aus Datenbankrollen übernehmen
-- Wenn ein Recht aus mehreren Datenbankrollen geerbt wird, wird das "größte" übernommen 
-- =============================================
CREATE PROCEDURE [dbo].[InherhitPermissions]
AS
BEGIN   
DECLARE @dbo BIT
DECLARE @CurrentUserId INT

SELECT @dbo = IS_MEMBER('db_owner')
IF @dbo = 0 
	BEGIN
		SELECT @CurrentUserId = UserId FROM UserPw WHERE UserName = CURRENT_USER 
		Print 'User' +  cast(@CurrentUserId as Varchar(10))
	END  
ELSE
	BEGIN
		SET @CurrentUserId = -1
		Print 'All User'
	END
	
--neue Berechtigungen einfügen
	INSERT INTO UserGruppe (GruppeID,UserID,BerechtigungsbereichID,Schreiben,OptionsFlag,IsInherited,LM,UM,LC,UC)
	SELECT  soll.GruppeID, ugs.UserID, soll.BerechtigungsbereichID, CAST(COUNT(soll.Schreiben) AS BIT), MAX(soll.OptionsFlag),1,MAX(soll.LM),MAX(soll.UM),MAX(soll.LC),MAX(soll.UC)
	FROM	UsersInGroups AS ugs 
		INNER JOIN	UserGruppe AS soll	ON ugs.GroupID = soll.UserID
		LEFT JOIN	UserGruppe AS ist	ON ugs.UserID = ist.UserID AND soll.GruppeID  = ist.GruppeID AND soll.BerechtigungsbereichID = ist.BerechtigungsbereichID
	WHERE  ist.UserGruppeID IS NULL AND (ugs.UserId = @CurrentUserId OR @CurrentUserId = -1)
	GROUP BY soll.GruppeID, ugs.UserID, soll.BerechtigungsbereichID


	--Berechtigungen entfernen
	DELETE FROM UserGruppe 
	WHERE IsInherited = 1 
		AND (UserGruppe.UserId = @CurrentUserId OR @CurrentUserId = -1)
		AND  UserGruppeID  NOT IN 
				(
					SELECT  ist.UserGruppeID
					FROM			UsersInGroups AS ugs 
						INNER JOIN	UserGruppe AS soll		ON ugs.GroupId = soll.UserID
						INNER JOIN	UserGruppe as ist	ON ugs.UserID = ist.UserID AND soll.GruppeID  = ist.GruppeID AND soll.BerechtigungsbereichID = ist.BerechtigungsbereichID
				)

		
	UPDATE UserGruppe SET UserGruppe.Schreiben = SollSchreiben, UserGruppe.OptionsFlag=SollOp
	FROM 
	(SELECT ugs.UserId, g.GruppeID, BerechtigungsbereichID, MAX(CAST(g.Schreiben AS INT)) AS SollSchreiben, MAX(CAST(g.OptionsFlag AS INT)) AS SollOp 
		FROM UsersInGroups AS ugs 
			INNER JOIN UserGruppe AS G ON ugs.GroupId = G.UserID
		GROUP BY ugs.UserId , g.GruppeID, BerechtigungsbereichID) AS soll 
	INNER JOIN UserGruppe  ON 
			soll.UserId = UserGruppe.UserID AND 
			soll.GruppeID = UserGruppe.GruppeID AND 
			soll.BerechtigungsbereichID = UserGruppe.BerechtigungsbereichID
	WHERE (SollSchreiben <> UserGruppe.Schreiben OR SollOp <>  UserGruppe.OptionsFlag)  AND UserGruppe.IsInherited = 1  AND (UserGruppe.UserId = @CurrentUserId OR @CurrentUserId = -1)
	
	
	--Jeden User in Gruppe Kontaktdaten Jeder
	INSERT INTO UserGruppe(GruppeID ,UserID,Schreiben,LM,UM,LC,UC,BerechtigungsbereichID,OptionsFlag)
	SELECT -1, UserPw.UserID,0, '19000101',0,'19000101',0,0,0  
	FROM UserPw LEFT JOIN (SELECT * FROM UserGruppe WHERE BerechtigungsbereichID=0 AND GruppeID = -1) AS UG on UserPW.UserID=UG.UserID WHERE UG.UserGruppeID IS NULL

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

	--2014-09-05 sh
	--um das löschen zu beschleunigen, werden die ids aus der bisherigen in-anweisung in eine eigene temporäre tabelle gespeichert
	CREATE TABLE #UserIdTable(UserForAccessID INT)
	INSERT into #UserIdTable (UserForAccessID)
	SELECT			ist.UserForAccessID
	FROM			UsersInGroups AS ugs  	
		INNER JOIN	UserForAccess soll		ON ugs.GroupId = soll.UserID
		INNER JOIN	UserForAccess ist		ON ugs.UserId = ist.UserID  AND soll.SpzNr=ist.SpzNr
		
	DELETE FROM UserForAccess 
	WHERE IsInherited = 1 AND  UserForAccessID NOT IN (
		SELECT UserForAccessID from #UserIdTable
	) AND (UserId = @CurrentUserId OR @CurrentUserId = -1)

END	

GO
GRANT EXECUTE ON InherhitPermissions TO Public



--2010-10-25
--View [DienstplanArten] angepasst, keien ausnahme mehr für dbo und persoadmin
DROP VIEW [dbo].[DienstplanArten]
GO

CREATE VIEW [dbo].[DienstplanArten] 
	AS 
	SELECT DISTINCT da.*
	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 OR da.DienstplanArtenID = 0
GO

GRANT SELECT ON DienstplanArten TO public

GRANT DELETE ON DienstplanArten TO ChorAdmin
GRANT INSERT ON DienstplanArten TO ChorAdmin
GRANT UPDATE ON DienstplanArten TO ChorAdmin

GRANT DELETE ON DienstplanArten TO PersoAdmin
GRANT INSERT ON DienstplanArten TO PersoAdmin
GRANT UPDATE ON DienstplanArten TO PersoAdmin
GO
--2010 11 08 Tagesplan
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Zeichen' AND o.id = OBJECT_ID(N'[dbo].TagesplanAusgabe') AND c.prec < 50)
BEGIN
ALTER TABLE  TagesplanAusgabe ALTER COLUMN  Zeichen Varchar(50)
END
GO
--2010 11 011 SecurityAdmin 
EXEC sp_addrolemember N'db_accessadmin', N'SecurityAdmin'
EXEC sp_addrolemember N'db_SecurityAdmin', N'SecurityAdmin'
GO
--Berechtigungen aus Kontaktdaten lese in Public
GRANT SELECT ON AbPersKomAlle TO public
GRANT SELECT ON AbPersKontakt TO public
GRANT SELECT ON AbPersonalNotizen TO public
GRANT SELECT ON AbPersonalNotizen_Update TO public
GRANT INSERT ON AbPersonalNotizen_Update TO public
GRANT UPDATE ON AbPersonalNotizen_Update TO public
GRANT DELETE ON AbPersonalNotizen_Update TO public
GRANT SELECT ON AbPersZusatzDaten TO public
GRANT SELECT ON AbPersZusatzDaten_Update TO public

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'LongName' AND o.id = OBJECT_ID(N'[dbo].Ring'))
BEGIN 
	ALTER TABLE Ring ADD LongName Varchar(50)
END

go
--UPDATE Zeitkonten SET Formel = 3010 WHERE ZeitKtoNr = 10 AND Formel = 0 OR Formel IS NULL
--UPDATE Zeitkonten SET Formel = 3011 WHERE ZeitKtoNr = 11 AND Formel = 0 OR Formel IS NULL
--UPDATE Zeitkonten SET Formel = 3013 WHERE ZeitKtoNr = 13 AND Formel = 0 OR Formel IS NULL
--UPDATE Zeitkonten SET Formel = 3050 WHERE ZeitKtoNr = 25 AND Formel = 0 OR Formel IS NULL
--UPDATE Zeitkonten SET Formel = 1230 WHERE ZeitKtoNr = 41 AND Formel = 0 OR Formel IS NULL
--UPDATE Zeitkonten SET Formel = 1252 WHERE ZeitKtoNr = 52 AND Formel = 0 OR Formel IS NULL
--UPDATE Zeitkonten SET Formel = 1253 WHERE ZeitKtoNr = 53 AND Formel = 0 OR Formel IS NULL
GO
go
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Note' AND o.id = OBJECT_ID(N'[dbo].DayNotes') AND c.prec < 250)
BEGIN
	ALTER TABLE DayNotes ALTER COLUMN Note VARCHAR(250)
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'FixCostUnitType' AND o.id = OBJECT_ID(N'[dbo].Zulagen'))
BEGIN 
	ALTER TABLE Zulagen ADD FixCostUnitType INT NULL
END

GO

--2010-12-01
--BugFix für FlexExport -> ControlContainerName wurde bei neuen Filtern nicht gesetzt
UPDATE VerteilerFeld SET ControlContainerName = 'ts_DataAuff' WHERE VFID IN (
	SELECT vf.VFID FROM VerteilerFeld vf JOIN Verteiler v ON vf.VerteilerID = v.VerteilerID
	WHERE v.VerteilerName = 'export' AND cast(v.sqlString AS VARCHAR(10))='frmExport'
)
GO
 
 
GRANT SELECT ON Serienbrief TO Public
GRANT UPDATE ON Serienbrief TO [Kontaktdaten ändern]
GRANT DELETE ON Serienbrief TO [Kontaktdaten ändern]
GRANT INSERT ON Serienbrief TO [Kontaktdaten ändern]
GO

--2010-12-15
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ShortName_en' AND o.id = OBJECT_ID(N'[dbo].zr'))
BEGIN 
	ALTER TABLE zr ADD ShortName_en VARCHAR(10) NULL
	ALTER TABLE zr ADD Name_en VARCHAR(60) NULL
	
	ALTER TABLE AuffTypen ADD ShortName_en VARCHAR(6) NULL
	ALTER TABLE AuffTypen ADD Name_en VARCHAR(30) NULL
END

go

--2011-01-07 SH
--PersoAdmin Schreibberechtigungen auf Feiertage erteilen
GRANT UPDATE ON Feiertage TO PersoAdmin
GRANT DELETE ON Feiertage TO PersoAdmin
GRANT INSERT ON Feiertage TO PersoAdmin
go

--2011-01-21 TH
--Neue Spalte im CastStatus für den DefaultGeheimStatus
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DefaultSecretState' and o.id = OBJECT_ID(N'[dbo].[CastStatus]'))
BEGIN
	ALTER TABLE dbo.CastStatus ADD DefaultSecretState BIT NOT NULL CONSTRAINT DF_CastStatus_DefaultSecretState DEFAULT 0
	EXEC('UPDATE dbo.CastStatus SET DefaultSecretState = 1 WHERE CastStatusTyp < 10')
END
go
--2011-02-07 TH
--Neue Spalte um PlanSpalten für die Tagesplansektion "Vorstellungen" zu kennzeichnen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'Function' AND o.id = OBJECT_ID(N'[dbo].[PlanSpalte]'))
BEGIN
	ALTER TABLE dbo.PlanSpalte ADD [Function] INT NULL
END
go

--2011-01-28
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PersDataCategories]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.PersDataCategories(
		PersDataCategoryId int IDENTITY(1,1) NOT NULL,
		CategoryName VARCHAR(100) NOT NULL,
		CategoryCode VARCHAR(20) NULL,
		Sort int NOT NULL DEFAULT(0), 
		LM datetime NOT NULL,
		UM int NOT NULL,
		LC datetime NOT NULL,
		UC int NOT NULL,
		CONSTRAINT PK_PersDataCategories PRIMARY KEY CLUSTERED (PersDataCategoryId ASC) ON [PRIMARY],
	) ON [PRIMARY]

	CREATE UNIQUE NONCLUSTERED INDEX [IX_CategoryCode] ON dbo.PersDataCategories (CategoryCode)
	CREATE NONCLUSTERED INDEX [IX_Sort] ON dbo.PersDataCategories (Sort)

END

-- BugFix 2011-02-04
GRANT SELECT ON [dbo].[PersDataCategories] TO [public]
-- //BugFix 2011-02-04
GRANT SELECT ON [dbo].PersDataCategories TO [Soli-Daten lesen]
GRANT SELECT ON [dbo].PersDataCategories TO [Soli-Daten ändern]
GRANT DELETE ON [dbo].PersDataCategories TO [Soli-Daten ändern]
GRANT INSERT ON [dbo].PersDataCategories TO [Soli-Daten ändern]
GRANT UPDATE ON [dbo].PersDataCategories TO [Soli-Daten ändern]


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PersDataCategoryData]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.PersDataCategoryData(
		PersDataCategoryDataId int IDENTITY(1,1) NOT NULL,
		PersDataCategoryId int NOT NULL,
		PersonId int NOT NULL,
		TextValue VARCHAR(250) NOT NULL,
		LM datetime NOT NULL,
		UM int NOT NULL,
		LC datetime NOT NULL,
		UC int NOT NULL,
		CONSTRAINT PK_PersDataCategoryData PRIMARY KEY CLUSTERED (PersDataCategoryDataId ASC) ON [PRIMARY],
		CONSTRAINT [FK_PersDataCategoryData_PersDataCategories] FOREIGN KEY(PersDataCategoryId) REFERENCES dbo.PersDataCategories (PersDataCategoryId),
		CONSTRAINT [FK_PersDataCategoryData_PersH] FOREIGN KEY(PersonId) REFERENCES dbo.PersH (PersNr)  ON DELETE CASCADE
	) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX [IX_PersonId] ON dbo.PersDataCategoryData (PersonId)
	CREATE NONCLUSTERED INDEX [IX_PersDataCategoryId] ON dbo.PersDataCategoryData (PersDataCategoryId)
	
	
	IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PersDataCategoryData]')  AND name = 'IX_PersDataCategory_PersonId')
	BEGIN
	CREATE UNIQUE NONCLUSTERED INDEX IX_PersDataCategory_PersonId ON dbo.PersDataCategoryData
		(PersDataCategoryId, PersonId) ON [PRIMARY]
	END
END

GRANT SELECT ON [dbo].PersDataCategoryData TO [Soli-Daten lesen]
GRANT SELECT ON [dbo].PersDataCategoryData TO [Soli-Daten ändern]
GRANT DELETE ON [dbo].PersDataCategoryData TO [Soli-Daten ändern]
GRANT INSERT ON [dbo].PersDataCategoryData TO [Soli-Daten ändern]
GRANT UPDATE ON [dbo].PersDataCategoryData TO [Soli-Daten ändern]

IF NOT EXISTS (SELECT * FROM PersDataCategories)
BEGIN
	SET IDENTITY_INSERT PersDataCategories  ON
	INSERT INTO PersDataCategories (PersDataCategoryId,Sort,CategoryName,CategoryCode,LM,UM,LC,UC) VALUES (1,1,'Frühere Nationalität','PreviousNationality',GETDATE(),0,GETDATE(),0)
	INSERT INTO PersDataCategories (PersDataCategoryId,Sort,CategoryName,CategoryCode,LM,UM,LC,UC) VALUES (2,2,'Name des Vaters','NameOfFather',GETDATE(),0,GETDATE(),0)
	INSERT INTO PersDataCategories (PersDataCategoryId,Sort,CategoryName,CategoryCode,LM,UM,LC,UC) VALUES (3,3,'Beruf','Job',GETDATE(),0,GETDATE(),0)
	INSERT INTO PersDataCategories (PersDataCategoryId,Sort,CategoryName,CategoryCode,LM,UM,LC,UC) VALUES (4,4,'Aufenthaltserlaubnis','ResidencePermit',GETDATE(),0,GETDATE(),0)
	INSERT INTO PersDataCategories (PersDataCategoryId,Sort,CategoryName,CategoryCode,LM,UM,LC,UC) VALUES (5,5,'Geburtsland','LandOfBirth',GETDATE(),0,GETDATE(),0)
	SET IDENTITY_INSERT PersDataCategories  OFF
	
	INSERT INTO PersDataCategoryData (TextValue, PersDataCategoryId,PersonId,LM,UM,LC,UC) SELECT  PreviousNationality,pnr,1,GETDATE(),0,GETDATE(),0 FROM PersonalDetails WHERE NOT PreviousNationality IS NULL
	INSERT INTO PersDataCategoryData (TextValue, PersDataCategoryId,PersonId,LM,UM,LC,UC) SELECT  NameOfFather,pnr,2,GETDATE(),0,GETDATE(),0  FROM PersonalDetails WHERE NOT NameOfFather IS NULL
	INSERT INTO PersDataCategoryData (TextValue, PersDataCategoryId,PersonId,LM,UM,LC,UC) SELECT  Job,pnr,3,GETDATE(),0,GETDATE(),0  FROM PersonalDetails WHERE NOT Job IS NULL
	INSERT INTO PersDataCategoryData (TextValue, PersDataCategoryId,PersonId,LM,UM,LC,UC) SELECT  ValidResidencePermit,pnr,4 ,GETDATE(),0,GETDATE(),0 FROM PersonalDetails WHERE NOT ValidResidencePermit IS NULL
	INSERT INTO PersDataCategoryData (TextValue, PersDataCategoryId,PersonId,LM,UM,LC,UC) SELECT  LandOfBirth,pnr,5  ,GETDATE(),0,GETDATE(),0 FROM PersonalDetails WHERE NOT LandOfBirth IS NULL
END 
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ContractPartTimePeriods]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.ContractPartTimePeriods(
		ContractPartTimePeriodId int IDENTITY(1,1) NOT NULL,
		ContractId int NOT NULL,
		StartDate DATETIME NULL,
		EndDate DATETIME NULL,
		WorkingMinutesDay0 int NOT NULL CONSTRAINT [DF_ContractPartTimePeriods_WorkingMinutesDay0] DEFAULT (0),
		WorkingMinutesDay1 int NOT NULL CONSTRAINT [DF_ContractPartTimePeriods_WorkingMinutesDay1] DEFAULT (0),
		WorkingMinutesDay2 int NOT NULL CONSTRAINT [DF_ContractPartTimePeriods_WorkingMinutesDay2] DEFAULT (0),
		WorkingMinutesDay3 int NOT NULL CONSTRAINT [DF_ContractPartTimePeriods_WorkingMinutesDay3] DEFAULT (0),
		WorkingMinutesDay4 int NOT NULL CONSTRAINT [DF_ContractPartTimePeriods_WorkingMinutesDay4] DEFAULT (0),
		WorkingMinutesDay5 int NOT NULL CONSTRAINT [DF_ContractPartTimePeriods_WorkingMinutesDay5] DEFAULT (0),
		WorkingMinutesDay6 int NOT NULL CONSTRAINT [DF_ContractPartTimePeriods_WorkingMinutesDay6] DEFAULT (0),
		Notes VARCHAR(250) NULL,
		LM datetime NOT NULL,
		UM int NOT NULL,
		LC datetime NOT NULL,
		UC int NOT NULL,
		CONSTRAINT PK_ContractPartTimePeriods PRIMARY KEY CLUSTERED (ContractPartTimePeriodId ASC) ON [PRIMARY],
		CONSTRAINT [FK_ContractPartTimePeriods_VertragPerso] FOREIGN KEY(ContractId) REFERENCES dbo.VertragPerso (VertragsNr)ON DELETE CASCADE
	) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX [IX_ContractId] ON dbo.ContractPartTimePeriods (ContractId)
	
END
go
GRANT SELECT ON [dbo].ContractPartTimePeriods TO Public
go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'PureTitel' AND o.id = OBJECT_ID(N'[dbo].[StückeDetails]'))
BEGIN 
	ALTER TABLE [StückeDetails] ADD PureTitel VARCHAR(20) NULL
END
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ModuleGroupId' AND o.id = OBJECT_ID(N'[dbo].[Stücke]'))
BEGIN 
	ALTER TABLE [Stücke] ADD ModuleGroupId INT NULL
END
go
UPDATE PersH SET  Ansprache  = BriefAnrede  FROM PersAgentur INNER JOIN PersH on PersAgentur.PersNr=PersH.PersNr  where PersAgentur.PersNr = PersAgentur.ChildPersNr AND not BriefAnrede is null
DELETE FROM PersAgentur WHERE PersAgentur.PersNr = PersAgentur.ChildPersNr
go
--2011-01-24
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KenntnisDel]')  AND name = 'IX_XHID')
CREATE NONCLUSTERED INDEX IX_XHID ON dbo.KenntnisDel (XHID)  ON [PRIMARY]
go
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KenntnisDel]')  AND name = 'IX_UC_Tabl')
CREATE NONCLUSTERED INDEX IX_UC_Tabl ON dbo.KenntnisDel (uc, Tabl)  ON [PRIMARY]
go
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[XHDelAufführg]')  AND name = 'IX_ActivityId')
CREATE NONCLUSTERED INDEX IX_ActivityId ON dbo.XHDelAufführg (AuffNr)  ON [PRIMARY]
go
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[XHDelAufführg]')  AND name = 'IX_Date')
CREATE NONCLUSTERED INDEX IX_Date ON dbo.XHDelAufführg (Datum)  ON [PRIMARY]
go
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[XHDelBesetzung]')  AND name = 'IX_ActivityId')
CREATE NONCLUSTERED INDEX IX_ActivityId ON dbo.XHDelBesetzung (AuffNr)  ON [PRIMARY]
go

GO

--2011-01-13 SH
--zusätzliche Spalte zum Zuordnen von Verträgen zu Kosten
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'VrId' AND o.id = OBJECT_ID(N'[dbo].Kosten_Stück'))
BEGIN 
	ALTER TABLE dbo.Kosten_Stück ADD VrId int NULL

	CREATE NONCLUSTERED INDEX IX_Kosten_Stück_VrId ON dbo.Kosten_Stück ( 
		VrId
	) ON [PRIMARY]

	ALTER TABLE dbo.Kosten_Stück ADD CONSTRAINT FK_Kosten_Stück_VertragRolle
	FOREIGN KEY (VrId) REFERENCES dbo.VertragRolle (VRID)
END
GO

--2011-01-14 SH
--Tabelle für Fälligkeiten
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ContractDateMaturities]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ContractDateMaturities] (
	[ContractDateId] INT NOT NULL,
	[Description] [varchar](50) NULL,
	[Amount] [money] NULL,
	[LC] DATETIME NULL,
	[UC] INT NULL,
	[LM] DATETIME NULL,
	[UM] INT NULL,
	CONSTRAINT FK_Maturities_ContractDates FOREIGN KEY (ContractDateId) REFERENCES dbo.ContractDates (ContractDateId)
	ON UPDATE CASCADE
	ON DELETE CASCADE,
	CONSTRAINT PK_Maturities PRIMARY KEY CLUSTERED ([ContractDateId] ASC) ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON [ContractDateMaturities] TO [Honorar-Daten lesen]

GRANT SELECT ON [ContractDateMaturities] TO [Honorar-Daten ändern]
GRANT DELETE ON [ContractDateMaturities] TO [Honorar-Daten ändern]
GRANT INSERT ON [ContractDateMaturities] TO [Honorar-Daten ändern]
GRANT UPDATE ON [ContractDateMaturities] TO [Honorar-Daten ändern]
GO

--2011-01-14 SH
--zusätzliche Spalten in ContractDates
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IsMaturityDate' AND o.id = OBJECT_ID(N'[dbo].ContractDates'))
BEGIN 	
	ALTER TABLE dbo.ContractDates ADD IsMaturityDate BIT NOT NULL CONSTRAINT DF_ContractDates_IsMaturityDate DEFAULT 0
	
	ALTER TABLE dbo.ContractDates ADD ActivityId INT NULL
	ALTER TABLE dbo.ContractDates ADD ActivityTypeId INT NULL	
	
	ALTER TABLE dbo.ContractDates ALTER COLUMN StageId INT NULL
	ALTER TABLE dbo.ContractDates ALTER COLUMN IsCanceled BIT NOT NULL
	
	EXEC DeleteConstraint 'ContractDates', 'CDStatusId'
	ALTER TABLE [dbo].[ContractDates] ADD CONSTRAINT DF_ContractDates_CDStatusId DEFAULT 0 FOR [CDStatusId]
END
GO

--2011-02-01 SH
--Neue Spalte ServiceDate in CashCommandPositions
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ServiceDate' and o.id = OBJECT_ID(N'[dbo].[CashCommandPos]'))
BEGIN
	ALTER TABLE dbo.CashCommandPos ADD ServiceDate DATETIME NULL
END
GO

-- 2011-02-14 TH
-- Neue Spalte IsPerformanceSection diese gibt an ob es sich um eine Section (Tagesplanabschnitt)
-- für VBorastellungen handelt.
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsPerformanceSection' and o.id = OBJECT_ID(N'[dbo].[TagSparteSort]'))
BEGIN
	ALTER TABLE dbo.TagSparteSort ADD IsPerformanceSection BIT NOT NULL CONSTRAINT DF_TagSparteSort_IsPerformanceSection DEFAULT 0
END
GO



--2011-02-09 SH
--neue Spalte für Vorlagen-Parameter
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'TemplateParameterData' AND o.id = OBJECT_ID(N'[dbo].Vorlagen'))
BEGIN 	
	ALTER TABLE dbo.Vorlagen ADD TemplateParameterData VARCHAR(2000) NULL
END
GO
--2011-02-18
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BriefAnrede' AND o.id = OBJECT_ID(N'[dbo].Anrede') AND c.prec < 100)
BEGIN
	ALTER TABLE Anrede ALTER COLUMN BriefAnrede VARCHAR(100)
END
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'RolleKurz' AND o.id = OBJECT_ID(N'[dbo].RollenLtg') AND c.prec < 15)
BEGIN
	ALTER TABLE RollenLtg ALTER COLUMN RolleKurz VARCHAR(15)
END
Go

--2011-02-24 SH
--neue Spalte für Kostenart von Fälligkeiten
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'CostType' AND o.id = OBJECT_ID(N'[dbo].ContractDateMaturities'))
BEGIN 	
	ALTER TABLE dbo.ContractDateMaturities ADD CostType INT NOT NULL CONSTRAINT DF_ContractDateMaturities_CostType DEFAULT 0
END
GO

--2011-03-09 SH
--neue Spalte für Auzahlungslohnart in Rapportspalten
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'PaymentWageTypeId' AND o.id = OBJECT_ID(N'[dbo].RapportSpalte'))
BEGIN 	
	
	ALTER TABLE dbo.RapportSpalte ADD PaymentWageTypeId INT NULL
	ALTER TABLE dbo.RapportSpalte ADD CONSTRAINT FK_RapportSpalte_PaymentWageTypeId_WageType
	FOREIGN KEY ( PaymentWageTypeId	) REFERENCES dbo.WageType ( WageTypeId )
END
GO

--2011 03 11
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'[dbo].[Qualification_Person]'))
BEGIN
	ALTER TABLE [dbo].[Qualification_Person] ADD Sort INT NULL
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ShowProductionColor' and o.id = OBJECT_ID(N'[dbo].[DienstplanArtenTabelle]'))
BEGIN
	ALTER TABLE [dbo].[DienstplanArtenTabelle] ADD ShowProductionColor BIT NOT NULL DEFAULT (0)
END
GO

 
  
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TotalCastShiftsPerWeek' and o.id = OBJECT_ID(N'[dbo].[PersoParameter]'))
BEGIN
	ALTER TABLE [dbo].PersoParameter ADD TotalCastShiftsPerWeek INT NOT NULL DEFAULT (0)
	ALTER TABLE [dbo].PersoParameter ADD PerformanceCastShiftsPerWeek INT NOT NULL DEFAULT (0)
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'WorkPercent' and o.id = OBJECT_ID(N'[dbo].[VertragsVorlagen]'))
BEGIN
	ALTER TABLE [dbo].VertragsVorlagen ADD WorkPercent REAL NOT NULL DEFAULT (100)
	ALTER TABLE [dbo].ContractPartTimePeriods ADD WorkPercent REAL NOT NULL DEFAULT (100)
END
 
GO

--2011-03-18 TK
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ResourceTypes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].ResourceTypes (
	ResourceTypeId INT IDENTITY(1,1) NOT NULL,
	Name VARCHAR(50) NOT NULL,
	Modules INT NOT NULL,
	[LC] DATETIME NULL,
	[UC] INT NULL,
	[LM] DATETIME NULL,
	[UM] INT NULL
	CONSTRAINT PK_ResourceTypes PRIMARY KEY CLUSTERED (ResourceTypeId ASC) ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON ResourceTypes TO Public
GRANT DELETE ON ResourceTypes TO [TheaOrchester]
GRANT INSERT ON ResourceTypes TO [TheaOrchester]
GRANT UPDATE ON ResourceTypes TO [TheaOrchester]



IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Resources]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].Resources (
	ResourceId INT IDENTITY(1,1) NOT NULL,
	ResourceTypeId INT NOT NULL,
	PersonId INT NULL,
	Name VARCHAR (200) NULL,
	ValueEstimatedBy VARCHAR (200) NULL,
	Value MONEY NULL,
	IsPrivate BIT NOT NULL CONSTRAINT DF_Resources_IsPrivate DEFAULT (0),
	IsOutdoorCapable  BIT NOT NULL CONSTRAINT DF_Resources_IsOutdoorCapable DEFAULT (0),
	HasDecreaseInValue BIT NOT NULL CONSTRAINT DF_Resources_HasDecreaseInValue DEFAULT (0),
	Note VARCHAR (1000) NULL,
	IsAssured BIT NOT NULL CONSTRAINT DF_Resources_IsAssured DEFAULT (0) ,
	[LC] DATETIME NULL,
	[UC] INT NULL,
	[LM] DATETIME NULL,
	[UM] INT NULL,
	CONSTRAINT FK_Resources_ResourceTypes FOREIGN KEY (ResourceTypeId) REFERENCES dbo.ResourceTypes (ResourceTypeId),
	CONSTRAINT FK_Resources_Person FOREIGN KEY (PersonId) REFERENCES dbo.PersH (Persnr),
	CONSTRAINT PK_Ressources PRIMARY KEY CLUSTERED (ResourceId ASC) ON [PRIMARY]
) ON [PRIMARY]
CREATE INDEX IX_Resources_ResourceTypeId ON dbo.Resources (ResourceTypeId) ON [PRIMARY]
CREATE INDEX IX_Resources_PersonId ON dbo.Resources (PersonId) ON [PRIMARY]
END
GO

GRANT SELECT ON Resources TO [TheaOrchester lesen]
GRANT SELECT ON Resources TO [TheaOrchester]
GRANT DELETE ON Resources TO [TheaOrchester]
GRANT INSERT ON Resources TO [TheaOrchester]
GRANT UPDATE ON Resources TO [TheaOrchester]



IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DefaultTravelCosts' and o.id = OBJECT_ID(N'[dbo].[PersonalHonorar]'))
BEGIN
	ALTER TABLE [PersonalHonorar] ADD DefaultTravelCosts  MONEY NULL
	ALTER TABLE [PersonalHonorar] ADD DefaultPerformanceFee  MONEY NULL
	ALTER TABLE [PersonalHonorar] ADD DefaultRehersalFee  MONEY NULL
	EXEC ('UPDATE [PersonalHonorar] SET DefaultPerformanceFee=CASE WHEN HonorarVs =0 THEN NULL ELSE HonorarVs END ,DefaultRehersalFee=CASE WHEN HonorarPro =0 THEN NULL ELSE HonorarPro END ')
END
  

--2011-03-18 TH
--neue Spalte für Seitenumbruch zwischen Tagesplanabschnitten
--neue Spalte für Type des Abschnitts
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'PageBreak' AND o.id = OBJECT_ID(N'[dbo].TagSparteSort'))
BEGIN 	
	ALTER TABLE dbo.TagSparteSort ADD PageBreak BIT NOT NULL CONSTRAINT DF_TagSparteSort_PageBreak DEFAULT 0
	ALTER TABLE dbo.TagSparteSort ADD SectionType INT NOT NULL CONSTRAINT DF_TagSparteSort_SectionType DEFAULT 0
END
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ModuleGroupId' AND o.id = OBJECT_ID(N'[dbo].[Stücke]' ) AND c.isnullable = 1) 
BEGIN	
	UPDATE [Stücke] SET ModuleGroupId = 1 WHERE ModuleGroupId IS NULL
	ALTER TABLE [Stücke] ADD DEFAULT ((1)) FOR ModuleGroupId
	ALTER TABLE [Stücke] ALTER COLUMN ModuleGroupId INT NOT NULL
	
	Update Anrede Set BriefAnrede = 'Sehr geehrter Herr {0:S},' WHERE BriefAnrede = 'Sehr geehrter Herr'
	Update Anrede Set BriefAnrede = 'Sehr geehrte Frau {0:S},' WHERE BriefAnrede = 'Sehr geehrte Frau'
	Update Anrede Set BriefAnrede = 'Sehr geehrte Familie {0:S},' WHERE BriefAnrede = 'Sehr geehrte Familie'
	
END

--2011-04-04 SH
--Spalte Sort für Abteilungen
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'[dbo].DienstplanArtenTabelle'))
BEGIN 	
	ALTER TABLE dbo.DienstplanArtenTabelle ADD Sort INT NOT NULL CONSTRAINT DF_DienstplanArtenTabelle_Sort DEFAULT 0	
END
GO
GRANT UPDATE ON [dbo].[Zeitkonten] TO [PersoAdmin]
GRANT INSERT ON [dbo].[Zeitkonten] TO [PersoAdmin]
GRANT DELETE ON [dbo].[Zeitkonten] TO [PersoAdmin]
GO


--2011-04-06 TH Berechtigungen an die Mandantentrennung anpassen
--TEMP-TABELLE MIT DEN ZUORDUNGEN VON USER UND ROLE
IF (SELECT COUNT(*) FROM NvData WHERE ByModulScript = 1 AND lfdVerNr < 20110406) > 0 BEGIN
DECLARE @userRoles TABLE
( UserName varchar(500) COLLATE DATABASE_DEFAULT, RoleName varchar(500) COLLATE DATABASE_DEFAULT)
INSERT
INTO @userRoles
	SELECT g.name, u.name 
	FROM [sysusers] AS u 
	INNER JOIN [sysmembers] AS m ON u.uid = m.memberuid
	INNER JOIN [sysusers] AS g ON m.groupuid = g.uid
                             

--ALLE DIE BEREITS EIN LESE RECHT HABEN UND DIE DATENBANK BERECHTIGUNG "SPIELPLAN SCHREIBEN" BEKOMMEN EIN UPDATE
UPDATE UserGruppe SET Schreiben = 1
WHERE UserGruppe.UserID IN(
	SELECT DISTINCT(U.UserID)
	FROM UserPw AS U
	INNER JOIN @userRoles AS UR ON UR.UserName = U.UserName AND UR.RoleName = 'Spielplan ändern' COLLATE DATABASE_DEFAULT
	INNER JOIN UserGruppe AS UG ON UG.UserID = U.UserID AND UG.BerechtigungsbereichID = 2 AND UG.GruppeID = 1
) AND BerechtigungsbereichID = 2 AND GruppeID = 1

--FÜR ALLE DIE NOCH KEINE BERECHTIGUNG IM BERECHTIGUNGSBEREICH HABEN UND DIE DATENBAK BERECHTIGUNG "SPIELPLAN SCHREIBEN" HABEN WIRD EIN DATENSATZ ANGELEGT
INSERT INTO UserGruppe (UserID, GruppeID, BerechtigungsbereichID, Schreiben)
	SELECT DISTINCT(U.UserID), 1, 2, 1 
	FROM UserPw AS U
	INNER JOIN @userRoles AS UR ON UR.UserName = U.UserName AND UR.RoleName = 'Spielplan ändern' COLLATE DATABASE_DEFAULT
	WHERE U.UserID NOT IN (
		SELECT UG.UserID 
		FROM UserGruppe AS UG 
		WHERE UG.BerechtigungsbereichID = 2 AND UG.GruppeID = 1
	)
END
GO

--2011-04-11 SH
--Neue Spalte "zulagenpflichtig" in AufführgTabelle
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IsExtraPayLiable' AND o.id = OBJECT_ID(N'[dbo].AufführgTabelle'))
BEGIN 	
	ALTER TABLE dbo.AufführgTabelle ADD IsExtraPayLiable BIT NOT NULL CONSTRAINT DF_AufführgTabelle_IsExtraPayLiable DEFAULT 0	
END
GO

--Tabelle für Rollen-Kategorien
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[RoleCategories]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].RoleCategories (
	RoleCategoryId INT IDENTITY(1,1) NOT NULL,
	Name VARCHAR (200) NULL,
	Points FLOAT NOT NULL CONSTRAINT DF_RoleCategories_Points DEFAULT (0),
	[LC] DATETIME NOT NULL,
	[UC] INT NOT NULL,
	[LM] DATETIME NOT NULL,
	[UM] INT NOT NULL,
	CONSTRAINT PK_RoleCategories PRIMARY KEY CLUSTERED (RoleCategoryId ASC) ON [PRIMARY],
	CONSTRAINT UQ_RoleCategories_Name UNIQUE NONCLUSTERED (Name ASC) ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON [dbo].[RoleCategories] TO [public]
GRANT UPDATE ON [dbo].[RoleCategories] TO [Stammdaten ändern]
GRANT INSERT ON [dbo].[RoleCategories] TO [Stammdaten ändern]
GRANT DELETE ON [dbo].[RoleCategories] TO [Stammdaten ändern]
GO
--2011-04-12 TH
--Neue Spalte in rollen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'RoleCategoryId' AND o.id = OBJECT_ID(N'[dbo].BesetzungStd'))
BEGIN
	ALTER TABLE dbo.BesetzungStd ADD RoleCategoryId INT NULL CONSTRAINT FK_Roles_RoleCategories FOREIGN KEY (RoleCategoryId) REFERENCES dbo.RoleCategories (RoleCategoryId)
END
GO

--2011-04-13 TH
--Neue Tabelle für Szenen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Scenes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
--DROP Table [dbo].Roles_Scenes
--DROP TABLE [dbo].Scenes
CREATE TABLE [dbo].Scenes (
	SceneId INT IDENTITY(1,1) NOT NULL,
	ActId INT NOT NULL,
	Name VARCHAR (200) NULL,
	[LC] DATETIME NOT NULL,
	[UC] INT NOT NULL,
	[LM] DATETIME NOT NULL,
	[UM] INT NOT NULL,
	CONSTRAINT PK_Scenes PRIMARY KEY CLUSTERED (SceneId ASC) ON [PRIMARY],
	CONSTRAINT FK_Scenes_ProductionTimeFlows FOREIGN KEY (ActId) REFERENCES dbo.ProductionTimeFlow (ProductionTimeFlowId)
) ON [PRIMARY]
END
GO

GRANT SELECT ON [dbo].Scenes TO Public
GRANT DELETE ON [dbo].Scenes TO [Stammdaten ändern]
GRANT INSERT ON [dbo].Scenes TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].Scenes TO [Stammdaten ändern]

GO
--Neue Tabelle zur Zuordnung von Rollen zu Szenen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Roles_Scenes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].Roles_Scenes (
	RolesScenesId INT IDENTITY(1,1) NOT NULL,
	RoleId INT NOT NULL,
	SceneId INT NOT NULL,
	[LC] DATETIME NOT NULL,
	[UC] INT NOT NULL,
	[LM] DATETIME NOT NULL,
	[UM] INT NOT NULL,
	CONSTRAINT PK_Roles_Scenes PRIMARY KEY CLUSTERED (RolesScenesId ASC) ON [PRIMARY],
	CONSTRAINT FK_Roles_Scenes_Roles FOREIGN KEY (RoleId) REFERENCES dbo.BesetzungStd (ID) ON DELETE CASCADE,
	CONSTRAINT FK_Roles_Scenes_Scenes FOREIGN KEY (SceneId) REFERENCES dbo.Scenes (SceneId) ON DELETE CASCADE,
	CONSTRAINT UQ_Roles_Scenes_RoleId_SceneId UNIQUE NONCLUSTERED (RoleId, SceneId ASC) ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON [dbo].Roles_Scenes TO Public
GRANT DELETE ON [dbo].Roles_Scenes TO [Stammdaten ändern]
GRANT INSERT ON [dbo].Roles_Scenes TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].Roles_Scenes TO [Stammdaten ändern]

GO


--2011 04 13TK
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'CastWorkingHoursSettings' AND o.id = OBJECT_ID(N'[dbo].VertragsVorlagen'))
BEGIN
	ALTER TABLE dbo.VertragsVorlagen ADD CastWorkingHoursSettings Varchar(2000)
END
GO

--2011-04-18 TH
--Neue Tabelle zum verknüpfen von Rollen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[RoleConnection]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].RoleConnection (
	RoleConnectionId INT IDENTITY(1,1) NOT NULL,
	ParentRoleId INT NOT NULL,
	ChildRoleId INT NOT NULL,
	[LC] DATETIME NOT NULL,
	[UC] INT NOT NULL,
	[LM] DATETIME NOT NULL,
	[UM] INT NOT NULL,
	CONSTRAINT PK_RoleConnection PRIMARY KEY CLUSTERED (RoleConnectionId ASC) ON [PRIMARY],
	CONSTRAINT FK_Roles_Roles_Parent FOREIGN KEY (ParentRoleId) REFERENCES dbo.BesetzungStd (ID),
	CONSTRAINT FK_Roles_Roles_Child FOREIGN KEY (ChildRoleId) REFERENCES dbo.BesetzungStd (ID),
	CONSTRAINT UQ_RoleConnection_ParentRoleId_ChildRoleId UNIQUE NONCLUSTERED (ParentRoleId, ChildRoleId ASC) ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON [dbo].RoleConnection TO Public
GRANT DELETE ON [dbo].RoleConnection TO [Stammdaten ändern]
GRANT INSERT ON [dbo].RoleConnection TO [Stammdaten ändern]
GRANT UPDATE ON [dbo].RoleConnection TO [Stammdaten ändern]

GO

------------------------------------------------------------------
-- Übernommen aus Pre-Release damit theadispo v3 "funktioniert" --
------------------------------------------------------------------
--2011-04-11 SH
--Neue Spalte "zulagenpflichtig" in AufführgTabelle
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IsExtraPayLiable' AND o.id = OBJECT_ID(N'[dbo].AufführgTabelle'))
BEGIN 	
	ALTER TABLE dbo.AufführgTabelle ADD IsExtraPayLiable BIT NOT NULL CONSTRAINT DF_AufführgTabelle_IsExtraPayLiable DEFAULT 0	
END
GO
------------------------------------------------------------------
UPDATE Gruppe SET vDatum = '30000101' WHERE vDatum IS NULL
GO

--2011-05-13 TH
--Neue Relation zwischen RollenLtg undQualification zur zuordnung von "Instrumenten" (Orchester)
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o ON c.id = o.id
	WHERE c.name = 'QualificationId' AND o.id = OBJECT_ID(N'[dbo].RollenLtg'))
BEGIN
	ALTER TABLE dbo.RollenLtg ADD QualificationId INT NULL CONSTRAINT FK_RoleLtg_Qualification FOREIGN KEY (QualificationId) REFERENCES Qualification (QualificationId)
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o ON c.id = o.id
	WHERE c.name = 'Module' AND o.id = OBJECT_ID(N'[dbo].RollenLtg'))
BEGIN
	ALTER TABLE dbo.RollenLtg ADD Module INT NOT NULL CONSTRAINT DF_RoleLtg_Module DEFAULT 1
END
GO

--Neue Tabelle zum Verbinden von Qualificationen einer Person und deren Verträgen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Contract_Qualification_Person]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].Contract_Qualification_Person (
	ContractQualificationPersonId INT IDENTITY(1,1) NOT NULL,
	ContractId INT NOT NULL,
	QualificationPersonId INT NOT NULL,
	[LC] DATETIME NOT NULL,
	[UC] INT NOT NULL,
	[LM] DATETIME NOT NULL,
	[UM] INT NOT NULL,
	CONSTRAINT PK_ContractQualificationPerson PRIMARY KEY CLUSTERED (ContractQualificationPersonId ASC) ON [PRIMARY],
	CONSTRAINT FK_Contract_Qualification_Person_Contract FOREIGN KEY (ContractId) REFERENCES dbo.Vertrag (VertragsNr),
	CONSTRAINT FK_Contract_Qualification_Person_Qualification_Person FOREIGN KEY (QualificationPersonId) REFERENCES dbo.Qualification_Person (Qualification_PersonId),
	CONSTRAINT UQ_ContractQualificationPerson_ContractId_QualificationPersonId UNIQUE NONCLUSTERED (ContractId, QualificationPersonId ASC) ON [PRIMARY]
) ON [PRIMARY]
END
GO

GRANT SELECT ON [dbo].Contract_Qualification_Person TO Public
REVOKE DELETE ON [dbo].Contract_Qualification_Person TO [PersoContractWrite]
GO

--Die Qualificationen einer Person um einen Wert für Rang/Wertigkeit erweitern
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o ON o.id = c.id
	WHERE c.name = 'Priority' AND o.id = OBJECT_ID(N'[dbo].Qualification_Person'))
BEGIN
	ALTER TABLE dbo.Qualification_Person ADD Priority INT NOT NULL CONSTRAINT DF_Qualification_Person_Priority DEFAULT 0	
END
GO

--2011-05-20
--Formelkonfigurationen

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FormulaConfigurations]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].FormulaConfigurations (
	FormulaConfigurationId INT IDENTITY(1,1) NOT NULL,
	Name VARCHAR(50) NOT NULL,
	Code VARCHAR(5) NOT NULL,
	SerializedParameter TEXT NULL,
	FormulaId VARCHAR(256) NOT NULL,
	Modul INT NOT NULL,
	[LC] DATETIME NOT NULL,
	[UC] INT NOT NULL,
	[LM] DATETIME NOT NULL,
	[UM] INT NOT NULL,
	CONSTRAINT PK_FormulaConfiguration PRIMARY KEY CLUSTERED (FormulaConfigurationId ASC) ON [PRIMARY],
) ON [PRIMARY]
END
GO

GRANT SELECT ON [dbo].FormulaConfigurations TO Public
GRANT DELETE ON [dbo].FormulaConfigurations TO [PersoAdmin], [ChorAdmin], [TheaOrchester]
GRANT INSERT ON [dbo].FormulaConfigurations TO [PersoAdmin], [ChorAdmin], [TheaOrchester]
GRANT UPDATE ON [dbo].FormulaConfigurations TO [PersoAdmin], [ChorAdmin], [TheaOrchester]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FormulaConfigurations_Departments]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].FormulaConfigurations_Departments (
	FormulaConfiguration_DepartmentId INT IDENTITY(1,1) NOT NULL,
	FormulaConfigurationId INT NOT NULL,
	DepartmentId INT NOT NULL,
	[LC] DATETIME NOT NULL,
	[UC] INT NOT NULL,
	[LM] DATETIME NOT NULL,
	[UM] INT NOT NULL,
	CONSTRAINT PK_FormulaConfigurations_Departments PRIMARY KEY CLUSTERED (FormulaConfiguration_DepartmentId ASC) ON [PRIMARY],
	CONSTRAINT FK_FormulaConfigurations_Departments_Departments FOREIGN KEY (DepartmentId) REFERENCES dbo.DienstplanArtenTabelle (DienstplanArtenID),
	CONSTRAINT FK_FormulaConfigurations_Departments_FormulaConfigurations FOREIGN KEY (FormulaConfigurationId) REFERENCES dbo.FormulaConfigurations (FormulaConfigurationId),
) ON [PRIMARY]
END
GO

GRANT SELECT ON [dbo].FormulaConfigurations_Departments TO Public
GRANT DELETE ON [dbo].FormulaConfigurations_Departments TO [PersoAdmin], [ChorAdmin], [TheaOrchester]
GRANT INSERT ON [dbo].FormulaConfigurations_Departments TO [PersoAdmin], [ChorAdmin], [TheaOrchester]
GRANT UPDATE ON [dbo].FormulaConfigurations_Departments TO [PersoAdmin], [ChorAdmin], [TheaOrchester]
GO
--2011-05-20 SH
--originaltitel von speziellen stücken setzen damit in der produktionsmakse keine fehlermeldung kommt
UPDATE Stücke SET OriginalTitel = Titel WHERE OriginalTitel IS NULL AND (Snr IN (-1,-2) OR Titel = '*')
GO

--2011-05-17
--neue Spalte IsPublicAccessible im Plan
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IsPublicAccessible' AND o.id = OBJECT_ID(N'[dbo].Plan'))
BEGIN
	ALTER TABLE dbo.[Plan] ADD IsPublicAccessible BIT NOT NULL CONSTRAINT DF_Plan_IsPublicAccessible DEFAULT 0
END
GO



GRANT DELETE ON [dbo].SalaryLevel TO ChorAdmin
GRANT INSERT ON [dbo].SalaryLevel TO ChorAdmin
GRANT UPDATE ON [dbo].SalaryLevel TO ChorAdmin

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ProductionId' AND o.id = OBJECT_ID(N'[dbo].VertragRolle'))
BEGIN 	 
	ALTER TABLE dbo.VertragRolle ADD ProductionId INT NULL 
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'FeeRuleSettings' AND o.id = OBJECT_ID(N'[dbo].SalaryLevel'))
BEGIN 	 
	ALTER TABLE dbo.SalaryLevel ADD FeeRuleSettings TEXT 
	ALTER TABLE dbo.SalaryLevel ADD IsInactive BIT NOT NULL CONSTRAINT DF_SalaryLevel_IsInactive DEFAULT (0)
	UPDATE dbo.SalaryLevel SET Module = 4 WHERE Module  IS NULL or Module = 0
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractRole_Productions]') AND type = 'F')
ALTER TABLE [dbo].[VertragRolle]  WITH CHECK ADD  CONSTRAINT [FK_ContractRole_Productions] FOREIGN KEY([ProductionId])
REFERENCES [dbo].[Stücke] ([Snr])
GO
ALTER TABLE [dbo].[VertragRolle] CHECK CONSTRAINT [FK_ContractRole_Productions]


IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'UserName' AND o.id = OBJECT_ID(N'[dbo].userpw') AND c.prec < 60)
BEGIN
	ALTER TABLE userpw ALTER COLUMN UserName VARCHAR(60)
END

--TK 2011-06-18 Bezeichnug für aufftypen  auf 40 (+1)
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TagBez' AND o.id = OBJECT_ID(N'[dbo].aufftypen') AND c.prec < 40)
BEGIN
	ALTER TABLE aufftypen ALTER COLUMN TagBez VARCHAR(40)
END

-- 20110622 TK Bemerkungen pro rolle u. Spz
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Role_Season]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].Role_Season (
	Role_SeasonId INT IDENTITY(1,1) NOT NULL,
	RoleId INT NOT NULL,
	SeasonId INT NOT NULL,
	Note Text,
	[LC] DATETIME NOT NULL,
	[UC] INT NOT NULL,
	[LM] DATETIME NOT NULL,
	[UM] INT NOT NULL,
	CONSTRAINT PK_Role_SeasonId PRIMARY KEY CLUSTERED (Role_SeasonId ASC) ON [PRIMARY],
	CONSTRAINT FK_Role_Season_Role FOREIGN KEY (RoleId) REFERENCES dbo.BesetzungStd (id)  ON DELETE CASCADE,
	CONSTRAINT FK_Role_Season_Season FOREIGN KEY (SeasonId) REFERENCES dbo.Spielzeittabelle (SpzNr)  ON DELETE CASCADE,
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Role_Season]')  AND name = 'IX_RoleID_SeasonId')
BEGIN
CREATE UNIQUE NONCLUSTERED INDEX IX_RoleID_SeasonId ON dbo.Role_Season	(RoleId, SeasonId) ON [PRIMARY]
END
GO

GRANT SELECT ON [dbo].Role_Season TO [Spielplan ändern], [Spielplan alles lesen]
GRANT DELETE ON [dbo].Role_Season TO [Spielplan ändern]
GRANT INSERT ON [dbo].Role_Season TO [Spielplan ändern]
GRANT UPDATE ON [dbo].Role_Season TO [Spielplan ändern]
GO

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

CREATE FUNCTION [dbo].[SplitIds](@OrderList varchar(4000))
RETURNS 
	@ParsedList TABLE( OrderID INT)
AS
BEGIN
    DECLARE @OrderID varchar(10), @Pos INT

    SET @OrderList = LTRIM(RTRIM(@OrderList))+ ','
    SET @Pos = CHARINDEX(',', @OrderList, 1)

    IF REPLACE(@OrderList, ',', '') <> ''
    BEGIN
        WHILE @Pos > 0
        BEGIN
            SET @OrderID = LTRIM(RTRIM(LEFT(@OrderList, @Pos - 1)))
            IF @OrderID <> ''
            BEGIN
                    INSERT INTO @ParsedList (OrderID) 
                    VALUES (CAST(@OrderID AS int)) --Use Appropriate conversion
            END
            SET @OrderList = RIGHT(@OrderList, LEN(@OrderList) - @Pos)
            SET @Pos = CHARINDEX(',', @OrderList, 1)

        END
    END 
    RETURN
END
go

--TK 2011-06-30 SP zum Dienste zählern
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].CountCast'))
BEGIN
	DROP PROCEDURE dbo.CountCast 
END
go


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

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

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

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

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

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

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

IF @countType = 0
	--Anzahl
	BEGIN
		IF @activitytypIds IS NULL
			--ohne Aufftypfilter
			BEGIN 
				SELECT ca.PersNr, CAST(COUNT (DISTINCT ca.AuffNr) AS float) AS Sum  
				FROM		AufführgTabelle ac
					INNER JOIN Besetzungtabelle	AS ca	ON ac.Auffnr =ca.auffnr
					INNER JOIN BesetzungStd		AS r	ON ca.RolleID =r.id
					INNER JOIN #personIds				ON ca.PersNr = #personIds.id
					INNER JOIN #groupIds				ON r.Besitzer = #groupIds.id
				WHERE Datum BETWEEN @start AND @end 
					AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
					AND ac.Status BETWEEN 0 AND 99 	
				GROUP BY PersNr
			END
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT ca.PersNr, CAST(COUNT (DISTINCT ca.AuffNr) AS float) AS Sum  
				FROM		AufführgTabelle ac
					INNER JOIN Besetzungtabelle	AS ca	ON ac.Auffnr =ca.auffnr
					INNER JOIN BesetzungStd		AS r	ON ca.RolleID =r.id
					INNER JOIN #personIds				ON ca.PersNr = #personIds.id
					INNER JOIN #groupIds				ON r.Besitzer = #groupIds.id
					INNER JOIN #activitytypIds			ON ac.art = #activitytypIds.id
				WHERE Datum BETWEEN @start AND @end 
					AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
					AND ac.Status BETWEEN 0 AND 99 
				GROUP BY PersNr
			END
		END
	ELSE IF @countType = 1
		--Anrechenbare
		BEGIN
		IF @activitytypIds IS NULL
		--ohne Aufftypfilter
			BEGIN 
				SELECT PersNr, SUM(Sum1) FROM (SELECT PersNr, ca.AuffNr, 
					MAX(ISNULL(ca.Creditable,
						ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr > 10 THEN ISNULL(ProdDep.ShiftCount ,1) ELSE 1 END))) AS Sum1 
				FROM		AufführgTabelle			AS ac
					INNER JOIN AuffTypen			AS at		ON at.AuffTNr = ac.Art
					INNER JOIN Besetzungtabelle		AS ca		ON ac.Auffnr =ca.auffnr
					INNER JOIN BesetzungStd			AS r		ON ca.RolleID =r.id
					LEFT JOIN AuffDienstplanArten	AS ActDep	ON ac.AuffNr = ActDep.AuffNr AND ActDep.DienstplanArtenID = @departmentId
					LEFT JOIN StückeDienstplan		AS ProdDep	ON ac.SNr = ProdDep.Snr AND ProdDep.DienstplanArtenID = @departmentId
					INNER JOIN #personIds						ON ca.PersNr = #personIds.id
					INNER JOIN #groupIds						ON r.Besitzer = #groupIds.id
					WHERE Datum BETWEEN @start AND @end 
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY PersNr, ca.AuffNr) AS SubSQL GROUP BY PersNr 
			END
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT PersNr, SUM(Sum1) FROM (SELECT PersNr, ca.AuffNr, MAX(ISNULL(ca.Creditable,
						ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr > 10 THEN ISNULL(ProdDep.ShiftCount ,1) ELSE 1 END))) AS Sum1 
				FROM		AufführgTabelle			AS ac
					INNER JOIN AuffTypen			AS at		ON at.AuffTNr = ac.Art
					INNER JOIN Besetzungtabelle		AS ca		ON ac.Auffnr = ca.auffnr
					INNER JOIN BesetzungStd			AS r		ON ca.RolleID = r.id
					LEFT JOIN AuffDienstplanArten	AS ActDep	ON ac.AuffNr = ActDep.AuffNr AND ActDep.DienstplanArtenID = @departmentId
					LEFT JOIN StückeDienstplan		AS ProdDep	ON ac.SNr = ProdDep.Snr AND ProdDep.DienstplanArtenID = @departmentId
					INNER JOIN #personIds						ON ca.PersNr = #personIds.id
					INNER JOIN #groupIds						ON r.Besitzer = #groupIds.id
					INNER JOIN #activitytypIds					ON ac.art = #activitytypIds.id
					WHERE Datum BETWEEN @start AND @end 
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY PersNr, ca.AuffNr) AS SubSQL GROUP BY PersNr 
			END	
		END
ELSE IF @countType = 2
	BEGIN
	--Zählen pro Tag max 2 Dienst  (morgens < 14:00 und abends)
			IF @activitytypIds IS NULL
		--ohne Aufftypfilter
			BEGIN 
				SELECT PersNr, SUM(Sum1) FROM (SELECT PersNr, CONVERT(VARCHAR(10),ac.datum,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.UhrBeg, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, 
					MAX(ISNULL(ca.Creditable, ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr > 10 THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
				FROM		AufführgTabelle			AS ac
					INNER JOIN AuffTypen			AS at	ON at.AuffTNr = ac.Art
					INNER JOIN Besetzungtabelle		AS ca	ON ac.Auffnr = ca.auffnr
					INNER JOIN BesetzungStd			AS r	ON ca.RolleID = r.id
					LEFT JOIN AuffDienstplanArten	AS ActDep ON ac.AuffNr = ActDep.AuffNr AND ActDep.DienstplanArtenID = @departmentId
					LEFT JOIN StückeDienstplan		AS ProdDep ON ac.SNr = ProdDep.Snr AND ProdDep.DienstplanArtenID = @departmentId
					INNER JOIN #personIds				ON ca.PersNr = #personIds.id
					INNER JOIN #groupIds				ON r.Besitzer = #groupIds.id
					WHERE Datum BETWEEN @start AND @end 
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY PersNr, CONVERT(VARCHAR(10),ac.datum,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.UhrBeg, 108) > '14:00'  THEN '2' ELSE '1' END) AS SubSQL GROUP BY PersNr 
			END
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT PersNr, SUM(Sum1) FROM (SELECT PersNr, CONVERT(VARCHAR(10),ac.datum,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.UhrBeg, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, MAX(ISNULL(ca.Creditable,
						ISNULL(ActDep.ShiftCount, CASE WHEN at.KatNr > 10 THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
				FROM		AufführgTabelle			AS ac
					INNER JOIN AuffTypen			AS at	ON at.AuffTNr = ac.Art
					INNER JOIN Besetzungtabelle		AS ca	ON ac.Auffnr = ca.auffnr
					INNER JOIN BesetzungStd			AS r	ON ca.RolleID = r.id
					LEFT JOIN AuffDienstplanArten	AS ActDep ON ac.AuffNr = ActDep.AuffNr AND ActDep.DienstplanArtenID = @departmentId
					LEFT JOIN StückeDienstplan		AS ProdDep ON ac.SNr = ProdDep.Snr AND ProdDep.DienstplanArtenID = @departmentId
					INNER JOIN #personIds				ON ca.PersNr = #personIds.id
					INNER JOIN #groupIds				ON r.Besitzer = #groupIds.id
					INNER JOIN #activitytypIds			ON ac.art = #activitytypIds.id
					WHERE Datum BETWEEN @start AND @end 
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY PersNr, CONVERT(VARCHAR(10),ac.datum,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.UhrBeg, 108) > '14:00'  THEN '2' ELSE '1' END) AS SubSQL GROUP BY PersNr 
			END		
	END
ELSE IF @countType = 3
	BEGIN
	--Zählen pro Tag max 2 Dienst  (morgens < 14:00 und abends)
			IF @activitytypIds IS NULL
		--ohne Aufftypfilter
			BEGIN 
				SELECT PersNrDay, SUM(SumDay) FROM(
				SELECT PersNr AS PersNrDay, datum, SUM(Sum1)-1  AS [SumDay]
				FROM (
					SELECT PersNr, ac.datum, CONVERT(VARCHAR(10),ac.datum,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.UhrBeg, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, 
						MAX(ISNULL(ca.Creditable, ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr > 10 
							THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
					FROM		AufführgTabelle			AS ac
					INNER JOIN AuffTypen			AS at	ON at.AuffTNr = ac.Art
					INNER JOIN Besetzungtabelle		AS ca	ON ac.Auffnr = ca.auffnr
					INNER JOIN BesetzungStd			AS r	ON ca.RolleID = r.id
					LEFT JOIN AuffDienstplanArten	AS ActDep ON ac.AuffNr = ActDep.AuffNr AND ActDep.DienstplanArtenID =@departmentId
					LEFT JOIN StückeDienstplan		AS ProdDep ON ac.SNr = ProdDep.Snr AND ProdDep.DienstplanArtenID = @departmentId
					INNER JOIN #personIds				ON ca.PersNr = #personIds.id
					INNER JOIN #groupIds				ON r.Besitzer = #groupIds.id
					WHERE Datum BETWEEN @start AND @end
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY PersNr, ac.datum, CONVERT(VARCHAR(10),ac.datum,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.UhrBeg, 108) > '14:00'  THEN '2' ELSE '1' END) AS SubSQL 
				GROUP BY PersNr, datum)  AS subDay Group By PersNrDay
END		
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT PersNrDay, SUM(SumDay) FROM(
				SELECT PersNr AS PersNrDay, datum, SUM(Sum1)-1  AS [SumDay]
				FROM (
					SELECT PersNr, ac.datum, CONVERT(VARCHAR(10),ac.datum,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.UhrBeg, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, 
						MAX(ISNULL(ca.Creditable, ISNULL(ActDep.ShiftCount, 
						CASE WHEN at.KatNr > 10 
							THEN ISNULL(ProdDep.ShiftCount, 1) ELSE 1 END))) AS Sum1 
					FROM		AufführgTabelle			AS ac
					INNER JOIN AuffTypen			AS at	ON at.AuffTNr = ac.Art
					INNER JOIN Besetzungtabelle		AS ca	ON ac.Auffnr = ca.auffnr
					INNER JOIN BesetzungStd			AS r	ON ca.RolleID = r.id
					LEFT JOIN AuffDienstplanArten	AS ActDep ON ac.AuffNr = ActDep.AuffNr AND ActDep.DienstplanArtenID =@departmentId
					LEFT JOIN StückeDienstplan		AS ProdDep ON ac.SNr = ProdDep.Snr AND ProdDep.DienstplanArtenID = @departmentId
					INNER JOIN #personIds				ON ca.PersNr = #personIds.id
					INNER JOIN #groupIds				ON r.Besitzer = #groupIds.id
					INNER JOIN #activitytypIds			ON ac.art = #activitytypIds.id
					WHERE Datum BETWEEN @start AND @end
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND ac.Status BETWEEN 0 AND 99
					GROUP BY PersNr, ac.datum, CONVERT(VARCHAR(10),ac.datum,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.UhrBeg, 108) > '14:00'  THEN '2' ELSE '1' END) AS SubSQL 
				GROUP BY PersNr, datum)  AS subDay Group By PersNrDay
			END		
	END
ELSE IF @countType = 4
	BEGIN
		IF @activitytypIds IS NULL
			--ohne Aufftypfilter
			BEGIN 
				SELECT ca.PersNr, CAST(COUNT (DISTINCT ac.Datum) AS float) AS Sum  
				FROM		AufführgTabelle ac
					INNER JOIN Besetzungtabelle	AS ca	ON ac.Auffnr =ca.auffnr
					INNER JOIN BesetzungStd		AS r	ON ca.RolleID =r.id
					INNER JOIN #personIds				ON ca.PersNr = #personIds.id
					INNER JOIN #groupIds				ON r.Besitzer = #groupIds.id
				WHERE Datum BETWEEN @start AND @end 
					AND ca.IsCanceled = 0 
					AND ac.Status BETWEEN 0 AND 99 	
				GROUP BY PersNr
			END
		ELSE
		--mit Aufftypfilter
			BEGIN
				SELECT ca.PersNr, CAST(COUNT (DISTINCT ac.Datum) AS float) AS Sum  
				FROM		AufführgTabelle ac
					INNER JOIN Besetzungtabelle	AS ca	ON ac.Auffnr =ca.auffnr
					INNER JOIN BesetzungStd		AS r	ON ca.RolleID =r.id
					INNER JOIN #personIds				ON ca.PersNr = #personIds.id
					INNER JOIN #groupIds				ON r.Besitzer = #groupIds.id
					INNER JOIN #activitytypIds			ON ac.art = #activitytypIds.id
				WHERE Datum BETWEEN @start AND @end 
					AND ca.IsCanceled = 0 
					AND ac.Status BETWEEN 0 AND 99 
				GROUP BY PersNr
			END
		END


END		
	DROP TABLE #groupIds
	DROP TABLE  #personIds
	IF @activitytypIds IS NOT NULL
	BEGIN
		DROP TABLE #activitytypIds
	END

GO
GRANT EXECUTE ON CountCast TO Public
GO

--TK 2011-07-1 SP Name von 10 auf 15 Stellenn
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DienstplanBez' AND o.id = OBJECT_ID(N'[dbo].DienstplanArtenTabelle') AND c.prec < 15)
BEGIN
	ALTER TABLE DienstplanArtenTabelle ALTER COLUMN DienstplanBez VARCHAR(15)
END




--TK 2011-06-28 Index entfernt (führt in V4 zu Fehler)
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PlanSort]')  AND name = 'TextID_SpalteID')
	DROP Index PlanSort.TextID_SpalteID

GO
--TK 20110811 Doppelte User entfernen
DELETE FROM UserGruppe WHERE UserID IN (SELECT  MAX(userid) FROM UserPw Group by Username Having count(*)>1)
DELETE FROM UserLicenses WHERE UserID IN (SELECT  MAX(userid) FROM UserPw Group by Username Having count(*)>1)
DELETE FROM UserPw WHERE UserID IN (SELECT  MAX(userid) FROM UserPw Group by Username Having count(*)>1)
GO

--Wenn immernoch doppelte vorhanden sind, muss die Tabelle manuell bereinigt werden
--Nach erneutem ausführen wird ein eindeutiger Index erstellt
IF  EXISTS (SELECT * FROM UserPw Group by Username Having   count(*)>1)	
	BEGIN
		RAISERROR('Es existeiren doppelte Anmeldenamen (UserPw)', 15, -1) WITH LOG
	END
ELSE
	BEGIN
		IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[UserPw]')  AND name = 'IX_UserName')
		BEGIN
			CREATE UNIQUE NONCLUSTERED INDEX IX_UserName ON dbo.UserPw (UserName) ON [PRIMARY]
		END
	END
GO

--TK 2011-06-29 NOT NULL für DiplaDru gesetzt
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DiplaDru' AND o.id = OBJECT_ID(N'[dbo].[AufführgTabelle]') AND c.isnullable = 1)
BEGIN	
	IF (SELECT c.cdefault FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id
		WHERE c.name = 'DiplaDru' AND o.id = OBJECT_ID(N'dbo.AufführgTabelle')) <> 0
		EXECUTE sp_unbindefault N'dbo.AufführgTabelle.DiplaDru'

	UPDATE AufführgTabelle SET DiplaDru = 0 WHERE  DiplaDru IS NULL
	ALTER TABLE [dbo].[AufführgTabelle]  ALTER COLUMN [DiplaDru] BIT NOT NULL
	ALTER TABLE [dbo].[AufführgTabelle] ADD CONSTRAINT DF_Activities_PrintEndTime DEFAULT (0) FOR [DiplaDru]
END


IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'alt' AND o.id = OBJECT_ID(N'[dbo].[Persh]') AND c.isnullable = 1)
BEGIN	
	UPDATE persh SET alt = 0 WHERE alt IS NULL
	ALTER TABLE [dbo].persh  ALTER COLUMN alt SMALLINT NOT NULL
	ALTER TABLE [dbo].persh ADD CONSTRAINT DF_Personal_inactive DEFAULT (0) FOR alt
END

--TK 2011-07-13 Dienstplanbemerkung vergrößert
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Bemerkung' AND o.id = OBJECT_ID(N'[dbo].Dienstplan') AND c.prec < 100)
BEGIN
	ALTER TABLE Dienstplan ALTER COLUMN Bemerkung VARCHAR(100)
	ALTER TABLE Dienstplan ALTER COLUMN Anmerkung VARCHAR(50)
END
-- 2011-07-26 SH
-- neue Spalte für kalkulatorische Vertragstermine
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IsCostingDate' AND o.id = OBJECT_ID(N'[dbo].ContractDates'))
BEGIN
	ALTER TABLE dbo.[ContractDates] ADD IsCostingDate BIT NOT NULL CONSTRAINT DF_ContractDates_IsCostingDate DEFAULT 0
END
GO

-- 2011-07-26 SH
-- neue Spalte für Notizen in Arbeitsbereichen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'Note' AND o.id = OBJECT_ID(N'[dbo].AB'))
BEGIN
	ALTER TABLE dbo.[AB] ADD Note varchar(100) NULL
END
GO
--2011-08-10 TK
--neu Spalte für Filter im Header
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'HeaderSettings' AND o.id = OBJECT_ID(N'[dbo].DienstplanArtenTabelle'))
BEGIN
	ALTER TABLE dbo.[DienstplanArtenTabelle] ADD HeaderSettings varchar(2000) NULL
END
GO
--2011-08-11 TK
--neu Spalte für Sortierung 
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'[dbo].QualificationCategory'))
BEGIN
	ALTER TABLE dbo.QualificationCategory ADD Sort INT NOT NULL  CONSTRAINT DF_QualificationCategory_Sort DEFAULT 0
END
GO
--Text für Zusatzdaten vergrößert 
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ZDText' AND o.id = OBJECT_ID(N'[dbo].PersZusatzDaten') AND c.prec < 500)
BEGIN
	ALTER TABLE PersZusatzDaten ALTER COLUMN ZDText VARCHAR(500)
END
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BesBem' AND o.id = OBJECT_ID(N'[dbo].BesetzungTabelle') AND c.prec < 20)
BEGIN
	ALTER TABLE BesetzungTabelle ALTER COLUMN BesBem VARCHAR(20)
END
GO

--2011-0905 TH
--Spalte für Passnr. auf 30 Zeichen vergrößert
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PassNr' AND o.id = OBJECT_ID(N'[dbo].PersonalDetails') AND c.prec < 30)
BEGIN
	ALTER TABLE PersonalDetails ALTER COLUMN PassNr VARCHAR(30)
END
GO

--2011-09-21 TH
--Neue Spalte Alternativtexte in Tagesplanabschnitten eingefügt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'EmptySectionText' AND o.id = OBJECT_ID(N'[dbo].TagSparteSort'))
BEGIN
	ALTER TABLE TagSparteSort ADD EmptySectionText VARCHAR(200)
END
GO
--2011-09-21 TK
--neu Spalte für Layout
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'LayoutSettings' AND o.id = OBJECT_ID(N'[dbo].DienstplanArtenTabelle'))
BEGIN
	ALTER TABLE dbo.[DienstplanArtenTabelle] ADD LayoutSettings varchar(2000) NULL
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'MonMinutes' and o.id = OBJECT_ID(N'[dbo].[VertragsVorlagen]'))
BEGIN
	ALTER TABLE dbo.VertragsVorlagen ADD MonMinutes int NOT NULL CONSTRAINT DF_ContractTypes_MonMinutes DEFAULT 0
	ALTER TABLE dbo.VertragsVorlagen ADD TueMinutes int NOT NULL CONSTRAINT DF_ContractTypes_TueMinutes DEFAULT 0
	ALTER TABLE dbo.VertragsVorlagen ADD WedMinutes int NOT NULL CONSTRAINT DF_ContractTypes_WedMinutes DEFAULT 0
	ALTER TABLE dbo.VertragsVorlagen ADD ThuMinutes int NOT NULL CONSTRAINT DF_ContractTypes_ThuMinutes DEFAULT 0
	ALTER TABLE dbo.VertragsVorlagen ADD FriMinutes int NOT NULL CONSTRAINT DF_ContractTypes_FriMinutes DEFAULT 0
	ALTER TABLE dbo.VertragsVorlagen ADD SatMinutes int NOT NULL CONSTRAINT DF_ContractTypes_SatMinutes DEFAULT 0
	ALTER TABLE dbo.VertragsVorlagen ADD SunMinutes int NOT NULL CONSTRAINT DF_ContractTypes_SunMinutes DEFAULT 0
	EXEC ('UPDATE dbo.VertragsVorlagen SET 
	MonMinutes = ROUND(AZMO * 60, 0) ,
	TueMinutes = ROUND(AZDI * 60, 0) ,
	WedMinutes = ROUND(AZMI * 60, 0) ,
	ThuMinutes = ROUND(AZDO * 60, 0) ,
	FriMinutes = ROUND(AZFR * 60, 0) ,
	SatMinutes = ROUND(AZSA * 60, 0) ,
	SunMinutes = ROUND(AZSO * 60, 0) ')
END

--2011-09-30 SH
--neue Spalte für PayOutBeforeFactor
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'PayOutBeforeFactor' AND o.id = OBJECT_ID(N'[dbo].TimeAccountUsage')) 
BEGIN
	ALTER TABLE dbo.[TimeAccountUsage] ADD PayOutBeforeFactor BIT NOT NULL CONSTRAINT DF_TimeAccountUsage_PayOutBeforeFactor DEFAULT 0
END
GO

--2011-10-05 SH
--Tabelle für Szenen pro Aktivität
--enthält nur die Grundform für momentane Anforderung der Hinterlegung eines Zahlenwertes (Aus welcher Standardbesetzung wurde besetzt)
--änderung vom 2011-10-18 SH: UQ Key geändert
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ActivityScenes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].ActivityScenes (
	ActivityScenesId INT IDENTITY(1,1) NOT NULL,
	ActivityId INT NOT NULL,
	SceneId INT NULL,
	ScheduledBasicCast INT NULL,
	[LC] DATETIME NOT NULL,
	[UC] INT NOT NULL,
	[LM] DATETIME NOT NULL,
	[UM] INT NOT NULL,
	CONSTRAINT PK_ActivityScenes PRIMARY KEY CLUSTERED (ActivityScenesId ASC) ON [PRIMARY],
	CONSTRAINT FK_ActivityScenes_Activities FOREIGN KEY (ActivityId) REFERENCES dbo.AufführgTabelle (AuffNr)  ON DELETE CASCADE,
	CONSTRAINT FK_ActivityScenes_Scenes FOREIGN KEY (SceneId) REFERENCES dbo.Scenes (SceneId)  ON DELETE CASCADE,
	CONSTRAINT UQ_ActivityScenes_ActivityId_SceneId_ScheduledBasicCast UNIQUE NONCLUSTERED (ActivityId ASC,SceneId ASC, ScheduledBasicCast ASC) ON [PRIMARY],
) ON [PRIMARY]
END
GO
-- berechtigungen erstmal auf public, eventuell bei erweiterung der tabelle anpassen
GRANT SELECT ON ActivityScenes TO public

GRANT DELETE ON ActivityScenes TO [Spielplan ändern]
GRANT INSERT ON ActivityScenes TO [Spielplan ändern]
GRANT UPDATE ON ActivityScenes TO [Spielplan ändern]
GO

--2011-10-18 SH
--löschen des alten unique constrains und erstellen des neuen falls notwendig
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UQ_ActivityScenes_ActivityId_SceneId]') )
	ALTER TABLE dbo.ActivityScenes DROP CONSTRAINT UQ_ActivityScenes_ActivityId_SceneId
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UQ_ActivityScenes_ActivityId_SceneId_ScheduledBasicCast]') )
	ALTER TABLE dbo.ActivityScenes ADD CONSTRAINT UQ_ActivityScenes_ActivityId_SceneId_ScheduledBasicCast UNIQUE NONCLUSTERED (ActivityId ASC,SceneId ASC, ScheduledBasicCast ASC)
GO

--2011-10-27 TH
--löschen es Eindeutigenindex auf Pos/Rolle
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[BesetzungStdSoliTabelle]')  AND name = 'IX_SeasonIdRoleIdSort' )
BEGIN
	
		DROP INDEX BesetzungStdSoliTabelle.IX_SeasonIdRoleIdSort
END
GO
--Einstellung für Understudy anlegen
IF NOT EXISTS (SELECT * FROM Settings WHERE Form = 'DispoSettings' AND [Control] = 'FirstStudyCastRank')
BEGIN
	INSERT INTO [dbo].[Settings]([Form], [Control], [Wert], [Pref], [WertText], [LM], [UM], [LC], [UC])
SELECT N'DispoSettings', N'FirstStudyCastRank', NULL, NULL, N'3', NULL, NULL, NULL, NULL
END
GO
--2011-10-24 TH
--View für die PersKom-Einträge angepasst, sodass die Berechtigungen richtig geprüft werden.
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

	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

--FK_Contract_Qualification_Person_Contract verwendet jetzt Löschweitergabe
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Contract_Qualification_Person_Contract]') )
BEGIN
	ALTER TABLE Contract_Qualification_Person
		DROP CONSTRAINT FK_Contract_Qualification_Person_Contract
	ALTER TABLE Contract_Qualification_Person
		ADD CONSTRAINT FK_Contract_Qualification_Person_Contract 
		FOREIGN KEY (ContractId) 
		REFERENCES Vertrag(VertragsNr)
		ON DELETE CASCADE
END
GO

--2011-09-05 SH
--neu Spalte für Sicherheitsoptionen von Dienstplanberechtigungen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'Options' AND o.id = OBJECT_ID(N'[dbo].UserGruppe'))
BEGIN
	ALTER TABLE dbo.UserGruppe ADD Options VARCHAR(2000) NULL
END
GO
--2011-11-09 TK
--Neuer Berechtigungsbereich für Produktionsdaten
IF NOT EXISTS (SELECT * FROM UserGruppe WHERE BerechtigungsbereichID = 3)
BEGIN
	INSERT INTO [UserGruppe]
           ([GruppeID],[UserID],[Schreiben],[LM],[UM],[LC],[UC] ,[BerechtigungsbereichID],[IsInherited])
    SELECT [GruppeID],[UserID],[Schreiben],[LM],[UM],[LC],[UC] ,3 ,[IsInherited]
	FROM [UserGruppe] WHERE BerechtigungsbereichID = 2
END


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

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

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

GO
CREATE VIEW [dbo].[Productions_Update]
AS 
SELECT *
FROM Stücke 
WHERE Snr IN 
		(SELECT SNr 
		 FROM	UserGruppe 	INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
					 INNER JOIN Stücke AS P ON P.ModuleGroupId = UserGruppe.GruppeID
		 WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 3 ANd Schreiben = 1)	

GO
GRANT SELECT ON [Productions_Update] TO Public
GRANT DELETE ON [Productions_Update] TO Public
GRANT INSERT ON [Productions_Update] TO Public
GRANT UPDATE ON [Productions_Update] TO Public
GO

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

CREATE VIEW [dbo].[ProductionsDetails_Update]
AS 
SELECT * FROM StückeDetails WHERE Snr IN 	(SELECT SNr 
		 FROM	UserGruppe 	INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
					 INNER JOIN Stücke AS P ON P.ModuleGroupId = UserGruppe.GruppeID
		 WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 3 ANd Schreiben = 1)	

GO
GRANT SELECT ON ProductionsDetails_Update TO Public
GRANT DELETE ON ProductionsDetails_Update TO Public
GRANT INSERT ON ProductionsDetails_Update TO Public
GRANT UPDATE ON ProductionsDetails_Update TO Public
go

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

CREATE VIEW [dbo].ProductionTimeFlow_Update
AS 
SELECT * FROM ProductionTimeFlow WHERE ProductionId IN (
	SELECT  p.snr  FROM  Stücke AS P INNER  JOIN(SELECT DISTINCT GruppeID, Schreiben FROM UserGruppe 
					INNER JOIN	UserPW	ON UserGruppe.Userid = UserPW.Userid 
					WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 3 AND Schreiben = 1) AS UG
	ON p.ModuleGroupId = ug.GruppeID)
WITH CHECK OPTION

Go
GRANT SELECT ON ProductionTimeFlow_Update TO Public
GRANT DELETE ON ProductionTimeFlow_Update TO Public
GRANT INSERT ON ProductionTimeFlow_Update TO Public
GRANT UPDATE ON ProductionTimeFlow_Update TO Public
GO

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

CREATE VIEW [dbo].[Scenes_Update]
AS 
SELECT * FROM Scenes WHERE ActId IN (
	SELECT  ptf.ProductionTimeFlowId  FROM 	ProductionTimeFlow AS ptf 
		INNER JOIN Stücke AS P ON ptf.ProductionId= P.snr
		INNER  JOIN	(SELECT DISTINCT GruppeID, Schreiben FROM UserGruppe 
						INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
					WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 3 AND Schreiben = 1) AS UG
				ON p.ModuleGroupId = ug.GruppeID)
WITH CHECK OPTION

Go
GRANT SELECT ON Scenes_Update TO Public
GRANT DELETE ON Scenes_Update TO Public
GRANT INSERT ON Scenes_Update TO Public
GRANT UPDATE ON Scenes_Update TO Public
GO

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

CREATE VIEW [dbo].[Roles_Scenes_Update]
AS 
SELECT * FROM Roles_Scenes WHERE RoleId IN (
	SELECT Id FROM BesetzungStd AS R 
		INNER  JOIN	(SELECT DISTINCT GruppeID, Schreiben FROM UserGruppe INNER JOIN	UserPW	ON UserGruppe.Userid = UserPW.Userid 
					 WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 4 AND Schreiben = 1) AS UG
				ON r.Besitzer = ug.GruppeID)
WITH CHECK OPTION

GO
GRANT SELECT ON [Roles_Scenes_Update] TO Public
GRANT DELETE ON [Roles_Scenes_Update] TO Public
GRANT INSERT ON [Roles_Scenes_Update] TO Public
GRANT UPDATE ON [Roles_Scenes_Update] TO Public
GO

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

CREATE VIEW [dbo].Productions_Seasons_Update
AS 
SELECT * FROM StückeSpz WHERE Snr IN (
	SELECT  p.snr  FROM  Stücke AS P INNER  JOIN(SELECT DISTINCT GruppeID, Schreiben FROM UserGruppe 
					INNER JOIN	UserPW	ON UserGruppe.Userid = UserPW.Userid 
					WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 3 AND Schreiben = 1) AS UG
	ON p.ModuleGroupId = ug.GruppeID)
WITH CHECK OPTION

GO
GRANT SELECT ON Productions_Seasons_Update TO Public
GRANT DELETE ON Productions_Seasons_Update TO Public
GRANT INSERT ON Productions_Seasons_Update TO Public
GRANT UPDATE ON Productions_Seasons_Update TO Public
Go
--2011-11-08 TH
--Neue Spalte für QualifikationsKategorie in Arbeistbereichen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'QualificationCategoryId' AND o.id = OBJECT_ID(N'[dbo].Ab'))
BEGIN
	ALTER TABLE dbo.Ab ADD QualificationCategoryId INT NULL
	ALTER TABLE dbo.Ab
		ADD CONSTRAINT FK_AB_QualificationCategory 
		FOREIGN KEY (QualificationCategoryId) 
		REFERENCES QualificationCategory(QualificationCategoryId)
END
GO

--2011 11 10 TK
--Primäre Gruppe entfernen, wenn die Gruppe nicht mehr vorhanden ist
UPDATE UserPw Set PriGruppeID = null WHERE  UserID IN (SELECT UserID FROM UserPw LEFT JOIN Gruppe ON UserPw.PriGruppeID = Gruppe.GruppeID WHERE  Gruppe.GruppeID IS NULL AND NOT UserPw.PriGruppeID  IS NULL )
GO

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

DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
DECLARE @SQL as varchar(4000) 
DECLARE @CreateViewStatement VARCHAR(5000)
IF(@sql_server_version > 8)
BEGIN
SET  @CreateViewStatement  = '
CREATE VIEW [dbo].ProductionTimeFlow_Update
AS 
SELECT * FROM ProductionTimeFlow WHERE ProductionId IN (
	SELECT  p.snr  FROM  Stücke AS P INNER  JOIN(SELECT DISTINCT GruppeID, Schreiben FROM UserGruppe 
					INNER JOIN	UserPW	ON UserGruppe.Userid = UserPW.Userid 
					WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 3 AND Schreiben = 1) AS UG
	ON p.ModuleGroupId = ug.GruppeID)
WITH CHECK OPTION
'
END
ELSE
BEGIN
SET  @CreateViewStatement  = '
CREATE VIEW [dbo].ProductionTimeFlow_Update
AS 
SELECT * FROM ProductionTimeFlow WHERE ProductionId IN (
	SELECT  p.snr  FROM  Stücke AS P INNER  JOIN(SELECT DISTINCT GruppeID, Schreiben FROM UserGruppe 
					INNER JOIN	UserPW	ON UserGruppe.Userid = UserPW.Userid 
					WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 3 AND Schreiben = 1) AS UG
	ON p.ModuleGroupId = ug.GruppeID)
'
END
EXEC (@CreateViewStatement)
GRANT SELECT ON ProductionTimeFlow_Update TO Public
GRANT DELETE ON ProductionTimeFlow_Update TO Public
GRANT INSERT ON ProductionTimeFlow_Update TO Public
GRANT UPDATE ON ProductionTimeFlow_Update TO Public
GO

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

CREATE VIEW [dbo].[Scenes_Update]
AS 
SELECT * FROM Scenes WHERE ActId IN (
	SELECT  ptf.ProductionTimeFlowId  FROM 	ProductionTimeFlow AS ptf 
		INNER JOIN Stücke AS P ON ptf.ProductionId= P.snr
		INNER  JOIN	(SELECT DISTINCT GruppeID, Schreiben FROM UserGruppe 
						INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
					WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 3 AND Schreiben = 1) AS UG
				ON p.ModuleGroupId = ug.GruppeID)
WITH CHECK OPTION

Go
GRANT SELECT ON Scenes_Update TO Public
GRANT DELETE ON Scenes_Update TO Public
GRANT INSERT ON Scenes_Update TO Public
GRANT UPDATE ON Scenes_Update TO Public
GO

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

CREATE VIEW [dbo].[Roles_Scenes_Update]
AS 
SELECT * FROM Roles_Scenes WHERE RoleId IN (
	SELECT Id FROM BesetzungStd AS R 
		INNER  JOIN	(SELECT DISTINCT GruppeID, Schreiben FROM UserGruppe INNER JOIN	UserPW	ON UserGruppe.Userid = UserPW.Userid 
					 WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 4 AND Schreiben = 1) AS UG
				ON r.Besitzer = ug.GruppeID)
WITH CHECK OPTION

GO
GRANT SELECT ON [Roles_Scenes_Update] TO Public
GRANT DELETE ON [Roles_Scenes_Update] TO Public
GRANT INSERT ON [Roles_Scenes_Update] TO Public
GRANT UPDATE ON [Roles_Scenes_Update] TO Public
GO

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

CREATE VIEW [dbo].Productions_Seasons_Update
AS 
SELECT * FROM StückeSpz WHERE Snr IN (
	SELECT  p.snr  FROM  Stücke AS P INNER  JOIN(SELECT DISTINCT GruppeID, Schreiben FROM UserGruppe 
					INNER JOIN	UserPW	ON UserGruppe.Userid = UserPW.Userid 
					WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 3 AND Schreiben = 1) AS UG
	ON p.ModuleGroupId = ug.GruppeID)
WITH CHECK OPTION
GO

--2011-11-08 TH
--Neue Spalte für QualifikationsKategorie in Arbeistbereichen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'QualificationCategoryId' AND o.id = OBJECT_ID(N'[dbo].Ab'))
BEGIN
	ALTER TABLE dbo.Ab ADD QualificationCategoryId INT NULL
	ALTER TABLE dbo.Ab
		ADD CONSTRAINT FK_AB_QualificationCategory 
		FOREIGN KEY (QualificationCategoryId) 
		REFERENCES QualificationCategory(QualificationCategoryId)
END
GO

GRANT SELECT ON Productions_Seasons_Update TO Public
GRANT DELETE ON Productions_Seasons_Update TO Public
GRANT INSERT ON Productions_Seasons_Update TO Public
GRANT UPDATE ON Productions_Seasons_Update TO Public
Go

UPDATE UserPw Set PriGruppeID = null WHERE  UserID IN (SELECT UserID FROM UserPw LEFT JOIN Gruppe ON UserPw.PriGruppeID = Gruppe.GruppeID WHERE  Gruppe.GruppeID IS NULL AND NOT UserPw.PriGruppeID  IS NULL )
GO

--2011-11-15 SH
--Zeitkonten erweitert um Module und Code
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'Module' AND o.id = OBJECT_ID(N'[dbo].Zeitkonten'))
BEGIN
	--neue Spalte Module
	ALTER TABLE Zeitkonten ADD Module INT NOT NULL CONSTRAINT DF_Zeitkonten_Module DEFAULT 0
	--neue Spalte Code
	ALTER TABLE Zeitkonten ADD Code VARCHAR(10) NULL
END
GO
--2011 11 15 TK  DefaultCastStatus erstellen, Defaultwert setzen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DefaultPerformanceCastStatusId' and o.id = OBJECT_ID(N'[dbo].[Gruppe]'))
BEGIN
	ALTER TABLE dbo.Gruppe ADD DefaultPerformanceCastStatusId INT NOT NULL Default 0 
	
	EXEC ('
	UPDATE CastStatus SET DefaultSecretState=0 , NameShort = NULL WHERE CastStatusId = 0
	IF  EXISTS (SELECT * FROM CastStatus WHERE CastStatusTyp = 6 AND CastStatusId <> 0) 
		BEGIN
			UPDATE Gruppe SET DefaultPerformanceCastStatusId = (SELECT TOP 1 CastStatusId FROM CastStatus WHERE CastStatusTyp = 6 AND CastStatusId <> 0) FROM Gruppe WHERE Modul= 1
		END
	ELSE
	BEGIN
		IF  EXISTS (SELECT * FROM CastStatus WHERE CastStatusTyp = 4 AND CastStatusId <> 0) 
		BEGIN
			UPDATE Gruppe SET DefaultPerformanceCastStatusId = (SELECT TOP 1  CastStatusId FROM CastStatus WHERE CastStatusTyp = 4 AND CastStatusId <> 0) FROM Gruppe WHERE Modul= 1
		END
	END
	')
END


GO

--2011-11-10 TH
-- Die Tabelle Resources wird in ResourceObjects umbenannt
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ResourceObjects]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	EXEC sp_rename 'Resources', 'ResourceObjects'

	EXEC sp_rename
		@objname = 'ResourceObjects.ResourceId',
		@newname = 'ResourceObjectId',
		@objtype = 'COLUMN'

	EXEC sp_rename
		@objname = 'ResourceObjects.ResourceTypeId',
		@newname = 'ResourceId',
		@objtype = 'COLUMN'

	-- Die Tabelle ResourceTypes wird in Resources umbenannt
	EXEC sp_rename 'ResourceTypes', 'Resources'

	EXEC sp_rename
		@objname = 'Resources.ResourceTypeId',
		@newname = 'ResourceId',
		@objtype = 'COLUMN'

	--ALTE EINSCHRÄNKUNGEN LÖSCHEN
	ALTER TABLE ResourceObjects DROP Constraint PK_Ressources
	ALTER TABLE ResourceObjects DROP Constraint FK_Resources_ResourceTypes
	ALTER TABLE ResourceObjects DROP Constraint FK_Resources_Person
	ALTER TABLE Resources DROP Constraint PK_ResourceTypes
	ALTER TABLE Resources DROP COLUMN Modules
		
	--Neue Tabelle für ResourceTypes
	CREATE TABLE [dbo].ResourceTypes (
		ResourceTypeId INT IDENTITY(1,1) NOT NULL,
		Name VARCHAR(100) NOT NULL,
		Module INT NOT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		CONSTRAINT PK_ResourceTypes PRIMARY KEY CLUSTERED (ResourceTypeId ASC) ON [PRIMARY],
	) ON [PRIMARY]
	CREATE INDEX IX_ResourceTypes_Module ON ResourceTypes (Module)

	--Ein standradDatensatz mit der ID 0 wird eingefügt
	SET IDENTITY_INSERT ResourceTypes ON
	EXEC ('INSERT INTO ResourceTypes (ResourceTypeId, Name, Module, LC, UC, LM, UM) VALUES (1, ''Orchesterinstrumente'', 2, GETDATE(), 0, GETDATE(), 0)')
	SET IDENTITY_INSERT ResourceTypes OFF

	--Die Tabelle Resources bekommt eine neue Spalte und einen Verweis auf ResourceTypes
	ALTER TABLE Resources ADD ResourceTypeId INT NULL 
	EXEC ('UPDATE Resources SET ResourceTypeID = 1 WHERE ResourceTypeID IS NULL')
	ALTER TABLE Resources ALTER COLUMN ResourceTypeID INT NOT NULL
	--NEUE EINSCHRÄNKUNGEN DEFINIEREN
	ALTER TABLE Resources ADD CONSTRAINT PK_Resources PRIMARY KEY CLUSTERED (ResourceId ASC) ON [PRIMARY]
	ALTER TABLE ResourceObjects ADD CONSTRAINT PK_ResourceObjects PRIMARY KEY CLUSTERED (ResourceObjectId ASC) ON [PRIMARY]
	ALTER TABLE Resources ADD CONSTRAINT FK_Resources_ResourceTypes FOREIGN KEY (ResourceTypeId) REFERENCES ResourceTypes(ResourceTypeId)
	ALTER TABLE ResourceObjects ADD CONSTRAINT FK_ResourceObjects_Resources	FOREIGN KEY (ResourceId) REFERENCES Resources(ResourceId)
	ALTER TABLE ResourceObjects ADD CONSTRAINT FK_ResourceObjects_Person FOREIGN KEY (PersonId) REFERENCES PersH(PersNr)
	CREATE INDEX IX_Resources_ResourceTypeId ON Resources (ResourceTypeId)
	CREATE INDEX IX_ResourceObjects_ResourceId ON ResourceObjects (ResourceId)

	ALTER TABLE Resources ADD [Count] INT NOT NULL CONSTRAINT DF_Resources_Count DEFAULT 0

	GRANT SELECT ON [dbo].Resources TO [Stammdaten ändern], [public]
	GRANT DELETE ON [dbo].Resources TO [Stammdaten ändern]
	GRANT INSERT ON [dbo].Resources TO [Stammdaten ändern]
	GRANT UPDATE ON [dbo].Resources TO [Stammdaten ändern]

	GRANT SELECT ON [dbo].ResourceTypes TO [Stammdaten ändern], [public]
	GRANT DELETE ON [dbo].ResourceTypes TO [Stammdaten ändern]
	GRANT INSERT ON [dbo].ResourceTypes TO [Stammdaten ändern]
	GRANT UPDATE ON [dbo].ResourceTypes TO [Stammdaten ändern]

	--Neue Tabelle für ActivityTypeResourceTypes
	CREATE TABLE [dbo].ActivityTypeResourceTypes (
		ActivityTypeResourceTypeId INT IDENTITY(1,1) NOT NULL,
		ActivityTypeId INT NOT NULL,
		ResourceTypeId INT NOT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		CONSTRAINT PK_ActivityTypeResourceTypes PRIMARY KEY CLUSTERED (ActivityTypeResourceTypeId ASC) ON [PRIMARY],
		CONSTRAINT FK_ActivityTypeResourceTypes_ActivitieTypes FOREIGN KEY (ActivityTypeId) REFERENCES dbo.AuffTypen (AuffTNr) ON DELETE CASCADE,
		CONSTRAINT FK_ActivityTypeResourceTypes_ResourcesTypes FOREIGN KEY (ResourceTypeId) REFERENCES dbo.ResourceTypes (ResourceTypeId) ON DELETE CASCADE,
		CONSTRAINT UQ_ActivityTypeResourceTypes_ActivitieTypeId_ResourcesTypeId UNIQUE (ActivityTypeId, ResourceTypeId),
	) ON [PRIMARY]
	CREATE INDEX IX_ActivityTypeResourceTypes_ActivityTypeId ON ActivityTypeResourceTypes (ActivityTypeId)
	CREATE INDEX IX_ActivityTypeResourceTypes_ResourceTypeId ON ActivityTypeResourceTypes (ResourceTypeId)
	GRANT SELECT ON [dbo].ActivityTypeResourceTypes TO [Stammdaten ändern], [public]
	GRANT DELETE ON [dbo].ActivityTypeResourceTypes TO [Stammdaten ändern]
	GRANT INSERT ON [dbo].ActivityTypeResourceTypes TO [Stammdaten ändern]
	GRANT UPDATE ON [dbo].ActivityTypeResourceTypes TO [Stammdaten ändern]
	--Neue Tabelle für ProductionResources
	CREATE TABLE [dbo].ProductionResources (
		ProductionResourceId INT IDENTITY(1,1) NOT NULL,
		ProductionId INT NOT NULL,
		ResourceId INT NOT NULL,
		[Count] INT NOT NULL CONSTRAINT DF_ProductionResources_Count DEFAULT 0,
		[Note] TEXT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		CONSTRAINT PK_ProductionResources PRIMARY KEY CLUSTERED (ProductionResourceId ASC) ON [PRIMARY],
		CONSTRAINT FK_ProductionResources_Productions FOREIGN KEY (ProductionId) REFERENCES dbo.Stücke (Snr) ON DELETE CASCADE,
		CONSTRAINT FK_ProductionResources_Resources FOREIGN KEY (ResourceId) REFERENCES dbo.Resources (ResourceId) ON DELETE CASCADE,
		CONSTRAINT UQ_ProductionResources_ProductionId_ResourceId UNIQUE (ProductionId, ResourceId)
	) ON [PRIMARY]
	GRANT SELECT ON [ProductionResources] TO Public
	CREATE INDEX IX_ProductionResources_ProductionId ON ProductionResources (ProductionId)
	CREATE INDEX IX_ProductionResources_ResourceId ON ProductionResources (ResourceId)

	--Neue Tabelle für ResourceBlockPeriods
	CREATE TABLE [dbo].ResourceBlockPeriods (
		ResourceBlockPeriodId INT IDENTITY(1,1) NOT NULL,
		ResourceId INT NOT NULL,
		[Count] INT NOT NULL CONSTRAINT DF_ResourceBlockPeriods_Count DEFAULT 0,
		[Start] DATETIME NOT NULL,
		[End] DATETIME NOT NULL,
		[Note] TEXT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		CONSTRAINT PK_ResourceBlockPeriods PRIMARY KEY CLUSTERED (ResourceBlockPeriodId ASC) ON [PRIMARY],
		CONSTRAINT FK_ResourceBlockPeriods_Resources FOREIGN KEY (ResourceId) REFERENCES dbo.Resources (ResourceId)  ON DELETE CASCADE,
	) ON [PRIMARY]
	CREATE INDEX IX_ResourceBlockPeriods_ResourceId ON ResourceBlockPeriods (ResourceId)
	GRANT SELECT ON [dbo].ResourceBlockPeriods TO [Spielplan ändern], [Spielplan alles lesen]
	GRANT DELETE ON [dbo].ResourceBlockPeriods TO [Spielplan ändern]
	GRANT INSERT ON [dbo].ResourceBlockPeriods TO [Spielplan ändern]
	GRANT UPDATE ON [dbo].ResourceBlockPeriods TO [Spielplan ändern]

END
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ResourceObjects_Resources]') )
BEGIN
	ALTER TABLE ResourceObjects DROP CONSTRAINT FK_ResourceObjects_Resources
	ALTER TABLE ResourceObjects ADD CONSTRAINT FK_ResourceObjects_Resources	FOREIGN KEY (ResourceId) REFERENCES Resources(ResourceId)
END
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ResourceObjects_Person]') )
BEGIN
	ALTER TABLE ResourceObjects DROP CONSTRAINT FK_ResourceObjects_Person
	ALTER TABLE ResourceObjects ADD CONSTRAINT FK_ResourceObjects_Person FOREIGN KEY (PersonId) REFERENCES PersH(PersNr)
END
GO
--View für die ProductionResources anlegen (Vorher löschen)
IF   EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[ProductionResources_Update]'))
BEGIN
	DROP VIEW [dbo].[ProductionResources_Update]
END
GO

CREATE VIEW [dbo].[ProductionResources_Update]
AS 
SELECT * FROM ProductionResources WHERE ProductionId IN (
	SELECT  p.Snr  FROM  Stücke AS p
		INNER  JOIN	(SELECT DISTINCT GruppeID, Schreiben 
					 FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
					 WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 3 AND Schreiben = 1) AS UG
					  ON p.ModuleGroupId = ug.GruppeID)
WITH CHECK OPTION
GO
GRANT SELECT ON ProductionResources_Update TO Public
GRANT DELETE ON [ProductionResources_Update] TO Public
GRANT INSERT ON [ProductionResources_Update] TO Public
GRANT UPDATE ON [ProductionResources_Update] TO Public
GO
--TK 2011 11 22 TODO default setzen
UPDATE PersKat SET AdressArt = 0 WHERE AdressArt IS NULL
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_PersKat_AdressArt]') )
BEGIN
ALTER TABLE PersKat ADD CONSTRAINT DF_PersKat_AdressArt DEFAULT 0 FOR Adressart
END
GO

--TH 2011-11-29 DELETE CASCADE

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Roles_Scenes_Roles]') )
BEGIN
	ALTER TABLE Roles_Scenes
		DROP FK_Roles_Scenes_Roles
	ALTER TABLE Roles_Scenes
		ADD CONSTRAINT FK_Roles_Scenes_Roles 
		FOREIGN KEY (RoleId) 
		REFERENCES BesetzungStd(ID)
		ON DELETE CASCADE
	ALTER TABLE Roles_Scenes
		DROP FK_Roles_Scenes_Scenes
	ALTER TABLE Roles_Scenes
		ADD CONSTRAINT FK_Roles_Scenes_Scenes 
		FOREIGN KEY (SceneId) 
		REFERENCES Scenes(SceneId)
		ON DELETE CASCADE
END
GO	
--TK 2011 12 08
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_SubscriptionActivityCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].sp_SubscriptionActivityCount
GO
CREATE 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
GO

GRANT EXECUTE ON sp_SubscriptionActivityCount TO Public
GO

--TH 2011-12-08 Neue Tabelle für Plan-Berechtigungen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PlanPermissionSettings]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].PlanPermissionSettings (
		PlanPermissionSettingsId INT IDENTITY(1,1) NOT NULL,
		PlanId INT NOT NULL,
		UserId INT NOT NULL,
		PublishInWeb BIT NOT NULL,
		[Start] DATETIME NOT NULL,
		[End] DATETIME NOT NULL,
		[ShowHistorySince] DATETIME NOT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		CONSTRAINT PK_PlanPermissionSettings PRIMARY KEY CLUSTERED (PlanPermissionSettingsId ASC) ON [PRIMARY],
		CONSTRAINT FK_PlanPermissionSettings_Plan FOREIGN KEY (PlanId) REFERENCES dbo.[Plan] (PlanId)  ON DELETE CASCADE,
		CONSTRAINT FK_PlanPermissionSettings_UserPW FOREIGN KEY (UserId) REFERENCES dbo.[UserPw] (UserId)  ON DELETE CASCADE,
		CONSTRAINT UQ_PlanPermissionSettings_PlanId_UserGroupId UNIQUE (PlanId, UserId)
	) ON [PRIMARY]
CREATE INDEX IX_PlanPermissionSettings_PlanId ON PlanPermissionSettings (PlanId)
CREATE INDEX IX_PlanPermissionSettings_UserId ON PlanPermissionSettings (UserId)
GRANT SELECT ON [dbo].PlanPermissionSettings TO [Public]
GRANT DELETE ON [dbo].PlanPermissionSettings TO [Spielplan ändern]
GRANT INSERT ON [dbo].PlanPermissionSettings TO [Spielplan ändern]
GRANT UPDATE ON [dbo].PlanPermissionSettings TO [Spielplan ändern]
END
GO

--TK 2011 12 01
DELETE FROM HDMZr WHERE ZrNr IN (SELECT HDMZr.zrnr FROM HDMZr LEFT JOIN ZR ON HDMZr.Zrnr = dbo.ZR.ZRNr WHERE ZR.zrnr IS NULL)
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_HDMZr_Zr]') )
BEGIN
	ALTER TABLE HDMZr
		ADD CONSTRAINT FK_HDMZr_Zr 
		FOREIGN KEY (zrnr) 
		REFERENCES zr(zrnr)
		ON DELETE CASCADE
END
GO

--TK 2011 12 21
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IsMale' AND o.id = OBJECT_ID(N'[dbo].Anrede'))
BEGIN
	ALTER TABLE dbo.Anrede ADD IsMale BIT NULL
	EXEC ('UPDATE Anrede SET IsMale = 0 WHERE Geschlechtid = 0');
	EXEC ('UPDATE Anrede SET IsMale = 1 WHERE Geschlechtid = -1');
END
GO

--TH 2011-12-27
--Neue Spalte für Anzahl Dienste in die Tabelle AuffDienstplanArten
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ShiftCount' AND o.id = OBJECT_ID(N'[dbo].AuffDienstplanArten'))
BEGIN
	ALTER TABLE AuffDienstplanArten ADD ShiftCount DECIMAL NULL
END
GO

--TH 2011-12-27
--Neue Spalte für Anzahl Dienste in die Tabelle StückeDienstplan
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ShiftCount' AND o.id = OBJECT_ID(N'[dbo].StückeDienstplan'))
BEGIN
	ALTER TABLE StückeDienstplan ADD ShiftCount DECIMAL NOT NULL CONSTRAINT DF_StückeDienstplan_ShiftCount DEFAULT 1
END
GO

--TK 2011 12 22
--% auszahlen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'PayOutPercentage' AND o.id = OBJECT_ID(N'[dbo].TimeAccountUsage')) 
BEGIN
	ALTER TABLE dbo.[TimeAccountUsage] ADD PayOutPercentage BIT NOT NULL CONSTRAINT DF_TimeAccountUsage_PayOutPercentage DEFAULT 100
	exec ('UPDATE VertragRolle SET ExtraFee = HonorarUeberspiel FROM VertragRolle INNER JOIN VertragDetails ON VertragRolle.VertragsNr=VertragDetails.VertragsNr WHERE  HonorarUeberspiel>0')
END
GO
--TH 2012-01-11
--Neue Spalte für Anzahl Dienste in die Tabelle StückeDienstplan
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ConverterSettings' AND o.id = OBJECT_ID(N'[dbo].AdressAusgabe'))
BEGIN
	ALTER TABLE AdressAusgabe ADD ConverterSettings TEXT NULL
END
GO

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = '[Description]' AND o.id = OBJECT_ID(N'[dbo].CashCommandPos') AND c.prec < 400)
BEGIN
	ALTER TABLE CashCommandPos ALTER COLUMN [Description] VARCHAR(400)
	Print 'WertText geändert'
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'TaxId' AND o.id = OBJECT_ID(N'[dbo].CashCommandPos')) 
BEGIN
	ALTER TABLE dbo.CashCommandPos ADD TaxId INT NULL
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'MaintenanceId' AND o.id = OBJECT_ID(N'[dbo].CashCommandPos')) 
BEGIN
	ALTER TABLE dbo.CashCommandPos ADD MaintenanceId INT NULL
	ALTER TABLE dbo.CashCommandPos ADD MaintenanceFrom datetime NULL
	ALTER TABLE dbo.CashCommandPos ADD MaintenanceUntil datetime NULL
END
GO

--UPDATE CashCommandPos SET  MaintenanceId =CashCommand.InternalMaintenanceId , MaintenanceFrom =CashCommand.BillingPeriodStart , MaintenanceUntil = CashCommand.BillingPeriodEnd FROM CashCommandPos INNER JOIN CashCommand ON CashCommandPos.CashCommandId = CashCommand.CashCommandId

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'CashCommandNo' AND o.id = OBJECT_ID(N'[dbo].CashCommand')) 
BEGIN
	ALTER TABLE dbo.CashCommand ADD CashCommandNo INT NULL
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'FreeTextAddress' AND o.id = OBJECT_ID(N'[dbo].CashCommand')) 
BEGIN
	ALTER TABLE dbo.CashCommand ADD FreeTextAddress VARCHAR(400)
	UPDATE CashCommand SET IsCleared = 0 WHERE IsCleared IS NULL
	ALTER TABLE CashCommand ADD CONSTRAINT DF_CashCommand_IsCleared DEFAULT 0 FOR IsCleared
	ALTER TABLE CashCommand ALTER COLUMN IsCleared BIT NOT NULL
	ALTER TABLE dbo.CashCommand ADD PayDate Datetime NULL
	
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'BackColorArgb' AND o.id = OBJECT_ID(N'[dbo].BesetzungTabelle')) 
BEGIN
	ALTER TABLE dbo.BesetzungTabelle ADD BackColorArgb INT NULL
END
GO

--2012-01-13
--Spalten auf NVARCHAR setzen
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'L10' AND o.id = OBJECT_ID(N'[dbo].PresseText') AND c.xtype <> 231)
BEGIN

ALTER TABLE [BesetzungStd] ALTER COLUMN [Rolle] nvarchar(150)
ALTER TABLE [BesetzungStd] ALTER COLUMN [RollePresse] nvarchar(100)
ALTER TABLE [PersH] ALTER COLUMN [Nachname] nvarchar(60)
ALTER TABLE [PersH] ALTER COLUMN [Vorname] nvarchar(60)
ALTER TABLE [PersonalDetails] ALTER COLUMN [CivilFirstName] nvarchar(60)
ALTER TABLE [PersonalDetails] ALTER COLUMN [civilName] nvarchar(60)
ALTER TABLE [PersonalDetails] ALTER COLUMN [GebOrt] nvarchar(50)
ALTER TABLE [PersonalDetails] ALTER COLUMN [NameOfFather] nvarchar(60)

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = N'TitelInszenierung' AND [id] = OBJECT_ID(N'[dbo].[Stücke]')) DROP INDEX [dbo].[Stücke].[TitelInszenierung]
ALTER TABLE [Stücke] ALTER COLUMN [Titel] nvarchar(20)
CREATE UNIQUE NONCLUSTERED INDEX [TitelInszenierung] ON [dbo].[Stücke] (
	[Titel] ASC,
	[Inszenierung] ASC
)ON [PRIMARY]

ALTER TABLE [PersAdresse] ALTER COLUMN [co] nvarchar(80)
ALTER TABLE [PersAdresse] ALTER COLUMN [Ort] nvarchar(80)
ALTER TABLE [PersAdresse] ALTER COLUMN [Str] nvarchar(150)

ALTER TABLE [BankAccount] ALTER COLUMN [AccountHolder] nvarchar(50)
ALTER TABLE [BankAccount] ALTER COLUMN [BankName] nvarchar(50)
ALTER TABLE [BankAccount] ALTER COLUMN [City] nvarchar(50)

ALTER TABLE [Stücke] ALTER COLUMN [OriginalTitel] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [F10] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [F20] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [F30] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [F40] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [K10] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [K20] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [K30] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [K40] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [Komponist] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [KRechts] nvarchar(255)

ALTER TABLE [StückeDetails] ALTER COLUMN [L10] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [L20] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [L30] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [L40] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [L50] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [L60] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [LRechts] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [T10] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [T20] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [T30] nvarchar(255)
ALTER TABLE [StückeDetails] ALTER COLUMN [T40] nvarchar(255)

ALTER TABLE PresseText ALTER COLUMN Bem nvarchar(10)
ALTER TABLE PresseText ALTER COLUMN [L10] nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN [L20] nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN [L30] nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN [L40] nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN [L50] nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN [L60] nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN [LRechts] nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN [K10] nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN [K20] nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN [K30] nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN [K40] nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN [KRechts] nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN POriginaltitel nvarchar(255)
ALTER TABLE PresseText ALTER COLUMN PKomponist nvarchar(255)

END
GO

--2012-01-13 [SH]
--AboBez auf 24 erhöhen (Anpassung an Zürich)
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AboBez' AND o.id = OBJECT_ID(N'[dbo].Ring') AND c.[length] < 25)
BEGIN
	ALTER TABLE Ring ALTER COLUMN AboBez varchar(25) NULL
	ALTER TABLE RingBez ALTER COLUMN AboBez varchar(25) NULL
END
GO

--Personalnummer auf 20 Stellen erhöhen (Anpassung an Lyon)
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PersonnelNo' AND o.id = OBJECT_ID(N'[dbo].PersH') AND c.[length] < 20)
BEGIN
	ALTER TABLE PersH ALTER COLUMN PersonnelNo VARCHAR(20) NULL
END
GO

--2012-01-13 [SH]
--BugFix AufführgTabelle.VonZeit auf NOT NULL stellen
--bestehenden Default Wert löschen wenn vorhanden
IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Aufführg_VonZeit_D]') AND OBJECTPROPERTY(id, N'IsDefault') = 1)
BEGIN
	EXECUTE sp_unbindefault N'dbo.AufführgTabelle.VonZeit'
	DROP DEFAULT [dbo].[Aufführg_VonZeit_D]
END
GO
--Spalte anpassen
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'VonZeit' AND o.id = OBJECT_ID(N'[dbo].AufführgTabelle') AND c.isnullable = 1)
BEGIN
	UPDATE AufführgTabelle SET VonZeit = 0 WHERE VonZeit IS NULL
	ALTER TABLE AufführgTabelle ALTER COLUMN VonZeit BIT NOT NULL
	ALTER TABLE AufführgTabelle ADD CONSTRAINT DF_AufführgTabelle_VonZeit DEFAULT 0 FOR VonZeit 
END
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Gesperrt' AND o.id = OBJECT_ID(N'[dbo].PersZusatzDatenTyp') AND c.isnullable = 1)
BEGIN
	UPDATE PersZusatzDatenTyp SET Gesperrt = 0 WHERE Gesperrt IS NULL
	ALTER TABLE PersZusatzDatenTyp ALTER COLUMN Gesperrt BIT NOT NULL
	ALTER TABLE PersZusatzDatenTyp ADD CONSTRAINT DF_PersZusatzDatenTyp_Gesperrtt DEFAULT 0 FOR Gesperrt 
END
GO


--Alle nicht gesperrten und alle Kontakte auf die min. Kontaktdaten lesen
ALTER VIEW [dbo].AbPersZusatzDaten
AS 
SELECT PersZusatzDatenID, zd.PersNr, zd.PersZDTypID, ZDText, ZDInt, ZDDate, zd.LM, zd.UM, zd.LC, zd.UC 
FROM			PersZusatzDaten				AS zd 
WHERE zd.PersZusatzDatenID  IN 
		(SELECT PersZusatzDatenID FROM PersZusatzDaten
			INNER JOIN	PersZusatzDatenTyp			AS zdt	ON zd.PersZDTypID = zdt.PersZDTypID
			LEFT  JOIN	PersonModulGroupPermission	AS gp	ON zd.PersNr = gp.PersonId
			INNER JOIN  UserGruppe					AS ug	ON zdt.Besitzer = ug.GruppeID
			INNER JOIN	UserPW								ON ug.Userid = UserPW.Userid 
		WHERE 
			zdt.gesperrt = 0 OR 
			(ug.BerechtigungsbereichID = 0 AND UserPW.Username = current_user))
			
go
--Alle mit Schreibrecht	
ALTER VIEW [dbo].AbPersZusatzDaten_Update
AS 		
SELECT PersZusatzDatenID, zd.PersNr, zd.PersZDTypID, ZDText, ZDInt, ZDDate, zd.LM, zd.UM, zd.LC, zd.UC 
FROM			PersZusatzDaten				AS zd 
WHERE zd.PersZusatzDatenID  IN 
		(SELECT PersZusatzDatenID FROM PersZusatzDaten
			INNER JOIN	PersZusatzDatenTyp			AS zdt	ON zd.PersZDTypID = zdt.PersZDTypID
			LEFT  JOIN	PersonModulGroupPermission	AS gp	ON zd.PersNr = gp.PersonId
			INNER JOIN  UserGruppe					AS ug	ON zdt.Besitzer = ug.GruppeID
			INNER JOIN	UserPW								ON ug.Userid = UserPW.Userid 
		WHERE 
			ug.BerechtigungsbereichID = 0 AND UserPW.Username = current_user AND gp.HasWritePermission = 1 AND ug.Schreiben = 1 )
go		 
ALTER VIEW [dbo].[AbPersZusatzDatenTyp]
AS 
 SELECT DISTINCT PersZusatzDatenTyp.* 
 FROM  PersZusatzDatenTyp  LEFT  JOIN 
		(SELECT GruppeID 
		 FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		 WHERE  BerechtigungsbereichID=0 AND  Username = CURRENT_USER) UG ON (PersZusatzDatenTyp.Besitzer = UG.GruppeID )
WHERE PersZusatzDatenTyp.Gesperrt =0 or not  UG.GruppeID IS NULL
GO

--2012-02-20 TH:
--Für jede Person ein gesprerrt merkmal
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsPerson1Locked' and o.id = OBJECT_ID(N'[dbo].[BesetzungStdSoliTabelle]'))
BEGIN
	ALTER TABLE BesetzungStdSoliTabelle ADD IsPerson1Locked BIT NOT NULL CONSTRAINT [DF_BesetzungStdSoliTabelle_IsPerson1Locked] DEFAULT 0
	ALTER TABLE BesetzungStdSoliTabelle ADD IsPerson2Locked BIT NOT NULL CONSTRAINT [DF_BesetzungStdSoliTabelle_IsPerson2Locked] DEFAULT 0
	ALTER TABLE BesetzungStdSoliTabelle ADD IsPerson3Locked BIT NOT NULL CONSTRAINT [DF_BesetzungStdSoliTabelle_IsPerson3Locked] DEFAULT 0
	ALTER TABLE BesetzungStdSoliTabelle ADD IsPerson4Locked BIT NOT NULL CONSTRAINT [DF_BesetzungStdSoliTabelle_IsPerson4Locked] DEFAULT 0

	UPDATE BesetzungStdSoliTabelle SET Gesperrt = 0 WHERE Gesperrt IS NULL
	ALTER TABLE BesetzungStdSoliTabelle ALTER COLUMN Gesperrt BIT NOT NULL
	ALTER TABLE BesetzungStdSoliTabelle ADD CONSTRAINT [DF_BesetzungStdSoliTabelle_Gesperrt] DEFAULT 0 FOR Gesperrt

	EXEC ('UPDATE BesetzungStdSoliTabelle SET IsPerson1Locked = Gesperrt, IsPerson2Locked = Gesperrt, IsPerson3Locked = Gesperrt, IsPerson4Locked = Gesperrt')
END
GO
ALTER VIEW [dbo].[AbPersZusatzDatenTyp_Update]
AS 
SELECT  * FROM PersZusatzDatenTyp 
WHERE PerszdTypid in (
	SELECT PerszdTypid 
	FROM  PersZusatzDatenTyp  LEFT  JOIN (SELECT GruppeID, schreiben 
											FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
											WHERE  BerechtigungsbereichID=0 AND  Username = CURRENT_USER) UG ON (PersZusatzDatenTyp.Besitzer = UG.GruppeID )
	WHERE Schreiben=1
)
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ContractTracking]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ContractTracking](
	[ContractTrackingId] [int] IDENTITY(1,1) NOT NULL,
	[ContractConfirmationId] [int] NOT NULL,
	[ContractTrackingStatusId] [int] NOT NULL,
	[TrackingDate] DATETIME NOT NULL,
	[Note] VARCHAR(250) NULL,
	[LM] [datetime] NOT NULL,
	[UM] [int] NOT NULL,
	[LC] [datetime] NOT NULL,
	[UC] [int] NOT NULL,
	CONSTRAINT [PK_ContractTrackingId] PRIMARY KEY CLUSTERED ([ContractTrackingId] ASC) ON [PRIMARY],	
	CONSTRAINT FK_ContractTracking_ContractConfirmations FOREIGN KEY (ContractConfirmationId) REFERENCES dbo.ContractConfirmations (ContractConfirmationId),
	CONSTRAINT FK_ContractTracking_ContractDateStatus FOREIGN KEY ([ContractTrackingStatusId]) REFERENCES dbo.ContractDateStatus (CDStatusId)
) ON [PRIMARY]
END
GRANT SELECT ON [ContractTracking] TO [Honorar-Daten lesen]
GRANT SELECT ON [ContractTracking] TO [Honorar-Daten ändern]
GRANT DELETE ON [ContractTracking] TO [Honorar-Daten ändern]
GRANT INSERT ON [ContractTracking] TO [Honorar-Daten ändern]
GRANT UPDATE ON [ContractTracking] TO [Honorar-Daten ändern]
GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ContractTrackingWorkflow]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[ContractTrackingWorkflow](
	ContractTrackingWorkflowId		int IDENTITY(1,1) NOT NULL,
	DocumentTypeId					int NOT NULL,
	ContractTrackingStatusId		int NOT NULL,
	ByUserId							int NULL,
	BeforeDocumentTypeId			int NULL,
	BeforeContractTrackingStatusId	int NULL,
	[LM]							datetime NOT NULL,
	[UM]							int NOT NULL,
	[LC]							datetime NOT NULL,
	[UC]							int NOT NULL,
	CONSTRAINT [PK_ContractTrackingWorkflowId] PRIMARY KEY CLUSTERED ([ContractTrackingWorkflowId] ASC) ON [PRIMARY],	
	CONSTRAINT FK_ContractTrackingWorkflow_ContractDateStatus FOREIGN KEY (ContractTrackingStatusId) REFERENCES dbo.ContractDateStatus (CDStatusId),
	CONSTRAINT FK_ContractTrackingWorkflow_BeforeContractDateStatus FOREIGN KEY (BeforeContractTrackingStatusId) REFERENCES dbo.ContractDateStatus (CDStatusId),
	CONSTRAINT FK_ContractTrackingWorkflow_UserPw FOREIGN KEY (ByUserId) REFERENCES dbo.UserPw  (UserId)
) ON [PRIMARY]

CREATE UNIQUE NONCLUSTERED INDEX IX_ContractTrackingDocumentTypeId_ContractTrackingStatusId ON [dbo].[ContractTracking] (
	[ContractConfirmationId] ASC,
	[ContractTrackingStatusId] ASC
)ON [PRIMARY]

END
GRANT SELECT ON [ContractTrackingWorkflow] TO [Public]
GRANT DELETE ON [ContractTrackingWorkflow] TO [Honorar-Daten ändern]
GRANT INSERT ON [ContractTrackingWorkflow] TO [Honorar-Daten ändern]
GRANT UPDATE ON [ContractTrackingWorkflow] TO [Honorar-Daten ändern]
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ParentContractConfirmationId' AND o.id = OBJECT_ID(N'[dbo].ContractConfirmations')) 
BEGIN
	ALTER TABLE dbo.ContractConfirmations ADD ParentContractConfirmationId INT NULL
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'DocumentNo' AND o.id = OBJECT_ID(N'[dbo].ContractConfirmations')) 
BEGIN
	ALTER TABLE dbo.ContractConfirmations ADD DocumentNo VarChar(50)
END
--2012-02 nich mehr verwendet
IF EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoShiftWrite')
BEGIN
	EXEC DropRoleWithDropRoleMember N'PersoShiftWrite'
END

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BesBem' AND o.id = OBJECT_ID(N'[dbo].BesetzungTabelle') AND c.prec < 250)
BEGIN
	ALTER TABLE BesetzungTabelle ALTER COLUMN BesBem VARCHAR(250)
	Print 'WertText geändert'
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'SortMale' AND o.id = OBJECT_ID(N'[dbo].BodyMeasures')) 
BEGIN
	ALTER TABLE dbo.BodyMeasures ADD SortMale INT NULL
	ALTER TABLE dbo.BodyMeasures ADD SortFemale INT NULL
	exec ('UPDATE BodyMeasures SET SortMale = Sort, SortFemale = Sort')
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'LastDocumentTypeId' AND o.id = OBJECT_ID(N'[dbo].ContractDates')) 
BEGIN
	ALTER TABLE dbo.ContractDates ADD LastDocumentTypeId INT NULL
END

--2012-02-09 SH
--dateinamen bei vorlagen auf 75 vergrößern
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DokName' AND o.id = OBJECT_ID(N'[dbo].Vorlagen') AND c.[length] < 75)
BEGIN
	ALTER TABLE Vorlagen ALTER COLUMN DokName VARCHAR(75) NULL
END
GO

--2012-03-12
--Änderungen der Einstellungen von Instrumentenfilter auf neue Struktur
UPDATE Settings SET 
	Settings.Form='departmentscheduling.workareafilter',
	Settings.Control = 'department_' + substring(Settings.Control,11,len(Settings.Control)-10) --alter key ist orchestra_ID
WHERE Settings.Form = 'orchestra.dispo.instrumentfilter'
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'PayOutPercentage' AND o.id = OBJECT_ID(N'[dbo].TimeAccountUsage') AND c.xType = 62) 
BEGIN
	EXEC DeleteConstraint 'TimeAccountUsage', 'PayOutPercentage' 
	ALTER TABLE dbo.[TimeAccountUsage] ALTER COLUMN PayOutPercentage float NOT NULL
	UPDATE dbo.[TimeAccountUsage] SET PayOutPercentage = 100
	ALTER TABLE TimeAccountUsage ADD CONSTRAINT DF_TimeAccountUsage_PayOutPercentage DEFAULT 100 FOR PayOutPercentage 
	Print 'PayOutPercentage'
END
GO

--2012-02-20 TH:
--Neue Spalte für XML-Settings im Rapport
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'FormatSettings' AND o.id = OBJECT_ID(N'[dbo].Rapport'))
BEGIN
	ALTER TABLE Rapport ADD FormatSettings TEXT NULL
END
GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DepartmentCollectives]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].DepartmentCollectives(
	DepartmentCollectivesId		int IDENTITY(1,1) NOT NULL,
	DepartmentId					int NOT NULL,
	PersonId						int NOT NULL,
	[LM]							datetime NOT NULL,
	[UM]							int NOT NULL,
	[LC]							datetime NOT NULL,
	[UC]							int NOT NULL,
	CONSTRAINT [PK_DepartmentCollectivesId] PRIMARY KEY CLUSTERED ([DepartmentCollectivesId] ASC) ON [PRIMARY],	
	CONSTRAINT FK_DepartmentCollectives_Department FOREIGN KEY (DepartmentId) REFERENCES dbo.DienstplanArtenTabelle (DienstplanArtenId),
	CONSTRAINT FK_DepartmentCollectives_Personal FOREIGN KEY (PersonId) REFERENCES dbo.PersH (Persnr),
) ON [PRIMARY]

CREATE UNIQUE NONCLUSTERED INDEX IX_DepartmentId_PersonId ON [dbo].DepartmentCollectives (
	DepartmentId ASC,
	PersonId ASC
)ON [PRIMARY]
exec ('INSERT INTO DepartmentCollectives (DepartmentId,PersonId,lm,um,lc,uc)
	SELECT a.DienstplanArtenId, b.Persnr,''19000101'',-1,''19000101'',-1 FROM 
		(SELECT DienstplanArtenId FROM DienstplanArtenTabelle as d INNER JOIN Gruppe ON d.ModulGruppeID=Gruppe.GruppeID  WHERE Gruppe.Modul = 2) as a CROSS JOIN (SELECT Persnr FROM  PersH INNER JOIN PersKat  ON PersH.PersKatNr=PersKat.PersKatNr WHERE PersKat.AdressArt = 100) as b
')

exec ('INSERT INTO DepartmentCollectives (DepartmentId,PersonId,lm,um,lc,uc)
	SELECT a.DienstplanArtenId, b.Persnr,''19000101'',-1,''19000101'',-1 FROM 
		(SELECT DienstplanArtenId FROM DienstplanArtenTabelle as d INNER JOIN Gruppe ON d.ModulGruppeID=Gruppe.GruppeID  WHERE Gruppe.Modul = 16) as a CROSS JOIN (SELECT Persnr FROM  PersH INNER JOIN PersKat  ON PersH.PersKatNr=PersKat.PersKatNr WHERE PersKat.AdressArt = 110) as b
')

exec ('INSERT INTO DepartmentCollectives (DepartmentId,PersonId,lm,um,lc,uc)
	SELECT a.DienstplanArtenId, b.Persnr,''19000101'',-1,''19000101'',-1 FROM 
		(SELECT DienstplanArtenId FROM DienstplanArtenTabelle as d INNER JOIN Gruppe ON d.ModulGruppeID=Gruppe.GruppeID  WHERE Gruppe.Modul = 32) as a CROSS JOIN (SELECT Persnr FROM  PersH INNER JOIN PersKat  ON PersH.PersKatNr=PersKat.PersKatNr WHERE PersKat.AdressArt = 120) as b
')

END
GRANT SELECT ON DepartmentCollectives TO [Public]
GRANT DELETE ON DepartmentCollectives TO [Stammdaten ändern]
GRANT INSERT ON DepartmentCollectives TO [Stammdaten ändern]
GRANT UPDATE ON DepartmentCollectives TO [Stammdaten ändern]

GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ValidityStatus' AND o.id = OBJECT_ID('dbo.ContractConfirmations'))
BEGIN
	ALTER TABLE ContractConfirmations ADD ValidityStatus INT NOT NULL CONSTRAINT [DF_ContractConfirmationsd_ValidityStatus] DEFAULT 0
END
GO

--2012-02-16 SH
--#region Tourneen [WI #2235]
--#region Rollen
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'CanWriteTours')
BEGIN
	EXEC sp_addrole @rolename = N'CanWriteTours'
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'CanValidateTours')
BEGIN
	EXEC sp_addrole @rolename = N'CanValidateTours'
END
GO

 --2012-03-01 TK Wahlabo
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IsChoiceSubscription' AND o.id = OBJECT_ID('dbo.RingBez'))
BEGIN
	ALTER TABLE RingBez ADD IsChoiceSubscription BIT NOT NULL CONSTRAINT [DF_RingBez_IsChoiceSubscription] DEFAULT 0
END
 
 
--#endregion

--#region Tabelle Tours
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Tours]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].Tours (
		TourId INT IDENTITY(1,1) NOT NULL, --ID
		Title NVARCHAR(40) NOT NULL, --Title
		[Description] NVARCHAR(70) NULL, --Name
		[CostUnitId] INT NOT NULL , --CostUnit
		[Start] DATETIME NOT NULL, --Start Date
		[End] DATETIME NOT NULL, --End Date
		[Status] INT NOT NULL CONSTRAINT DF_Tours_Status DEFAULT 0, --status
		[LastExportDate] DATETIME NULL, --export day		
		[LC] DATETIME NOT NULL, --creation date
		[UC] INT NOT NULL, --UserId (for creation)
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		CONSTRAINT PK_Tours PRIMARY KEY CLUSTERED (TourId ASC) ON [PRIMARY],
		CONSTRAINT FK_Tours_CostUnits FOREIGN KEY (CostUnitId) REFERENCES dbo.CostUnit (CostUnitId),
	) ON [PRIMARY]
GRANT SELECT ON [dbo].Tours TO [Public]
GRANT DELETE ON [dbo].Tours TO CanWriteTours
GRANT INSERT ON [dbo].Tours TO CanWriteTours
GRANT UPDATE ON [dbo].Tours TO CanWriteTours
END
--#endregion

--#region Tabelle Tours_Bonuses für die Standardwerte von Zulagen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Tours_Bonuses]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].Tours_Bonuses (
		TourBonusId INT IDENTITY(1,1) NOT NULL,
		TourId INT NOT NULL,
		BonusId INT NOT NULL,
		DefaultValue FLOAT NOT NULL CONSTRAINT DF_Tours_Bonuses_DefaultValue DEFAULT 0,		
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		CONSTRAINT PK_Tours_Bonuses PRIMARY KEY CLUSTERED (TourBonusId ASC) ON [PRIMARY],
		CONSTRAINT FK_Tours_Bonuses_Tours FOREIGN KEY (TourId) REFERENCES dbo.[Tours] (TourId),
		CONSTRAINT FK_Tours_Bonuses_Bonuses FOREIGN KEY (BonusId) REFERENCES dbo.[Zulagen] (ZulagenNr),
		CONSTRAINT UQ_Tours_Bonuses_TourId_BonusId UNIQUE (TourId, BonusId)
	) ON [PRIMARY]
GRANT SELECT ON [dbo].Tours_Bonuses TO [Public]
GRANT DELETE ON [dbo].Tours_Bonuses TO CanWriteTours
GRANT INSERT ON [dbo].Tours_Bonuses TO CanWriteTours
GRANT UPDATE ON [dbo].Tours_Bonuses TO CanWriteTours
END
--#endregion

--#region Tabelle Tours_Contracts für die der Tournee zugeordneten Verträge (und damit Personen)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Tours_Contracts]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].Tours_Contracts (
		TourContractId INT IDENTITY(1,1) NOT NULL,
		TourId INT NOT NULL,
		ContractId INT NOT NULL,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		CONSTRAINT PK_Tours_Contracts PRIMARY KEY CLUSTERED (TourContractId ASC) ON [PRIMARY],
		CONSTRAINT FK_Tours_Contracts_Tours FOREIGN KEY (TourId) REFERENCES dbo.[Tours] (TourId),
		CONSTRAINT FK_Tours_Contracts_Contracts FOREIGN KEY (ContractId) REFERENCES dbo.[Vertrag](VertragsNr),
		CONSTRAINT UQ_Tours_TourId_ContractId UNIQUE (TourId, ContractId)
	) ON [PRIMARY]
GRANT SELECT ON [dbo].Tours_Contracts TO [Public]
GRANT DELETE ON [dbo].Tours_Contracts TO CanWriteTours
GRANT INSERT ON [dbo].Tours_Contracts TO CanWriteTours
GRANT UPDATE ON [dbo].Tours_Contracts TO CanWriteTours
END
--#endregion

--#region Tabelle Tours_Costs für die Kosten (z.B. für Transport) die bei der Tournee anfallen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Tours_Costs]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].Tours_Costs (
		TourCostId INT IDENTITY(1,1) NOT NULL,
		TourId INT NOT NULL,
		CostTypeId INT NOT NULL,
		[Description] NVARCHAR(40) NULL,
		[EstimatedCostValue] FLOAT NOT NULL CONSTRAINT DF_Tours_Costs_EstimatedCostValue DEFAULT 0,		
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		CONSTRAINT PK_Tours_Costs PRIMARY KEY CLUSTERED (TourCostId ASC) ON [PRIMARY],
		CONSTRAINT FK_Tours_Costs_Tours FOREIGN KEY (TourId) REFERENCES dbo.[Tours] (TourId),
		CONSTRAINT FK_Tours_Costs_Costs FOREIGN KEY (CostTypeId) REFERENCES dbo.Kosten (KostenID),
	) ON [PRIMARY]
GRANT SELECT ON [dbo].Tours_Costs TO [Public]
GRANT DELETE ON [dbo].Tours_Costs TO CanWriteTours
GRANT INSERT ON [dbo].Tours_Costs TO CanWriteTours
GRANT UPDATE ON [dbo].Tours_Costs TO CanWriteTours
END
--#endregion
--#endregion

 --2012-03-08 TK Fremdwährung
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.Currency') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.Currency (
			CurrencyId INT IDENTITY(1,1) NOT NULL,
			CurrencySymbol VARCHAR(3) NOT NULL,
			CurrencyName VARCHAR(30) NOT NULL,
			DefaultCurrencyRate FLOAT NULL,		
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_Currency PRIMARY KEY CLUSTERED (CurrencyId ASC) ON [PRIMARY]
		) ON [PRIMARY]
	GRANT SELECT ON dbo.Currency TO [Public]
	GRANT DELETE ON dbo.Currency TO [Stammdaten ändern]
	GRANT INSERT ON dbo.Currency TO [Stammdaten ändern]
	GRANT UPDATE ON dbo.Currency TO [Stammdaten ändern]
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ForeignCurrencyId' AND o.id = OBJECT_ID('dbo.Vertrag'))
BEGIN
	ALTER TABLE Vertrag ADD ForeignCurrencyId INT NULL 
	ALTER TABLE Vertrag ADD CurrencyRate FLOAT NULL  
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Vertrag_Currency]') AND type = 'F')
ALTER TABLE dbo.Vertrag ADD CONSTRAINT	FK_Vertrag_Currency FOREIGN KEY	(ForeignCurrencyId	)
REFERENCES dbo.Currency	(CurrencyId) 


IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ForeignCurrencyId' AND o.id = OBJECT_ID('dbo.CashCommandPos'))
BEGIN
	ALTER TABLE CashCommandPos ADD ForeignCurrencyId INT NULL 
	ALTER TABLE CashCommandPos ADD PaymentType INT NOT NULL CONSTRAINT DF_CashCommandPos_PaymentType DEFAULT 0
END

GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_CashCommandPos_Currency]') AND type = 'F')
ALTER TABLE dbo.CashCommandPos ADD CONSTRAINT	FK_CashCommandPos_Currency FOREIGN KEY	(ForeignCurrencyId	)
REFERENCES dbo.Currency	(CurrencyId) 
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'Note2' AND o.id = OBJECT_ID('dbo.StückeDienstplan'))
BEGIN
	ALTER TABLE StückeDienstplan ADD Note2 VARCHAR(1000)
END
GO

--Übernachtunngskostenpauschale hinzufügen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'OvernightExpensesFlat' and o.id = OBJECT_ID(N'[dbo].[VertragRolle]'))
BEGIN

	ALTER TABLE dbo.VertragRolle ADD OvernightExpensesFlat MONEY 
	
	--Daten nur übertragen wenn TravelExpensesFlat noch nicht da ist, da in früheren Versionen die Summe aus Unterkunft u. Übernachtung in TravelExpensesFlat geschrieben wurden
	IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TravelExpensesFlat' and o.id = OBJECT_ID(N'[dbo].[VertragRolle]'))
	
	exec('UPDATE VertragRolle Set OvernightExpensesFlat = s 
	FROM VertragRolle INNER JOIN 
		(SELECT ISNULL(VertragDetails.UnterkunftPro,0)  as s,
			(SELECT Min(VrID) FROM VertragRolle WHERE VertragRolle.VertragsNr=VertragDetails.VertragsNR ) as vrid   
			FROM VertragDetails WHERE (SELECT COUNT(*) FROM VertragRolle WHERE VertragRolle.VertragsNr=VertragDetails.VertragsNR) 
			 > 0 AND (not  VertragDetails.ReiseKostenpro is null or not VertragDetails.UnterkunftPro IS null)) as u ON VertragRolle.VRID=u.vrid')	

END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TravelExpensesFlat' and o.id = OBJECT_ID(N'[dbo].[VertragRolle]'))
BEGIN
	ALTER TABLE dbo.VertragRolle ADD TravelExpensesFlat MONEY 
	exec('UPDATE VertragRolle Set TravelExpensesFlat = s 
	FROM VertragRolle INNER JOIN 
		(SELECT ISNULL(VertragDetails.ReiseKostenpro,0) as s,
			(SELECT Min(VrID) FROM VertragRolle WHERE VertragRolle.VertragsNr=VertragDetails.VertragsNR ) as vrid   
			FROM VertragDetails WHERE (SELECT COUNT(*) FROM VertragRolle WHERE VertragRolle.VertragsNr=VertragDetails.VertragsNR) 
			 > 0 AND (not  VertragDetails.ReiseKostenpro is null or not VertragDetails.UnterkunftPro IS null)) as u ON VertragRolle.VRID=u.vrid')			 
END
GO


IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'RehearsalsCompensatedByPerformance' and o.id = OBJECT_ID(N'[dbo].[VertragRolle]'))
BEGIN
	ALTER TABLE Dienstplan ADD WorkingMinutes INT NOT NULL CONSTRAINT [DF_Dienstplan_WorkingMinutes] DEFAULT 0
	ALTER TABLE Dienstplan ADD WorkingMinutes1 INT NOT NULL CONSTRAINT [DF_Dienstplan_WorkingMinutes1] DEFAULT 0
	ALTER TABLE Dienstplan ADD WorkingMinutes2 INT NOT NULL CONSTRAINT [DF_Dienstplan_WorkingMinutes2] DEFAULT 0
	exec('UPDATE Dienstplan SET WorkingMinutes = ROUND(Az * 60, 0) WHERE Az <> 0')
	exec('UPDATE Dienstplan SET WorkingMinutes1 = ROUND(Az1 * 60, 0) WHERE Az1 <> 0')
	exec('UPDATE Dienstplan SET WorkingMinutes2 = ROUND(Az2 * 60, 0) WHERE Az2 <> 0')
	
	EXEC sp_rename 'Dienstplan.Az', 'azx', 'COLUMN'
	EXEC sp_rename 'Dienstplan.Az1', 'az1x', 'COLUMN'
	EXEC sp_rename 'Dienstplan.Az2', 'az2x', 'COLUMN'
	
	EXEC sp_rename 'Dienstplan.WorkingMinutes', 'Az', 'COLUMN'
	EXEC sp_rename 'Dienstplan.WorkingMinutes1', 'Az1', 'COLUMN'
	EXEC sp_rename 'Dienstplan.WorkingMinutes2', 'Az2', 'COLUMN'

	ALTER TABLE dbo.VertragRolle ADD RehearsalsCompensatedByPerformance INT NOT NULL CONSTRAINT [DF_VertragRolle_RehearsalsCompensatedByPerformance] DEFAULT 0
END	
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'alt' AND o.id = OBJECT_ID(N'[dbo].[Stücke]') AND c.isnullable = 1)
BEGIN	
	UPDATE Stücke SET alt = 0 WHERE alt IS NULL
	ALTER TABLE [dbo].Stücke  ALTER COLUMN alt SMALLINT NOT NULL
	ALTER TABLE [dbo].Stücke ADD CONSTRAINT DF_Productions_inactive DEFAULT (0) FOR alt
END
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TypID' AND o.id = OBJECT_ID(N'[dbo].[Stücke]') AND c.isnullable = 1)
BEGIN	
	UPDATE Stücke SET TypID = 0 WHERE TypID IS NULL
	ALTER TABLE [dbo].Stücke  ALTER COLUMN TypID INT NOT NULL
	ALTER TABLE [dbo].Stücke ADD CONSTRAINT DF_Productions_TypeId DEFAULT (0) FOR TypID
END
GO
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoWriteOwnRoster')
BEGIN
	EXEC sp_addrole @rolename = 'PersoWriteOwnRoster'
END

GO

UPDATE  BesetzungStd SET Besitzer = 1 WHERE Besitzer NOT IN (SELECT Gruppe.GruppeID FROM Gruppe)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Role_Group]') )
BEGIN
	ALTER TABLE BesetzungStd ADD CONSTRAINT FK_Role_Group FOREIGN KEY (Besitzer) REFERENCES Gruppe(GruppeID)
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.Attachments') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.Attachments (
			AttachmentId INT IDENTITY(1,1) NOT NULL,--ID
			AttachmentName VARCHAR(255) NOT NULL,--Anzeigename
			OriginalFileName VARCHAR(255) NOT NULL,--Name der Datei die Gespeichert wurde
			FileLength INT NOT NULL,--Länge der Datei
			AttachmentType INT NOT NULL,--Typ falls bekannt
			StoredFileName VARCHAR(255) NOT NULL,--Name unter dem die Datei abgelegt wurde (GUID)
			Category VARCHAR(255) NOT NULL,--Kategorie der Datei
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_Attachment PRIMARY KEY CLUSTERED (AttachmentId ASC) ON [PRIMARY]
		) ON [PRIMARY]
	GRANT SELECT ON dbo.Attachments TO [Public]
	GRANT DELETE ON dbo.Attachments TO [Public]
	GRANT INSERT ON dbo.Attachments TO [Public]
	GRANT UPDATE ON dbo.Attachments TO [Public]
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.ContractDocumentAttachments') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.ContractDocumentAttachments (
			ContractDocumentAttachmentId INT IDENTITY(1,1) NOT NULL,--ID
			ContractDocumentId INT NOT NULL, --ContractConfirmation...
			AttachmentId INT NOT NULL, --
			Note VARCHAR (255) NULL,
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_ContractDocumentAttachment PRIMARY KEY CLUSTERED (ContractDocumentAttachmentId ASC) ON [PRIMARY]
			CONSTRAINT FK_ContractDocumentAttachment_Contract FOREIGN KEY (ContractDocumentId) REFERENCES dbo.ContractConfirmations (ContractConfirmationId),
			CONSTRAINT FK_ContractDocumentAttachment_Attachment FOREIGN KEY (AttachmentId) REFERENCES dbo.[Attachments] (AttachmentId),
	) ON [PRIMARY]
	GRANT SELECT ON dbo.ContractDocumentAttachments TO [Public]
	GRANT DELETE ON dbo.ContractDocumentAttachments TO [Public]
	GRANT INSERT ON dbo.ContractDocumentAttachments TO [Public]
	GRANT UPDATE ON dbo.ContractDocumentAttachments TO [Public]
END
GO
IF NOT EXISTS (SELECT * FROM Settings WHERE Form = 'General' AND [Control] = 'DatabaseIdentifier')
BEGIN
INSERT INTO [dbo].[Settings] ([Form], [Control], [Pref], [WertText], [LM], [UM], [LC], [UC])
     VALUES( 'General','DatabaseIdentifier', NULL, NEWID(), GETDATE() ,0 ,GETDATE() ,0)
END
GO
--SELECT * FROM BesetzungStd WHERE ABGruppeID NOT IN (SELECT ABGruppe.ABGruppeId FROM ABGruppe)
--SELECT * FROM BesetzungStd WHERE AuffTNr NOT IN (SELECT AuffTypen.AuffTNr FROM AuffTypen)
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.SchoolHolidays') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.SchoolHolidays (
			SchoolHolidaysId INT IDENTITY(1,1) NOT NULL,
			Name VARCHAR(30) NOT NULL,	
			StartDate DATETIME NOT NULL,
			EndDate DATETIME NOT NULL,
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_SchoolHolidays PRIMARY KEY CLUSTERED (SchoolHolidaysId ASC) ON [PRIMARY]
		) ON [PRIMARY]
	GRANT SELECT ON dbo.SchoolHolidays TO [Public]
	GRANT DELETE ON dbo.SchoolHolidays TO [Stammdaten ändern]
	GRANT INSERT ON dbo.SchoolHolidays TO [Stammdaten ändern]
	GRANT UPDATE ON dbo.SchoolHolidays TO [Stammdaten ändern]
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'NotInSchoolHoliday' AND o.id = OBJECT_ID('dbo.RingBez'))
BEGIN
	ALTER TABLE RingBez ADD NotInSchoolHoliday BIT NOT NULL CONSTRAINT [DF_RingBez_NotInSchoolHoliday] DEFAULT 0
END
--20120419 fehlende Beziehungen erstellen
DELETE FROM Kosten_Stück WHERE KostenID NOT IN (SELECT Kosten.KostenID FROM Kosten)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Kosten_Stück_Kosten]') )
BEGIN
	ALTER TABLE Kosten_Stück ADD CONSTRAINT FK_Kosten_Stück_Kosten FOREIGN KEY (KostenID) REFERENCES Kosten(KostenID)
END

DELETE FROM Kosten_Aufführg WHERE KostenID NOT IN (SELECT Kosten.KostenID FROM Kosten)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Kosten_Aufführg_Kosten]') )
BEGIN
	ALTER TABLE Kosten_Aufführg ADD CONSTRAINT FK_Kosten_Aufführg_Kosten FOREIGN KEY (KostenID) REFERENCES Kosten(KostenID)
END
GO

--2012-05-10
--neue Spalte für die Produktion in ActivityScenes
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ProductionId' and o.id = OBJECT_ID(N'[dbo].[ActivityScenes]'))
BEGIN
	ALTER TABLE dbo.ActivityScenes ADD ProductionId INT NULL
	ALTER TABLE dbo.ActivityScenes ADD CONSTRAINT FK_ActivityScenes_Productions FOREIGN KEY (ProductionId) REFERENCES dbo.Stücke(SNr)
END	
GO

--2012-05-31 SH
--neue Spalten Format für DayNotes
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o on c.id = o.id
	WHERE c.name = 'Format' and o.id = OBJECT_ID(N'[dbo].[DayNotes]'))
BEGIN
	ALTER TABLE dbo.DayNotes ADD [Format] VARCHAR(512) NULL
END
GO

--2012-06-01 SH
--Ansicht der Tagesnotizen bei allen Abteilung uaf Standardmäßig ja setzen
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND Major <= 1 AND Minor < 293)
BEGIN
	UPDATE DienstplanArtenTabelle SET VisibleAreas = (VisibleAreas | 16)
END
GO

--2012-05-15
--neue Spalten für Schicht-Bemerkungen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o on c.id = o.id
	WHERE c.name = 'ShiftNote2' and o.id = OBJECT_ID(N'[dbo].[Dienstplan]'))
BEGIN
	ALTER TABLE dbo.Dienstplan ADD ShiftNote2 VARCHAR(100) NULL
	ALTER TABLE dbo.Dienstplan ADD ShiftNote3 VARCHAR(100) NULL
END
GO
	
--2012-05-16
--neue Spalten für Zeilennummer für die Anzeige im Dienstplan in ABGruppe
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o on c.id = o.id
	WHERE c.name = 'GroupPos' and o.id = OBJECT_ID(N'[dbo].[ABGruppe]'))
BEGIN
	ALTER TABLE dbo.ABGruppe ADD GroupPos INT NULL
	ALTER TABLE [dbo].ABGruppe ADD CONSTRAINT DF_ABGruppe_GroupPos DEFAULT (0) FOR GroupPos
END
GO
	
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ForeColor1' AND o.id = OBJECT_ID('dbo.Dienstplan'))
BEGIN
	ALTER TABLE Dienstplan ADD ForeColor1 INT NOT NULL CONSTRAINT DF_Dienstplan_ForeColor1 DEFAULT 0	
	ALTER TABLE Dienstplan ADD ForeColor2 INT NOT NULL CONSTRAINT DF_Dienstplan_ForeColor2 DEFAULT 0	
	ALTER TABLE Dienstplan ADD ForeColor3 INT NOT NULL CONSTRAINT DF_Dienstplan_ForeColor3 DEFAULT 0	
	UPDATE Dienstplan SET BackColor1 = Farbe WHERE (Farbe <> 0 AND Farbe <>-1) AND (BackColor1 = 0 OR  BackColor1 = -1)
	UPDATE Dienstplan SET BackColor2 = Farbe WHERE (Farbe <> 0 AND Farbe <>-1) AND (BackColor2 = 0 OR  BackColor2 = -1)
	UPDATE Dienstplan SET BackColor3 = Farbe WHERE (Farbe <> 0 AND Farbe <>-1) AND (BackColor3 = 0 OR  BackColor3 = -1)
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ForeColor' and o.id = OBJECT_ID(N'[dbo].[AuffDienstplanArten]'))
BEGIN
	ALTER TABLE dbo.AuffDienstplanArten ADD ForeColor  INT NOT NULL CONSTRAINT DF_AuffDienstplanArten_ForeColor DEFAULT 0
END
--20120525
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PublicChangeNote' and o.id = OBJECT_ID(N'[dbo].[AufführgDetails]'))
BEGIN
	ALTER TABLE dbo.AufführgDetails ADD PublicChangeNote VARCHAR(1000) NULL
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'RegulareWorkingTimeRule' and o.id = OBJECT_ID(N'[dbo].[FeiertageAusg]'))
BEGIN
	ALTER TABLE dbo.FeiertageAusg ADD RegulareWorkingTimeRule VARCHAR(5)
	exec('DELETE FROM FeiertageAusg WHERE Zyklus = 1')
	ALTER TABLE FeiertageAusg DROP COLUMN Zyklus
	ALTER TABLE FeiertageAusg DROP COLUMN ArbFreiGeplant
END

IF  NOT EXISTS (SELECT * FROM  FeiertageAusg)
BEGIN
	SET IDENTITY_INSERT dbo.FeiertageAusg ON
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (5 , 0, 0, 1, 0, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (6 , 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (11, 0, 1, 1, 0, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (12, 0, 1, 0, 0, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (17, 1, 0, 1, 0, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (18, 1, 0, 0, 0, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (23, 2, 0, 1, 1, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (24, 2, 0, 0, 0, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (29, 2, 1, 1, 1, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (30, 2, 1, 0, 0, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (35, 3, 0, 1, 1, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (36, 3, 0, 0, 0, 1, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (41, 3, 1, 1, 1, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (42, 3, 1, 0, 0, 1, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (47, 4, 1, 1, 1, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (48, 4, 1, 0, 0, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (49, 3, 7, 0, 0, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (50, 3, 7, 1, 0, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (51, 2, 7, 0, 0, 0, NULL, NULL, NULL, NULL)
	INSERT FeiertageAusg (FeiertageAusgID, FTArt, WT, ArbFrei, FF, AZA, LM, UM, LC, UC) VALUES (52, 2, 7, 1, 0, 0, NULL, NULL, NULL, NULL)
	SET IDENTITY_INSERT dbo.FeiertageAusg OFF
END
GO	

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[FeiertageAusg]')  AND name = 'IX_HolidayBalanceSetID_FtArt_Wt')
BEGIN
	
	CREATE UNIQUE NONCLUSTERED INDEX IX_HolidayBalanceSetID_FtArt_Wt ON dbo.FeiertageAusg
	(HolidayBalanceSetID, FTArt, Wt, ArbFrei) ON [PRIMARY]

END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ForeColor' and o.id = OBJECT_ID(N'[dbo].[AZTypen]'))
BEGIN
	ALTER TABLE dbo.AZTypen ADD ForeColor  INT NOT NULL CONSTRAINT DF_AZTypen_ForeColor DEFAULT 0
END
GO

--2012-06-06 SH
--neue Spalten in ZulagenDienstplan und Zulagen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BonusSalaryLevelId' and o.id = OBJECT_ID(N'[dbo].[ZulagenDienstplan]'))
BEGIN
	ALTER TABLE dbo.ZulagenDienstplan ADD BonusSalaryLevelId INT NULL
	ALTER TABLE dbo.ZulagenDienstplan ADD Percentage       INT NULL
	
	ALTER TABLE dbo.ZulagenDienstplan ADD CONSTRAINT FK_ZulagenDienstplan_SalaryLevel FOREIGN KEY (BonusSalaryLevelId) REFERENCES dbo.SalaryLevel(SalaryLevelId)

	ALTER TABLE dbo.Zulagen ADD IsPercentageAssignable  BIT NULL CONSTRAINT DF_Zulagen_IsPercentageAssignable  DEFAULT 0
	ALTER TABLE dbo.Zulagen ADD IsSalaryLevelAssignable BIT NULL CONSTRAINT DF_Zulagen_IsSalaryLevelAssignable DEFAULT 0
END
GO
--2012-06-06
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CollectivPersonId' and o.id = OBJECT_ID(N'[dbo].[ABGruppe]'))
BEGIN
	ALTER TABLE dbo.ABGruppe ADD CollectivPersonId INT 
END


--2012-06-07 TH
--neue Spalte für formelbezogene Einstellungen in der RapportSpalte
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o ON c.id = o.id
	WHERE c.name = 'FormulaSettings' AND o.id = OBJECT_ID(N'RapportSpalte'))
BEGIN
	ALTER TABLE RapportSpalte ADD FormulaSettings VARCHAR(2000) NULL
END
GO

--2012-06-11 TH
--neue Spalte für Kontierungsgruppe in der Tabelle Kostenstellen
IF  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o ON c.id = o.id
	WHERE c.name = 'AccountGroup' AND o.id = OBJECT_ID(N'CostCenter'))
BEGIN
	ALTER TABLE CostCenter DROP COLUMN AccountGroup
END
GO

--2012-07-12 TH
--neue Spalte für Kontierungsgruppe in der Tabelle Haushaltstitel
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o ON c.id = o.id
	WHERE c.name = 'AccountGroup' AND o.id = OBJECT_ID(N'BudgetItem'))
BEGIN
	ALTER TABLE BudgetItem ADD AccountGroup VARCHAR(80) NULL
END
GO


--2012-06-11 TH
--neue Tabelle die Daten für Vertragsarten/Abteilungen beinhaltet.
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.ContractType_Department') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.ContractType_Department (
			ContractType_DepartmentId INT IDENTITY(1,1) NOT NULL,
			ContractTypeId INT NOT NULL,	
			DepartmentId INT NOT NULL,	
			BudgetItemId INT NULL,	
			AllocationGroupId INT NULL,	
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_ContractType_Department PRIMARY KEY CLUSTERED (ContractType_DepartmentId ASC) ON [PRIMARY]
			CONSTRAINT FK_ContractType_Department_ContractType FOREIGN KEY (ContractTypeId) REFERENCES dbo.VertragsVorlagen (VorlagenID),
			CONSTRAINT FK_ContractType_Department_Department FOREIGN KEY (DepartmentId) REFERENCES dbo.Dienstplan (DienstplanId),
			CONSTRAINT FK_ContractType_Department_BudgetItem FOREIGN KEY (BudgetItemId) REFERENCES dbo.BudgetItem (BudgetItemId),
			CONSTRAINT FK_ContractType_Department_AllocationGroup FOREIGN KEY (AllocationGroupId) REFERENCES dbo.AllocationGroup (AllocationGroupId),
		) ON [PRIMARY]
	GRANT SELECT ON dbo.ContractType_Department TO [Public]
	GRANT DELETE ON dbo.ContractType_Department TO [Stammdaten ändern]
	GRANT INSERT ON dbo.ContractType_Department TO [Stammdaten ändern]
	GRANT UPDATE ON dbo.ContractType_Department TO [Stammdaten ändern]
END
GO

--2012-06-22 TH
--Pläne (Liste der Produktionen) umstellen
UPDATE [Plan] SET T1 = Bem, Bem = NULL WHERE PlanArt = 99 AND (T1 IS NULL)
GO

-- 2012-07-02 sh
-- erweiterungen für tourneen, start und endzeit sowie bemerkung
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o on c.id = o.id
	WHERE c.name = 'Note' and o.id = OBJECT_ID(N'[dbo].[Tours]'))
BEGIN
	ALTER TABLE dbo.Tours ADD Note VARCHAR(1024) NULL
	ALTER TABLE dbo.Tours ADD StartTime DATETIME NULL
	ALTER TABLE dbo.Tours ADD EndTime DATETIME NULL
	EXEC('UPDATE Tours SET Note = Description')
	EXEC('UPDATE Tours SET Description = NULL')
END
GO


--IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.ContractedRoles'))
--BEGIN
--	DROP VIEW dbo.ContractedRoles
--END
--GO
--CREATE VIEW dbo.ContractedRoles
--AS 
--SELECT vr.VRID, vr.RolleId, vr.vrVon, vr.vrBis, vr.LM, vr.UM, vr.LC, vr.UC 
-- FROM  
--	VertragRolle AS vr 
--	INNER JOIN Vertrag AS v ON VR.VertragsNr = v.VertragsNr  
--	INNER JOIN	(SELECT DISTINCT GruppeID, Schreiben 
--						FROM			UserGruppe 
--						INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
--						WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 1) AS UG
--				ON v.ModulGruppeID = UG.GruppeID
--GO
--GRANT SELECT ON ContractedRoles TO public
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.[AbVertragDetails]'))
BEGIN
	DROP VIEW dbo.[AbVertragDetails]
END
GO
CREATE VIEW [dbo].[AbVertragDetails]
AS 
SELECT  v.*  FROM  VertragDetails AS v  
	WHERE EXISTS
		(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 = 1 OR BerechtigungsbereichID = 5) and v.VertragsNr = Vertrag.VertragsNr) 


GO
GRANT SELECT ON [AbVertragDetails] TO public
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.[AbVertragDetails_Update]'))
BEGIN
	DROP VIEW dbo.[AbVertragDetails_Update]
END
GO
CREATE VIEW [dbo].[AbVertragDetails_Update]
AS 
SELECT * FROM VertragDetails WHERE VertragsNr 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 = 1 AND UserGruppe.Schreiben = 1) 
GO

	GRANT SELECT ON dbo.[AbVertragDetails_Update] TO [Public]
	GRANT DELETE ON dbo.[AbVertragDetails_Update] TO [Public]
	GRANT INSERT ON dbo.[AbVertragDetails_Update] TO [Public]
	GRANT UPDATE ON dbo.[AbVertragDetails_Update] TO [Public]
go
	GRANT SELECT ON dbo.[AbVertrag_Update] TO [Public]
	GRANT DELETE ON dbo.[AbVertrag_Update] TO [Public]
	GRANT INSERT ON dbo.[AbVertrag_Update] TO [Public]
	GRANT UPDATE ON dbo.[AbVertrag_Update] TO [Public]

GO


UPDATE VertragRolle SET RolleId = 0 WHERE Rolleid <> 0 AND NOT Rolleid IS NULL AND NOT EXISTS
 (SELECT * FROM BesetzungStd WHERE BesetzungStd.ID = Rolleid)

 IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractRole_Role]') AND type = 'F')
ALTER TABLE [dbo].VertragRolle  WITH CHECK ADD  CONSTRAINT FK_ContractRole_Role FOREIGN KEY(RolleId)
REFERENCES [dbo].BesetzungStd (Id) 
GO
ALTER TABLE [dbo].VertragRolle CHECK CONSTRAINT FK_ContractRole_Role
GO
--2012-07-11 TK: PersoPublic entfernen
IF EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'PersoPublic')
BEGIN
	EXEC DropRoleWithDropRoleMember N'PersoPublic'
END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.AbPersonal_Update'))
BEGIN
	DROP VIEW dbo.AbPersonal_Update
END
GO
--2012-07-11 TK: AbPersonal_Update erstellt
CREATE VIEW dbo.AbPersonal_Update
AS 
SELECT  PersH.*  FROM  PersH 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 pp.HasWritePermission=1 AND UG.Schreiben=1 AND ug.BerechtigungsbereichID = 0 AND pp.PermissionType=0 AND Username = CURRENT_USER GROUP BY pp.PersonId)
GO
	GRANT SELECT ON dbo.AbPersonal_Update TO [Public]
	GRANT DELETE ON dbo.AbPersonal_Update TO [Public]
	GRANT INSERT ON dbo.AbPersonal_Update TO [Public]
	GRANT UPDATE ON dbo.AbPersonal_Update TO [Public]

	GRANT SELECT ON dbo.ABPerskom_Update TO [Public]
	GRANT DELETE ON dbo.ABPerskom_Update TO [Public]
	GRANT INSERT ON dbo.ABPerskom_Update TO [Public]
	GRANT UPDATE ON dbo.ABPerskom_Update TO [Public]

	GRANT SELECT ON dbo.PersAgentur TO [Public]
	REVOKE DELETE ON dbo.PersAgentur TO [Public]
	REVOKE INSERT ON dbo.PersAgentur TO [Public]
	REVOKE UPDATE ON dbo.PersAgentur TO [Public]
	
GO
ALTER VIEW [dbo].[AbPersonalNotizen_Update]
AS
	SELECT * FROM PersonalNotizen WHERE PersonalNotizenID IN 
		(SELECT PersonalNotizenID FROM PersonalNotizen
			LEFT JOIN  
				(SELECT GruppeID FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
				WHERE  BerechtigungsbereichID = 0 AND  Username = CURRENT_USER and schreiben = 1) AS UG 
				ON (PersonalNotizen.Besitzer = UG.GruppeID )
	WHERE  NOT  UG.GruppeID IS NULL)


Go
-- TK 20120807
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o on c.id = o.id
	WHERE c.name = 'PricePercent' and o.id = OBJECT_ID(N'dbo.Ring'))
BEGIN
	ALTER TABLE dbo.Ring ADD PricePercent FLOAT NOT NULL CONSTRAINT DF_Ring_PricePercentage DEFAULT 0
	--Freietage pro Woch können jetzt 0 sein, vorher wurde bei 0 eine 2 zurüvkgegeben 
	UPDATE PersoParameter SET Freitage = 2 WHERE Freitage = 0 OR Freitage IS NULL
END
 
-- TK 20120808: [AbPersonalChield_Update] erstellt
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.[AbPersonalChield_Update]'))
BEGIN
	DROP VIEW dbo.[AbPersonalChield_Update]
END
GO
CREATE VIEW [dbo].[AbPersonalChield_Update]
AS 
SELECT  PersAgentur.*  FROM  PersAgentur 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 pp.HasWritePermission=1 AND UG.Schreiben=1 AND ug.BerechtigungsbereichID = 0 AND pp.PermissionType=0 AND Username = CURRENT_USER GROUP BY pp.PersonId)
	OR  ChildPersNr 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 pp.HasWritePermission=1 AND UG.Schreiben=1 AND ug.BerechtigungsbereichID = 0 AND pp.PermissionType=0 AND Username = CURRENT_USER GROUP BY pp.PersonId)
Go

GRANT SELECT ON dbo.[AbPersonalChield_Update] TO [Public]
GRANT DELETE ON dbo.[AbPersonalChield_Update] TO [Public]
GRANT INSERT ON dbo.[AbPersonalChield_Update] TO [Public]
GRANT UPDATE ON dbo.[AbPersonalChield_Update] TO [Public]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.SeatingPlans') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.SeatingPlans (
			SeatingPlanId INT IDENTITY(1,1) NOT NULL,
			Name VARCHAR(30) NOT NULL,	
			StageId INT NOT NULL,
			OrderNo INT NOT NULL  CONSTRAINT DF_SeatingPlans_OrderNo DEFAULT 0,
			IsInactive BIT NOT NULL CONSTRAINT DF_SeatingPlans_IsInactive DEFAULT 0,
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_SeatingPlans PRIMARY KEY CLUSTERED (SeatingPlanId ASC) ON [PRIMARY]
			CONSTRAINT FK_Stages_SeatingPlans FOREIGN KEY (StageId) REFERENCES dbo.Zr (ZrNr) ON DELETE CASCADE,
		) ON [PRIMARY]
	CREATE UNIQUE INDEX IX_SeatingPlans_Name ON SeatingPlans (Name)

	GRANT SELECT ON dbo.SeatingPlans TO [Public]
	GRANT DELETE ON dbo.SeatingPlans TO [Stammdaten ändern]
	GRANT INSERT ON dbo.SeatingPlans TO [Stammdaten ändern]
	GRANT UPDATE ON dbo.SeatingPlans TO [Stammdaten ändern]
END

GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.SeatGroups') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.SeatGroups (
			SeatGroupId INT IDENTITY(1,1) NOT NULL,
			Name VARCHAR(30) NOT NULL,	
			SeatingPlanId INT NOT NULL,
			OrderNo INT NOT NULL  CONSTRAINT DF_SeatGroups_OrderNo DEFAULT 0,
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_SeatGroups PRIMARY KEY CLUSTERED (SeatGroupId ASC) ON [PRIMARY]
			CONSTRAINT FK_SeatingPlans_SeatGroups FOREIGN KEY (SeatingPlanId) REFERENCES dbo.SeatingPlans (SeatingPlanId) ON DELETE CASCADE ,
		) ON [PRIMARY]

	GRANT SELECT ON dbo.SeatGroups TO [Public]
	GRANT DELETE ON dbo.SeatGroups TO [Stammdaten ändern]
	GRANT INSERT ON dbo.SeatGroups TO [Stammdaten ändern]
	GRANT UPDATE ON dbo.SeatGroups TO [Stammdaten ändern]
END
GO

 IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.SeatingPlan_PriceCategorys') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
 BEGIN
	CREATE TABLE dbo.SeatingPlan_PriceCategorys (
			SeatingPlanPriceCategoryId INT IDENTITY(1,1) NOT NULL,
			SeatingPlanId INT NOT NULL,
			PriceCategoryId INT NOT NULL,
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_SeatingPlan_PriceCategorys PRIMARY KEY CLUSTERED (SeatingPlanPriceCategoryId ASC) ON [PRIMARY]
			CONSTRAINT FK_PriceCategorys_SeatingPlan_PriceCategorys FOREIGN KEY (PriceCategoryId) REFERENCES dbo.Preise (PreisNr),
			CONSTRAINT FK_SeatingPlans_SeatingPlan_PriceCategorys  FOREIGN KEY (SeatingPlanId) REFERENCES dbo.SeatingPlans (SeatingPlanId) ON DELETE CASCADE,
		) ON [PRIMARY]

	CREATE UNIQUE NONCLUSTERED INDEX IX_SeatingPlanPriceCategorys_SeatingPlanId_PriceCategoryId ON dbo.SeatingPlan_PriceCategorys
	(SeatingPlanId, PriceCategoryId) ON [PRIMARY]

	GRANT SELECT ON dbo.SeatingPlan_PriceCategorys TO [Public]
	GRANT DELETE ON dbo.SeatingPlan_PriceCategorys TO [Stammdaten ändern]
	GRANT INSERT ON dbo.SeatingPlan_PriceCategorys TO [Stammdaten ändern]
	GRANT UPDATE ON dbo.SeatingPlan_PriceCategorys TO [Stammdaten ändern]
END
GO

 IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.TicketPrices') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.TicketPrices (
			TicketPriceId INT IDENTITY(1,1) NOT NULL,
			SeasonId INT NOT NULL,
			SeatGroupId INT NOT NULL,
			SeatingPlanPriceCategoryId INT NOT NULL,
			TicketKindId INT NOT NULL CONSTRAINT DF_TicketPrices_TicketKindId DEFAULT 0,
			PriceValue float NOT NULL,	
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_TicketPrices PRIMARY KEY CLUSTERED (TicketPriceId ASC) ON [PRIMARY]
			CONSTRAINT FK_Seasons_TicketPrices FOREIGN KEY (SeasonId) REFERENCES dbo.SpielzeitTabelle (SpzNr) ON DELETE CASCADE,
			CONSTRAINT FK_SeatGroups_TicketPrices FOREIGN KEY (SeatGroupId) REFERENCES dbo.SeatGroups (SeatGroupId) ON DELETE CASCADE,
			CONSTRAINT FK_SeatingPlan_PriceCategorys_TicketPrices FOREIGN KEY (SeatingPlanPriceCategoryId) REFERENCES dbo.SeatingPlan_PriceCategorys (SeatingPlanPriceCategoryId) 
		) ON [PRIMARY]
	CREATE UNIQUE NONCLUSTERED INDEX IX_TicketPrices_SeasonId_SeatGroupId_SeatingPlanPriceCategoryId_TicketKindId ON dbo.TicketPrices
	(SeasonId, SeatGroupId, SeatingPlanPriceCategoryId,TicketKindId) ON [PRIMARY]
	GRANT SELECT ON dbo.TicketPrices TO [Public]
	GRANT DELETE ON dbo.TicketPrices TO [Stammdaten ändern]
	GRANT INSERT ON dbo.TicketPrices TO [Stammdaten ändern]
	GRANT UPDATE ON dbo.TicketPrices TO [Stammdaten ändern]
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o on c.id = o.id
	WHERE c.name = 'SeatingPlanId' and o.id = OBJECT_ID(N'dbo.StückeSpz'))
BEGIN
	ALTER TABLE dbo.StückeSpz ADD SeatingPlanId INT NULL 
	ALTER TABLE dbo.AufführgDetails ADD SpecialSeatingPlanId INT NULL
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_SeatingPlans_ProductionsSeason') AND type = 'F')
ALTER TABLE dbo.StückeSpz   WITH CHECK ADD  CONSTRAINT FK_SeatingPlans_ProductionsSeason FOREIGN KEY(SeatingPlanId)
REFERENCES dbo.SeatingPlans (SeatingPlanId)
GO
ALTER TABLE dbo.StückeSpz CHECK CONSTRAINT FK_SeatingPlans_ProductionsSeason
Go

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_SeatingPlans_ActivityDetails]') AND type = 'F')
ALTER TABLE dbo.AufführgDetails  WITH CHECK ADD CONSTRAINT FK_SeatingPlans_ActivityDetails FOREIGN KEY(SpecialSeatingPlanId)
REFERENCES dbo.SeatingPlans (SeatingPlanId)
GO

ALTER TABLE dbo.AufführgDetails  CHECK CONSTRAINT FK_SeatingPlans_ActivityDetails
go

--2012-08-16 TH
-- Neue Spalte für Schriftinformationen einer Bühne
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'dbo.Vertrag')  AND name = 'IX_ModulGruppeID')
CREATE NONCLUSTERED INDEX IX_ModulGruppeID ON dbo.Vertrag (ModulGruppeID)  ON [PRIMARY]
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'FontFormatString' and o.id = OBJECT_ID(N'[dbo].[Zr]'))
BEGIN
	ALTER TABLE dbo.Zr ADD FontFormatString VARCHAR(600)
END
GO

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'FontFormatString' AND o.id = OBJECT_ID(N'[dbo].Zr') AND c.xtype <> 35)
BEGIN
	ALTER TABLE dbo.Zr ALTER COLUMN FontFormatString VARCHAR(600)
END
GO
-- 2012-08-31 TH
-- Neue Tabelle für PersonAttachments
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.PersonAttachments') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.PersonAttachments (
			PersonAttachmentsId INT IDENTITY(1,1) NOT NULL,--ID
			PersonId INT NOT NULL, 
			AttachmentId INT NOT NULL, 
			Note VARCHAR (255) NULL,
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_PersonAttachments PRIMARY KEY CLUSTERED (PersonAttachmentsId ASC) ON [PRIMARY]
			CONSTRAINT FK_PersonAttachments_Person FOREIGN KEY (PersonId) REFERENCES dbo.PersH (PersNr),
			CONSTRAINT FK_PersonAttachments_Attachment FOREIGN KEY (AttachmentId) REFERENCES dbo.[Attachments] (AttachmentId),
	) ON [PRIMARY]
	GRANT SELECT ON dbo.PersonAttachments TO [Public]
	GRANT DELETE ON dbo.PersonAttachments TO [Public]
	GRANT INSERT ON dbo.PersonAttachments TO [Public]
	GRANT UPDATE ON dbo.PersonAttachments TO [Public]
END
GO

--20120829 tk
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Description' AND o.id = OBJECT_ID(N'dbo.CashCommandPos') AND c.prec < 1000)
BEGIN
	ALTER TABLE CashCommandPos ALTER COLUMN [Description] VARCHAR(1000)
END


-- 2012-08-31 TH
-- ProduktionSpielzeiten mit ID 0 entfernen
IF EXISTS (SELECT * FROM StückeSPZ WHERE Spznr = 0)
BEGIN
	DELETE FROM StückeSPZ WHERE SPZNR = 0
END
GO

--20120903 tk
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.CashCommandPos_ContractDate') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.CashCommandPos_ContractDate(
		CashCommandPos_ContractDateId INT IDENTITY(1,1) NOT NULL,
		CashCommandPosId INT NOT NULL,
		ContractDateId INT NOT NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
	 CONSTRAINT PK_CashCommandPos_ContractDate PRIMARY KEY CLUSTERED  (CashCommandPos_ContractDateId ASC) ON [PRIMARY],
	 CONSTRAINT FK_CashCommandPos_ContractDate_CashCommandPos FOREIGN KEY(CashCommandPosId) REFERENCES dbo.CashCommandPos (CashCommandPosId) ON DELETE CASCADE,
	 CONSTRAINT FK_CashCommandPos_ContractDate_ContractDates FOREIGN KEY(ContractDateId) REFERENCES dbo.ContractDates (ContractDateId) ON DELETE CASCADE
	) ON [PRIMARY]	
END

GRANT SELECT ON dbo.CashCommandPos_ContractDate TO public

GRANT DELETE ON dbo.SeatingPlans TO [Vorverkauf ändern]
GRANT INSERT ON dbo.SeatingPlans TO [Vorverkauf ändern]
GRANT UPDATE ON dbo.SeatingPlans TO [Vorverkauf ändern]

GRANT DELETE ON dbo.SeatGroups TO [Vorverkauf ändern]
GRANT INSERT ON dbo.SeatGroups TO [Vorverkauf ändern]
GRANT UPDATE ON dbo.SeatGroups TO [Vorverkauf ändern]

GRANT DELETE ON dbo.SeatingPlan_PriceCategorys TO [Vorverkauf ändern]
GRANT INSERT ON dbo.SeatingPlan_PriceCategorys TO [Vorverkauf ändern]
GRANT UPDATE ON dbo.SeatingPlan_PriceCategorys TO [Vorverkauf ändern]

GRANT DELETE ON dbo.TicketPrices TO [Vorverkauf ändern]
GRANT INSERT ON dbo.TicketPrices TO [Vorverkauf ändern]
GRANT UPDATE ON dbo.TicketPrices TO [Vorverkauf ändern]



--2012-09-06
--Bezeichnung von Arbeitsbereich von 30 auf 60 Zeichen (Lyon)
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
		WHERE c.name = 'Bezeichnung' AND o.id = OBJECT_ID(N'[dbo].AB') AND c.prec < 60)
	BEGIN
		ALTER TABLE AB ALTER COLUMN Bezeichnung NVARCHAR(60) NOT NULL
	END
GO
--2012-09-11 TH
--Bugfix am Personalview für Mandantentrennung
ALTER VIEW [dbo].[Personal]
AS 
SELECT PersH.PersNr, PersH.Suchname, PersH.Vorname, PersH.Nachname, PersH.PersKatNr, PersH.Geschlecht, PersH.PersHTS, PersH.alt, PersH.VornKurz, PersH.MatchCode, pTitel
FROM PersH 
INNER JOIN PersKat ON Persh.Perskatnr=Perskat.PersKatNr 
INNER JOIN Gruppe AS G ON G.GruppeID = Besitzer 
WHERE (ShowInModul&1=1 OR G.Modul = 1) AND Besitzer <> 0 AND (Adressart = 0 or Adressart >99)
GO
--ID 0 wird nicht benötigt und hat zu Problemen geführt
DELETE FROM Jahresabschluss WHERE DienstplanArtenID = 0
DELETE FROM DienstplanArtenTabelle WHERE DienstplanArtenID = 0
Go
DELETE FROM AdressAuswahlPersKat WHERE NOT EXISTS (SELECT * FROM PersKat WHERE PersKat.PersKatNr = AdressAuswahlPersKat.PersKat)
GO
--Kopie von [InherhitPermissions]

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.InheritPermissions'))
BEGIN
	DROP PROCEDURE dbo.InheritPermissions 
END
go
-- =============================================
-- Author:			Torsten Klier
-- Create date:		2010 11 01
-- Modified date:	201 01 24
-- (Abteilungs-)Gruppenberechtigungen aus Datenbankrollen übernehmen
-- Wenn ein Recht aus mehreren Datenbankrollen geerbt wird, wird das "größte" übernommen 
-- =============================================
CREATE PROCEDURE dbo.InheritPermissions
AS
BEGIN   
DECLARE @dbo BIT
DECLARE @CurrentUserId INT

SELECT @dbo = IS_MEMBER('db_owner')
IF @dbo = 0 
	BEGIN
		SELECT @CurrentUserId = UserId FROM UserPw WHERE UserName = CURRENT_USER 
		Print 'User' +  cast(@CurrentUserId as Varchar(10))
	END  
ELSE
	BEGIN
		SET @CurrentUserId = -1
		Print 'All User'
	END
	
--neue Berechtigungen einfügen
	INSERT INTO UserGruppe (GruppeID, UserID, BerechtigungsbereichID, Schreiben, OptionsFlag, IsInherited, LM, UM, LC, UC)
	SELECT  soll.GruppeID, ugs.UserID, soll.BerechtigungsbereichID, CAST(COUNT(soll.Schreiben) AS BIT), MAX(soll.OptionsFlag), 1, MAX(soll.LM), MAX(soll.UM), MAX(soll.LC), MAX(soll.UC)
	FROM	UsersInGroups AS ugs 
		INNER JOIN	UserGruppe AS soll	ON ugs.GroupID = soll.UserID
		LEFT JOIN	UserGruppe AS ist	ON ugs.UserID = ist.UserID AND soll.GruppeID  = ist.GruppeID AND soll.BerechtigungsbereichID = ist.BerechtigungsbereichID
	WHERE  ist.UserGruppeID IS NULL AND (ugs.UserId = @CurrentUserId OR @CurrentUserId = -1)
	GROUP BY soll.GruppeID, ugs.UserID, soll.BerechtigungsbereichID

	--Berechtigungen entfernen
	DELETE FROM UserGruppe 
	WHERE IsInherited = 1 
		AND (UserGruppe.UserId = @CurrentUserId OR @CurrentUserId = -1)
		AND  UserGruppeID NOT IN 
				(
					SELECT  ist.UserGruppeID
					FROM			UsersInGroups AS ugs 
						INNER JOIN	UserGruppe AS soll		ON ugs.GroupId = soll.UserID
						INNER JOIN	UserGruppe as ist	ON ugs.UserID = ist.UserID AND soll.GruppeID  = ist.GruppeID AND soll.BerechtigungsbereichID = ist.BerechtigungsbereichID
				)
	
	UPDATE UserGruppe SET UserGruppe.Schreiben = SollSchreiben, UserGruppe.OptionsFlag=SollOp
	FROM 
	(SELECT ugs.UserId, g.GruppeID, BerechtigungsbereichID, MAX(CAST(g.Schreiben AS INT)) AS SollSchreiben, MAX(CAST(g.OptionsFlag AS INT)) AS SollOp 
		FROM UsersInGroups AS ugs 
			INNER JOIN UserGruppe AS G ON ugs.GroupId = G.UserID
		GROUP BY ugs.UserId , g.GruppeID, BerechtigungsbereichID) AS soll 
	INNER JOIN UserGruppe  ON 
			soll.UserId = UserGruppe.UserID AND 
			soll.GruppeID = UserGruppe.GruppeID AND 
			soll.BerechtigungsbereichID = UserGruppe.BerechtigungsbereichID
	WHERE  (SollSchreiben <> UserGruppe.Schreiben OR SollOp <>  UserGruppe.OptionsFlag)  AND UserGruppe.IsInherited = 1 AND (UserGruppe.UserId = @CurrentUserId OR @CurrentUserId = -1)
 	
	
	--Jeden User in Gruppe Kontaktdaten Jeder
	INSERT INTO UserGruppe(GruppeID ,UserID ,Schreiben, LM, UM, LC, UC, BerechtigungsbereichID, OptionsFlag)
	SELECT -1, UserPw.UserID, 0, GETDATE(), 0 ,GETDATE(), 0, 0, 0  
	FROM UserPw LEFT JOIN (SELECT * FROM UserGruppe WHERE BerechtigungsbereichID = 0 AND GruppeID = -1) AS UG on UserPW.UserID=UG.UserID WHERE UG.UserGruppeID IS NULL

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

	--2014-09-05 sh
	--um das löschen zu beschleunigen, werden die ids aus der bisherigen in-anweisung in eine eigene temporäre tabelle gespeichert
	CREATE TABLE #UserIdTable(UserForAccessID INT)
	INSERT into #UserIdTable (UserForAccessID)
	SELECT			ist.UserForAccessID
	FROM			UsersInGroups AS ugs  	
		INNER JOIN	UserForAccess soll		ON ugs.GroupId = soll.UserID
		INNER JOIN	UserForAccess ist		ON ugs.UserId = ist.UserID  AND soll.SpzNr=ist.SpzNr

	DELETE FROM UserForAccess 
	WHERE IsInherited = 1 AND  UserForAccessID NOT IN (
		SELECT UserForAccessID from #UserIdTable
	) AND (UserId = @CurrentUserId OR @CurrentUserId = -1)
END	
GO
GRANT EXECUTE ON InheritPermissions TO Public

Go


--tk 20120914 REFERENCES Verkaufsstatus
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_AufführgDetails_VKStatus') AND type = 'F')
BEGIN
UPDATE AufführgDetails Set AufführgDetails.VKStatus = NULL WHERE NOT AufführgDetails.VKStatus IS NULL AND  NOT EXISTS (SELECT * FROM VKStatus WHERE  VKStatus.VkStatusNr =AufführgDetails.VKStatus  )
ALTER TABLE dbo.AufführgDetails  WITH CHECK ADD  CONSTRAINT FK_AufführgDetails_VKStatus FOREIGN KEY(VKStatus)
REFERENCES dbo.VKStatus (VKStatusNr)
END
GO
ALTER TABLE dbo.AufführgDetails CHECK CONSTRAINT FK_AufführgDetails_VKStatus
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Note' and o.id = OBJECT_ID(N'dbo.BesetzungStdSoliTabelle'))
BEGIN
	ALTER TABLE dbo.BesetzungStdSoliTabelle ADD Note VARCHAR(250)
END
GO
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'ContractTrackingWrite')
BEGIN
	EXEC sp_addrole @rolename = N'ContractTrackingWrite'
	EXEC sp_addrole @rolename = N'ContractTrackingRead'
END


GRANT SELECT ON dbo.ContractDateConfirmations TO ContractTrackingRead
GRANT UPDATE ON dbo.ContractDateConfirmations TO ContractTrackingWrite
GRANT UPDATE ON dbo.ContractDates TO ContractTrackingWrite
GRANT SELECT ON dbo.ContractDateConfirmations TO ContractTrackingWrite
GRANT SELECT ON dbo.ContractConfirmations TO ContractTrackingRead
GRANT SELECT ON dbo.ContractConfirmations TO ContractTrackingWrite
GRANT SELECT ON dbo.ContractTracking TO ContractTrackingRead
GRANT SELECT ON dbo.ContractTracking TO ContractTrackingWrite
GRANT DELETE ON dbo.ContractTracking TO ContractTrackingWrite
GRANT INSERT ON dbo.ContractTracking TO ContractTrackingWrite
GRANT UPDATE ON dbo.ContractTracking TO ContractTrackingWrite


GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[ContractSeasonInformation]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ContractSeasonInformation](
	[ContractSeasonInformationId] [int] IDENTITY(1,1) NOT NULL,
	[ContractId] [int] NOT NULL,
	[SeasonId] [int] NOT NULL,
	[CalculationType] [int] NOT NULL,
	[LM] [datetime] NOT NULL,
	[UM] [int] NOT NULL,
	[LC] [datetime] NOT NULL,
	[UC] [int] NOT NULL,
 CONSTRAINT [PK_ContractSeasonInformation] PRIMARY KEY CLUSTERED ([ContractSeasonInformationId] ASC) ON [PRIMARY],
  CONSTRAINT [FK_ContractSeasonInformation_Contract] FOREIGN KEY([ContractId]) REFERENCES dbo.[Vertrag] ([VertragsNr]) ON DELETE CASCADE,
	 CONSTRAINT [PK_ContractSeasonInformation_Season] FOREIGN KEY([SeasonId]) REFERENCES dbo.[SpielzeitTabelle] ([SpzNr]) ON DELETE CASCADE
	 ) ON [PRIMARY]
END
GO

GRANT SELECT ON dbo.[ContractSeasonInformation] TO public
GRANT DELETE ON dbo.[ContractSeasonInformation] TO public
GRANT INSERT ON dbo.[ContractSeasonInformation] TO public
GRANT UPDATE ON dbo.[ContractSeasonInformation] TO public

--TK 2012-10-22 Zulagen ab einer Anzahl von Vst.
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'FromCount' and o.id = OBJECT_ID(N'dbo.ProductionBonus'))
BEGIN
	ALTER TABLE dbo.ProductionBonus ADD FromCount int NOT NULL  CONSTRAINT DF_ProductionBonus_FromCount DEFAULT 0
END

--TH 2012-10-24 Constrain korrigiert
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractType_Department_Department]') )
BEGIN
	ALTER TABLE ContractType_Department DROP CONSTRAINT FK_ContractType_Department_Department
	ALTER TABLE ContractType_Department ADD CONSTRAINT FK_ContractType_Department_Department FOREIGN KEY (DepartmentId) REFERENCES DienstplanArtenTabelle(DienstplanArtenID)
END
GO



IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GetActvityTypeNumbersRehearsal]') )
BEGIN
	DROP FUNCTION [dbo].[GetActvityTypeNumbersRehearsal]
END
GO
--Prüfen, ob es sich um einen SQL2005 oder höher hadelt und das Statement zum erstellen ggf erstellen
DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
DECLARE @SQL as varchar(4000) 
IF (@sql_server_version > 8)
	BEGIN
		SET @SQL = 'CREATE FUNCTION [dbo].[GetActvityTypeNumbersRehearsal](@start DATETIME, @end DATETIME)
		RETURNS TABLE
		AS
			RETURN (SELECT Row_Number() OVER (PARTITION BY Art, Snr ORDER BY Datum, CONVERT(CHAR(5), UhrBeg, 108)) as RowNum, AuffNr, Datum, SNr, ZRNr
			FROM AufführgTabelle AS A
			JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art 
			WHERE AT.LfdNr = 1 AND Datum BETWEEN @start AND @end AND [status] BETWEEN 0 AND 99)'
	END

--Ausführen des Create-Statement
EXEC (@sql)	
GO

--Nicht bei SQL2000
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GetActvityTypeNumbersRehearsal]') )
BEGIN
	GRANT SELECT ON GetActvityTypeNumbersRehearsal TO Public
END
GO


IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GetActvityTypeNumbersPerformance]') )
BEGIN
	DROP FUNCTION [dbo].[GetActvityTypeNumbersPerformance]
END
GO
--Prüfen, ob es sich um einen SQL2005 oder höher hadelt und das Statement zum erstellen ggf erstellen
DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
DECLARE @SQL as varchar(4000) 
IF (@sql_server_version > 8)
	BEGIN
		SET @SQL = 'CREATE FUNCTION [dbo].[GetActvityTypeNumbersPerformance](@start DATETIME, @end DATETIME)
		RETURNS TABLE
		AS
			RETURN (SELECT Row_Number() OVER (PARTITION BY Snr ORDER BY Datum, CONVERT(CHAR(5), UhrBeg, 108)) as RowNum, AuffNr, Datum, SNr, ZRNr
			FROM AufführgTabelle AS A
			JOIN AuffTypen AS AT ON AT.AuffTnr = A.Art
			WHERE KatNr = 0 AND Datum BETWEEN @start AND @end AND [status] BETWEEN 0 AND 99)'
	END
--Ausführen des Create-Statement
EXEC (@sql)
GO
--Nicht bei SQL2000
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GetActvityTypeNumbersPerformance]') )
BEGIN
	GRANT SELECT ON GetActvityTypeNumbersPerformance TO Public
END
GO

--Zuordnung von Ressource zu Tour
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o on c.id = o.id
	WHERE c.name = 'TourId' and o.id = OBJECT_ID(N'dbo.ResourceBlockPeriods'))
BEGIN
	ALTER TABLE dbo.ResourceBlockPeriods ADD TourId INT NULL
END

--Veranstalter einer Tour
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o on c.id = o.id
	WHERE c.name = 'ContactId' and o.id = OBJECT_ID(N'dbo.Tours'))
BEGIN
	ALTER TABLE dbo.Tours ADD ContactId INT NULL
END

--Art der "Tour" Vermietung/Gastspiel/Co-Produktion (Lookup/Enum)
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o on c.id = o.id
	WHERE c.name = 'TourTypeId' and o.id = OBJECT_ID(N'dbo.Tours'))
BEGIN
	ALTER TABLE dbo.Tours ADD TourTypeId INT NOT NULL CONSTRAINT DF_Tours_TourTypeId DEFAULT 0
END

--Zuordnung einer Aktivität zu einer Tour 
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysObjects o on c.id = o.id
	WHERE c.name = 'TourId' and o.id = OBJECT_ID(N'dbo.AufführgDetails'))
BEGIN
	ALTER TABLE dbo.AufführgDetails ADD TourId INT NULL
END
GO
--
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[ActivityTypeGroups]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[ActivityTypeGroups](
	[ActivityTypeGroupId] [int] IDENTITY(1,1) NOT NULL,
	[ActivityTypeId] [int] NOT NULL,
	[GroupId] [int] NOT NULL,
	[LM] [datetime] NOT NULL,
	[UM] [int] NOT NULL,
	[LC] [datetime] NOT NULL,
	[UC] [int] NOT NULL,
 CONSTRAINT [PK_ActivityTypeGroups] PRIMARY KEY CLUSTERED ([ActivityTypeGroupId] ASC) ON [PRIMARY],
  CONSTRAINT [FK_ActivityTypeGroup_ActivityType] FOREIGN KEY([ActivityTypeId]) REFERENCES dbo.[AuffTypen] ([AuffTNr]) ON DELETE CASCADE,
	 CONSTRAINT [PK_ActivityTypeGroup_Group] FOREIGN KEY([GroupId]) REFERENCES dbo.[Gruppe] ([GruppeID]) ON DELETE CASCADE
	 ) ON [PRIMARY]
END
GRANT SELECT ON [ActivityTypeGroups] TO Public
GRANT INSERT ON [ActivityTypeGroups] TO [Stammdaten ändern]
GRANT DELETE ON [ActivityTypeGroups] TO [Stammdaten ändern]
GRANT UPDATE ON [ActivityTypeGroups] TO [Stammdaten ändern]

GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.[ActivitiesUpdate]'))
BEGIN
	DROP VIEW dbo.[ActivitiesUpdate]
END
GO
CREATE VIEW [dbo].[ActivitiesUpdate]
AS
SELECT * 
FROM AufführgTabelle AS Auff 
WHERE Auff.Datum <= dbo.AccessDatum() 
AND AuffNr IN(
			SELECT DISTINCT A.AuffNr FROM AufführgTabelle AS A
			INNER JOIN AuffTypen AS AT ON AT.AuffTNr = A.Art
			LEFT JOIN ActivityTypeGroups AS ATG ON AT.AuffTNr = ATG.ActivityTypeId
			LEFT JOIN Stücke AS S ON S.Snr = A.SNr
				LEFT JOIN UserGruppe AS UGBB2 ON UGBB2.BerechtigungsbereichID = 2 AND UGBB2.schreiben <> 0 AND UGBB2.GruppeID = S.ModuleGroupId
			LEFT JOIN UserPW AS UPBB2 ON UGBB2.Userid  = UPBB2.Userid AND UPBB2.Username = CURRENT_USER
				LEFT JOIN UserGruppe AS UGBB9 ON UGBB9.BerechtigungsbereichID = 9 AND UGBB9.schreiben <> 0 AND UGBB9.GruppeID = ATG.GroupId
			LEFT JOIN UserPW AS UPBB9 ON UGBB9.Userid  = UPBB9.Userid AND UPBB9.Username = CURRENT_USER
			INNER JOIN UserPW AS UPC ON UPC.UserId = A.UC
			WHERE (ATG.ActivityTypeId IS NULL OR UPBB9.UserID IS NOT NULL) AND UPBB2.UserID IS NOT NULL OR 
			(1 = IS_MEMBER('db_owner') OR (UPC.UserName = CURRENT_USER))
		)
WITH CHECK OPTION
GO

GRANT SELECT ON [ActivitiesUpdate] TO Public
GRANT INSERT ON [ActivitiesUpdate] TO Public
GRANT DELETE ON [ActivitiesUpdate] TO Public
GRANT UPDATE ON [ActivitiesUpdate] TO Public
GO

IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'EditActivityRequests')
BEGIN
	EXEC sp_addrole @rolename = N'EditActivityRequests'
END

UPDATE AdressSpalte SET Schrift = 8 WHERE ISNULL(Schrift,0) = 0
GO

-- 2012-11-09 SH
-- neue spalte für resourceobject -> 
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsGuestPerformanceCapable' and o.id = OBJECT_ID(N'dbo.ResourceObjects'))
BEGIN
	ALTER TABLE dbo.ResourceObjects ADD IsGuestPerformanceCapable BIT NOT NULL CONSTRAINT DF_ResourceObjects_IsGuestPerformanceCapable DEFAULT 0
END
GO

DELETE FROM ZulagenDienstplan  WHERE Wert = 0 AND CostUnitId IS NULL  AND BonusSalaryLevelId IS NULL and Percentage IS NULL
DELETE FROM ZeitkontenMonat WHERE Wert = 0 AND (Bem IS NULL OR Bem = '' OR Bem = 'auto') AND (zmtype IN (1,4,16,32) OR (zmtype IN (2,8) AND Bem = 'auto'))
GO

--2012-11-15 SH
--neue spalten für salaryleveldata für brüssel
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'MonthlyRate' and o.id = OBJECT_ID(N'dbo.SalaryLevelData'))
BEGIN
	ALTER TABLE dbo.SalaryLevelData ADD MonthlyRate FLOAT NOT NULL CONSTRAINT DF_SalaryLevelData_MonthlyRate DEFAULT 0
	ALTER TABLE dbo.SalaryLevelData ADD Note VARCHAR(20) NULL
END
GO

--2012-11-19 SH
--neue spalten für contractdates zum identifizieren
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'LookupId' and o.id = OBJECT_ID(N'dbo.ContractDates'))
BEGIN
	ALTER TABLE dbo.ContractDates ADD LookupId VARCHAR(10) NULL
END
GO

--2012-11-16 sh
--anpassung von castpublic da dispo gruppen wo id >1 ausgeschlossen wurden
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[CastPublic]'))
BEGIN
	DROP VIEW [dbo].[CastPublic]
END
GO

--2009-09-21 CastPublic darf keine geheimen Dispo-Besetzungen zurückgeben!!
--2012-11-16 SH Prüfung auf Dispo-Besetzung nun über Gruppe und dessen Modul
CREATE VIEW [dbo].[CastPublic]
AS
	SELECT	ca.*
	FROM    dbo.BesetzungTabelle		AS ca 
		LEFT JOIN dbo.BesetzungStd		AS ro ON ca.RolleID = ro.ID
		LEFT JOIN dbo.Gruppe            AS g  ON g.GruppeID = ro.Besitzer	
	WHERE ca.Gesperrt = 0  OR ca.RolleId IS NULL OR g.Modul > 1	
GO

GRANT SELECT ON [dbo].CastPublic TO Public

GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_AuffTypen_VonZeitDrucken]') )
BEGIN
	UPDATE Aufftypen SET VonzeitDrucken = 1 WHERE VonzeitDrucken IS NULL 
	ALTER TABLE Aufftypen ALTER COLUMN VonzeitDrucken BIT NOT NULL
	ALTER TABLE Aufftypen ADD CONSTRAINT DF_AuffTypen_VonzeitDrucken DEFAULT 0 FOR VonzeitDrucken

	UPDATE Aufftypen SET BiszeitDrucken = 0 WHERE BiszeitDrucken IS NULL 
	ALTER TABLE Aufftypen ALTER COLUMN BiszeitDrucken BIT NOT NULL
	ALTER TABLE Aufftypen ADD CONSTRAINT DF_AuffTypen_BiszeitDrucken DEFAULT 0 FOR BiszeitDrucken

	
	UPDATE Aufftypen SET tsAuffTypBasisID = 0 WHERE tsAuffTypBasisID IN (10,200,380,420,430,480,490,600)
END
	UPDATE Aufftypen SET tsAuffTypBasisID = 560 WHERE tsAuffTypBasisID = 561


IF NOT EXISTS (SELECT * FROM [ActivityTypeGroups]) AND  EXISTS (SELECT * FROM Aufftypen WHERE Aufftypen.ModulGruppeIDWrite <> 1  )
BEGIN

	--Berechtigungen auf neue Struktur anpassen
	INSERT INTO [dbo].[ActivityTypeGroups]
			   ([ActivityTypeId]
			   ,[GroupId]
			   ,[LM],[UM],[LC],[UC])
	(	SELECT AT.AuffTNr, G.GruppeID, '19000101', 0, '19000101', 0 
		FROM Aufftypen AS AT 
			JOIN Gruppe AS G ON G.Modul = 4
		WHERE AT.ModulGruppeIDWrite&4 = 4 AND EXISTS (SELECT * FROM UserGruppe WHERE UserGruppe.GruppeID = g.GruppeID AND  [BerechtigungsbereichID] = 2) )

	INSERT INTO [dbo].[ActivityTypeGroups]
			   ([ActivityTypeId]
			   ,[GroupId]
			   ,[LM], [UM], [LC], [UC])
	(	SELECT AT.AuffTNr, G.GruppeID, '19000101', 0, '19000101', 0 
		FROM Aufftypen AS AT 
			JOIN Gruppe AS G ON G.Modul = 1
		WHERE AT.ModulGruppeIDWrite&1 = 1 AND EXISTS (SELECT * FROM UserGruppe WHERE UserGruppe.GruppeID = g.GruppeID AND  [BerechtigungsbereichID] = 2))

	INSERT INTO [dbo].[ActivityTypeGroups]
			   ([ActivityTypeId]
			   ,[GroupId]
			   ,[LM],[UM],[LC],[UC])
	(	SELECT AT.AuffTNr, G.GruppeID, '19000101', 0, '19000101', 0 
		FROM Aufftypen AS AT 
			JOIN Gruppe AS G ON G.Modul = 2
		WHERE AT.ModulGruppeIDWrite&2 = 2 AND EXISTS (SELECT * FROM UserGruppe WHERE UserGruppe.GruppeID = g.GruppeID AND  [BerechtigungsbereichID] = 2))

	INSERT INTO [dbo].[ActivityTypeGroups]
			   ([ActivityTypeId]
			   ,[GroupId]
			   ,[LM] ,[UM] ,[LC] ,[UC]) 
	(	SELECT AT.AuffTNr, G.GruppeID, '19000101', 0, '19000101', 0 
		FROM Aufftypen AS AT 
			JOIN Gruppe AS G ON G.Modul = 16
		WHERE AT.ModulGruppeIDWrite&16 = 16 AND EXISTS (SELECT * FROM UserGruppe WHERE UserGruppe.GruppeID = g.GruppeID AND  [BerechtigungsbereichID] = 2))

END
GO

----Berechtigungen auf Aufführungen anpassen
--UPDATE UserGruppe SET Schreiben = 1 
--WHERE BerechtigungsbereichId = 2 AND 
--GruppeID IN (
--	SELECT GruppeID 
--	FROM Gruppe 
--	WHERE Modul = 1) 
--AND UserID IN (
--	SELECT DISTINCT(UG.UserID) 
--	FROM UserGruppe AS UG 
--	INNER JOIN Gruppe AS G ON G.GruppeID = UG.GruppeID
--	WHERE UG.Schreiben = 1 AND G.Modul <>1)


--INSERT INTO [dbo].[UserGruppe]
--           ([GruppeID]
--           ,[UserID]
--           ,[Schreiben]
--           ,[LM]
--           ,[UM]
--           ,[LC]
--           ,[UC]
--           ,[BerechtigungsbereichID]
--           ,[OptionsFlag]
--           ,[IsInherited]
--           ,[Options])
--SELECT DISTINCT GNEW.GruppeID, UGEX.UserID, 1, '19000101', 0, '19000101', 0, 2, 0, 0,NULL
--FROM UserGruppe AS UGEX
--INNER JOIN Gruppe AS GEX ON GEX.GruppeID = UGEX.GruppeID
--LEFT JOIN Gruppe AS GNEW ON GNEW.Modul = 1
--WHERE UGEX.[BerechtigungsbereichID] = 2 AND Schreiben = 1 AND GEX.Modul <> 1 AND NOT EXISTS(
--	SELECT * 
--	FROM UserGruppe AS UG 
--	WHERE UG.GruppeID = GNEW.GruppeID AND UG.UserID = UGEX.UserId AND UG.[BerechtigungsbereichID] = 2)


IF NOT EXISTS(SELECT * FROM UserGruppe WHERE [BerechtigungsbereichID] = 9)
BEGIN
INSERT INTO [dbo].[UserGruppe]
           ([GruppeID]
           ,[UserID]
           ,[Schreiben]
           ,[LM]
           ,[UM]
           ,[LC]
           ,[UC]
           ,[BerechtigungsbereichID]
           ,[OptionsFlag]
           ,[IsInherited]
           ,[Options])
SELECT GruppeID, UserId, Schreiben, '19000101', 0, '19000101', 0, 9, OptionsFlag, IsInherited, Options FROm UserGruppe WHERE BerechtigungsbereichID = 2
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_AuffTypen_VonZeitDrucken]') )
BEGIN
	UPDATE Aufftypen SET VonzeitDrucken = 1 WHERE VonzeitDrucken IS NULL 
	ALTER TABLE Aufftypen ALTER COLUMN VonzeitDrucken BIT NOT NULL
	ALTER TABLE Aufftypen ADD CONSTRAINT DF_AuffTypen_VonzeitDrucken DEFAULT 0 FOR VonzeitDrucken

	UPDATE Aufftypen SET BiszeitDrucken = 0 WHERE BiszeitDrucken IS NULL 
	ALTER TABLE Aufftypen ALTER COLUMN BiszeitDrucken BIT NOT NULL
	ALTER TABLE Aufftypen ADD CONSTRAINT DF_AuffTypen_BiszeitDrucken DEFAULT 0 FOR BiszeitDrucken

	
	UPDATE Aufftypen SET tsAuffTypBasisID = 0 WHERE tsAuffTypBasisID IN (10,200,380,420,430,480,490,600)
	--Uraufführuing = Premiere
	UPDATE Aufftypen SET tsAuffTypBasisID = 560 WHERE tsAuffTypBasisID = 561
	--Keine Bauproben waren standard
	UPDATE Aufftypen SET tsAuffTypBasisID = 0 WHERE tsAuffTypBasisID = 100 AND KatNr <> 1 
END
GO

--2012-11-26 TH: Neue Spalte für XML-Settings in PersStatus
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Settings' and o.id = OBJECT_ID(N'[dbo].[Status]'))
ALTER TABLE dbo.[Status] ADD Settings VARCHAR(600) NULL

--2012-11-27 TH: Neue Spalte für die Einstellung, wie gezählt wern soll in PersStatus
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CountingType' and o.id = OBJECT_ID(N'[dbo].[Status]'))
ALTER TABLE dbo.[Status] ADD CountingType INT NOT NULL CONSTRAINT DF_Status_CountingType DEFAULT 0

--2012-11-28 TH: Lohndaten um eine Spalte für Einstellungen erweitert
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Settings' and o.id = OBJECT_ID(N'[dbo].[WageType]'))
ALTER TABLE dbo.[WageType] ADD Settings VARCHAR(5000) NULL

--2012-11-28 TH: VertragsVorlagen um eine Spalte erweitert, die angibt, ob der Vertrag für das Budget gewertet werden soll
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'InBudget' and o.id = OBJECT_ID(N'[dbo].[VertragsVorlagen]'))
ALTER TABLE dbo.[VertragsVorlagen] ADD InBudget BIT NOT NULL CONSTRAINT DF_VertragsVorlagen_InBudget DEFAULT 0

--2012-11-28 TH: SalaryLevel um eine Spalte erweitert, die angibt, welche Stufe diese Beschreibt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Level' and o.id = OBJECT_ID(N'[dbo].[SalaryLevel]'))
ALTER TABLE dbo.[SalaryLevel] ADD [Level] INT NULL

--2012-11-28 TH: SalaryLevel um eine Spalte erweitert, die angibt, welche Stufe diese Beschreibt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'SalaryLevelId' and o.id = OBJECT_ID(N'[dbo].[AB]'))
	BEGIN
ALTER TABLE dbo.[AB] ADD [SalaryLevelId] INT NULL
CONSTRAINT [FK_AB_SalaryLevel] FOREIGN KEY([SalaryLevelId]) REFERENCES dbo.[SalaryLevel] ([SalaryLevelId])
END
GO

--2012-11-29 TH: Neue Tabelle für das Verwalten von Budgets für Spielzeit/Kostenträger/Kostenstelle
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[Budgets]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[Budgets](
	[BudgetId] INT IDENTITY(1,1) NOT NULL,
	[SeasonId] INT NOT NULL,
	[CostUnitId] INT NOT NULL,
	[CostCenterId] INT NOT NULL,
	[BudgetValue] FLOAT NOT NULL CONSTRAINT DF_Budgets_BudgetsValue DEFAULT 0,
	[Note] VARCHAR(200) NULL,
	[LM] [datetime] NOT NULL,
	[UM] [int] NOT NULL,
	[LC] [datetime] NOT NULL,
	[UC] [int] NOT NULL,
	CONSTRAINT [PK_Budgets] PRIMARY KEY CLUSTERED ([BudgetId] ASC) ON [PRIMARY],
	CONSTRAINT [FK_Budgets_Seasons] FOREIGN KEY([SeasonId]) REFERENCES dbo.[SpielzeitTabelle] ([SpzNr]) ON DELETE CASCADE,
	CONSTRAINT [FK_Budgets_CostUnit] FOREIGN KEY([CostUnitId]) REFERENCES dbo.[CostUnit] ([CostUnitId]) ON DELETE CASCADE,
	CONSTRAINT [FK_Budgets_CostCenter] FOREIGN KEY([CostCenterId]) REFERENCES dbo.[CostCenter] ([CostCenterId]) ON DELETE CASCADE
	) ON [PRIMARY]
END
GO
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'BudgetWrite')
BEGIN
	EXEC sp_addrole @rolename = N'BudgetWrite'
END

REVOKE SELECT ON Budgets TO Public
GRANT INSERT ON Budgets TO BudgetWrite
GRANT DELETE ON Budgets TO BudgetWrite
GRANT UPDATE ON Budgets TO BudgetWrite

GO

--2012-11-30 SH
--neue Spalte für DienstplanRegeln
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PolicySettings' and o.id = OBJECT_ID(N'dbo.PersoParameter'))
BEGIN
	ALTER TABLE dbo.PersoParameter ADD PolicySettings TEXT NULL
END
GO
--TK 2012-12-09 
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CostCenterId' and o.id = OBJECT_ID(N'dbo.Vertrag'))
BEGIN
ALTER TABLE dbo.Vertrag ADD CostCenterId INT NULL 
CONSTRAINT [FK_Contract_CostCenter] FOREIGN KEY(CostCenterId) REFERENCES dbo.CostCenter (CostCenterId)
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Code' and o.id = OBJECT_ID(N'dbo.SchoolHolidays'))
BEGIN
	ALTER TABLE dbo.SchoolHolidays ADD Code VARCHAR(2) NULL
END

GO
--TK 2012-12
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.Computer') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].Computer(
	ComputerId INT IDENTITY(1,1) NOT NULL,
	Name VARCHAR(64) NOT NULL,
	theasoftVersion VARCHAR(15) NOT NULL,
	OSVersion VARCHAR(24) NOT NULL,
	IsAutoUpdateEnabled BIT NOT NULL  CONSTRAINT DF_Computers_IsAutoUpdateEnabled DEFAULT 0,
	AutoUpdatePath VARCHAR(255) NULL,
	[LM] [datetime] NOT NULL,
	[UM] [int] NOT NULL,
	[LC] [datetime] NOT NULL,
	[UC] [int] NOT NULL,
	CONSTRAINT [PK_Computer] PRIMARY KEY CLUSTERED (ComputerId ASC) ON [PRIMARY]
	) ON [PRIMARY]
END
GO
GRANT SELECT ON Computer TO Public
GO
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'dbo.[Computer]')  AND name = 'IX_Computer_Name')
CREATE UNIQUE NONCLUSTERED INDEX IX_Computer_Name ON dbo.Computer (Name)  ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'LastLoginComputerId' and o.id = OBJECT_ID(N'dbo.Userpw'))
BEGIN
	ALTER TABLE dbo.Userpw ADD LastLoginComputerId INT NULL
	ALTER TABLE dbo.Userpw ADD TreePath VARCHAR(200) NULL
	ALTER TABLE dbo.Userpw ADD Note VARCHAR(500) NULL
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_User_Computer') AND type = 'F')
ALTER TABLE dbo.UserPw   WITH CHECK ADD  CONSTRAINT FK_User_Computer FOREIGN KEY(LastLoginComputerId)
REFERENCES dbo.Computer (ComputerId)
GO
ALTER TABLE dbo.UserPw CHECK CONSTRAINT FK_User_Computer
GO
IF  EXISTS (SELECT * FROM sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.LogLogin')) DROP PROCEDURE [dbo].LogLogin
GO
CREATE PROCEDURE dbo.LogLogin 
	@ComputerName VARCHAR(64),
	@OSVersion VARCHAR(24),
	@TheasoftVersion VARCHAR(24),
	@IsAutoUpdateEnabled BIT,
	@AutoUpdatePath VARCHAR(255)
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, LM = GetDate(), UM = @UserId WHERE  ComputerId = @ComputerId
		END
	ELSE
		BEGIN
			INSERT INTO Computer (Name, theasoftVersion,  OSVersion, LC, UC, LM, UM) 
				VALUES (@ComputerName, @TheasoftVersion, @OSVersion, GetDate(), @UserId, GetDate(), @UserId) 

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

		UPDATE UserPW Set LastLoginDate = GetDate(), LastLoginComputerId = @ComputerId WHERE  UserID  = @UserId
END

GO
GRANT EXECUTE ON LogLogin TO Public
GO


--2012-12-11 TH
--Neue Tabelle für die Abfolge von Vertragsstatus
--Pers, da es sich um einen Personen-Vertrag handelt.
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[PersContractValidationType]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PersContractValidationType](
	[PersContractValidationTypeId] INT IDENTITY(1,1) NOT NULL,
	[Name] VARCHAR(100) NULL,
	[LM] [datetime] NOT NULL,
	[UM] [int] NOT NULL,
	[LC] [datetime] NOT NULL,
	[UC] [int] NOT NULL,
	CONSTRAINT [PK_PersContractValidationType] PRIMARY KEY CLUSTERED ([PersContractValidationTypeId] ASC) ON [PRIMARY],
) ON [PRIMARY]
END
GRANT SELECT ON [PersContractValidationType] TO Public
GRANT UPDATE ON [PersContractValidationType] TO PersoContractWrite
GRANT INSERT ON [PersContractValidationType] TO PersoContractWrite
GRANT DELETE ON [PersContractValidationType] TO PersoContractWrite
GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[PersContractValidationStatus]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[PersContractValidationStatus](
	[PersContractValidationStatusId] INT IDENTITY(1,1) NOT NULL,
	[PersContractValidationTypeId] INT NOT NULL,
	[Sort] INT NOT NULL CONSTRAINT DF_PersContractValidationStatus_Sort DEFAULT 0,
	[PersContractStatusId] INT NOT NULL,
	[UserGroupId] INT NOT NULL,
	[MailingListId] INT NULL,
	[CanChangeContractData] BIT NOT NULL CONSTRAINT DF_PersContractValidationStatus_CanChangeContractData DEFAULT 0,
	[LM] [datetime] NOT NULL,
	[UM] [int] NOT NULL,
	[LC] [datetime] NOT NULL,
	[UC] [int] NOT NULL,
	CONSTRAINT [PK_PersContractValidationStatus] PRIMARY KEY CLUSTERED ([PersContractValidationStatusId] ASC) ON [PRIMARY],
	CONSTRAINT [FK_PersContractValidationStatus_PersContractValidationType] FOREIGN KEY([PersContractValidationTypeId]) REFERENCES dbo.[PersContractValidationType] ([PersContractValidationTypeId]) ON DELETE CASCADE,
	CONSTRAINT [FK_PersContractValidationStatus_PersContractStatus] FOREIGN KEY([PersContractStatusId]) REFERENCES dbo.[VertragsStatus] ([VertragsStatusNr]) ON DELETE CASCADE,
	CONSTRAINT [FK_PersContractValidationStatus_UserGroup] FOREIGN KEY([UserGroupId]) REFERENCES dbo.[UserPw] ([UserID]),
	CONSTRAINT [FK_PersContractValidationStatus_MailingList] FOREIGN KEY([MailingListId]) REFERENCES dbo.[Verteiler] ([VerteilerID]),
) ON [PRIMARY]
	CREATE UNIQUE NONCLUSTERED INDEX IX_PersContractValidationStatus_PersContractValidationTypeId_Sort ON dbo.PersContractValidationStatus
	([PersContractValidationTypeId], [Sort]) ON [PRIMARY]
END
GRANT SELECT ON [PersContractValidationStatus] TO Public
GRANT UPDATE ON [PersContractValidationStatus] TO PersoContractWrite
GRANT INSERT ON [PersContractValidationStatus] TO PersoContractWrite
GRANT DELETE ON [PersContractValidationStatus] TO PersoContractWrite

GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PersContractValidationTypeId' and o.id = OBJECT_ID(N'dbo.VertragsVorlagen'))
BEGIN
	ALTER TABLE dbo.VertragsVorlagen ADD PersContractValidationTypeId INT NULL
	CONSTRAINT [FK_VertragsVorlagen_PersContractValidationType] FOREIGN KEY([PersContractValidationTypeId]) REFERENCES dbo.[PersContractValidationType] ([PersContractValidationTypeId])
END
GO
IF (SELECT Major FROM NVData WHERE ByModulScript = 1) = 1 AND (SELECT Minor FROM NVData WHERE ByModulScript = 1) <303
BEGIN
INSERT INTO [dbo].[UserGruppe]
           ([GruppeID]
           ,[UserID]
           ,[Schreiben]
           ,[LM]
           ,[UM]
           ,[LC]
           ,[UC]
           ,[BerechtigungsbereichID]
           ,[OptionsFlag]
           ,[IsInherited]
           ,[Options])
SELECT DISTINCT GNEW.GruppeID, UGEX.UserID, 1, '19000101', 0, '19000101', 0, 2, 0, 0,NULL
FROM UserGruppe AS UGEX
INNER JOIN Gruppe AS GEX ON GEX.GruppeID = UGEX.GruppeID
LEFT JOIN Gruppe AS GNEW ON GNEW.Modul = 1
WHERE UGEX.[BerechtigungsbereichID] = 2 AND Schreiben = 1 AND GEX.Modul <> 1 AND NOT EXISTS(
	SELECT * 
	FROM UserGruppe AS UG 
	WHERE UG.GruppeID = GNEW.GruppeID AND UG.UserID = UGEX.UserId AND UG.[BerechtigungsbereichID] = 2)
END
GO
--IF (SELECT Major FROM NVData WHERE ByModulScript = 1) = 1 AND (SELECT Minor FROM NVData WHERE ByModulScript = 1) <303
--BEGIN
----Berechtigungen auf Aufführungen anpassen
--UPDATE UserGruppe SET Schreiben = 1 
--WHERE GruppeID IN (
--	SELECT GruppeID 
--	FROM Gruppe 
--	WHERE Modul = 1) 
--AND UserID IN (
--	SELECT DISTINCT(UG.UserID) 
--	FROM UserGruppe AS UG 
--	INNER JOIN Gruppe AS G ON G.GruppeID = UG.GruppeID
--	WHERE UG.Schreiben = 1 AND G.Modul <>1)
--END
GO


--TK 2012-12-09 
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CostCenterId' and o.id = OBJECT_ID(N'dbo.Vertrag'))
BEGIN
ALTER TABLE dbo.Vertrag ADD CostCenterId INT NULL 
CONSTRAINT [FK_Contract_CostCenter] FOREIGN KEY(CostCenterId) REFERENCES dbo.CostCenter (CostCenterId)
END
GO

--SH 2013-01-03
--Zulagen Standardwerte real -> float
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'StdWertVst' AND o.id = OBJECT_ID(N'[dbo].Zulagen') AND c.xtype = 59)
BEGIN
	ALTER TABLE Zulagen ALTER COLUMN StdWertVst FLOAT NULL
	ALTER TABLE Zulagen ALTER COLUMN StdWertPro FLOAT NULL
END
GO

--2013-01-11 SH 
--ändern des pfades für rollenname in adressplanspalten
UPDATE AdressAusgabe SET ContentPath = 'role.name' WHERE ContentPath = 'basiccast.role'
GO


--SH 2013-01-03
--contractdates -> start wird nullable
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Start' AND o.id = OBJECT_ID(N'[dbo].ContractDates') AND c.isnullable = 0)
BEGIN
	ALTER TABLE ContractDates ALTER COLUMN Start DATETIME NULL
END
GO
-- TK 2013-01-14
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'TemplateId' and o.id = OBJECT_ID(N'dbo.Vertrag'))
BEGIN
	ALTER TABLE dbo.Vertrag ADD TemplateId INT NULL 
	CONSTRAINT [FK_Contract_Template] FOREIGN KEY(TemplateId) REFERENCES dbo.Vorlagen (VorlagenID)
	ALTER TABLE dbo.Vertrag ADD IsBudgetRelevant BIT NOT NULL  CONSTRAINT DF_ContractIsBudgetRelevant DEFAULT 0
END

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'GruppeBezKurz' AND o.id = OBJECT_ID(N'[dbo].FahrplanGruppen') AND c.prec < 20)
BEGIN
	ALTER TABLE FahrplanGruppen ALTER COLUMN GruppeBezKurz VARCHAR(20)
END
GO
-- TK 2013-01-17
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IsGlobalSetting' and o.id = OBJECT_ID(N'dbo.Settings'))
BEGIN
	ALTER TABLE dbo.Settings ADD IsGlobalSetting BIT NOT NULL CONSTRAINT DF_SettingsIsGlobalSetting DEFAULT 0
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'ShowBonusIn' and o.id = OBJECT_ID(N'dbo.ZulagenDienstplanArt'))
BEGIN
       ALTER TABLE dbo.ZulagenDienstplanArt ADD ShowBonusIn INT NOT NULL CONSTRAINT DF_ZulagenDienstplanArtShowBonusIn DEFAULT 1 --Dienstplan
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'LastDatabaseUpdateDate' and o.id = OBJECT_ID(N'dbo.NvData'))
BEGIN
       ALTER TABLE dbo.NvData ADD LastDatabaseUpdateDate DATETIME NOT NULL CONSTRAINT DF_NvDataLastDatabaseUpdateDate  DEFAULT GetDate()
END

GO

-- 2013-01-21 SH
-- verbindungstabelle zw. vertragsart und vorlagen für eine n:m beziehung
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ContractTypes_Templates]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].ContractTypes_Templates (
		ContractTypTemplateId INT IDENTITY(1,1) NOT NULL,
		ContractTypeId INT NOT NULL,
		TemplateId INT NOT NULL,
		[Sort] INT NOT NULL CONSTRAINT DF_ContractTypes_Templates_Sort DEFAULT 0,
		[LC] DATETIME NOT NULL,
		[UC] INT NOT NULL,
		[LM] DATETIME NOT NULL,
		[UM] INT NOT NULL,
		CONSTRAINT PK_ContractTypes_Templates PRIMARY KEY CLUSTERED (ContractTypTemplateId ASC) ON [PRIMARY],
		CONSTRAINT FK_ContractTypes_Templates_ContractTypes FOREIGN KEY (ContractTypeId) REFERENCES dbo.VertragsVorlagen (VorlagenID) ON DELETE CASCADE,
		CONSTRAINT FK_ContractTypes_Templates_Templates FOREIGN KEY (TemplateId) REFERENCES dbo.Vorlagen (VorlagenID) ON DELETE CASCADE,
		CONSTRAINT UQ_ContractTypes_Templates_ContractTypeId_TemplateId UNIQUE (ContractTypeId, TemplateId)
	) ON [PRIMARY]

	INSERT INTO ContractTypes_Templates (ContractTypeId,TemplateId,Sort,LC,UC,LM,UM)
	SELECT vv.VorlagenID, vv.TemplateId, 0, GETDATE(), 0, GETDATE(), 0 FROM VertragsVorlagen vv WHERE NOT vv.TemplateId IS NULL
END
GO

GRANT SELECT ON [dbo].ContractTypes_Templates TO Public
GRANT DELETE ON [dbo].ContractTypes_Templates TO [PersoContractWrite], [PersoAdmin], [Honorar-Daten ändern]
GRANT INSERT ON [dbo].ContractTypes_Templates TO [PersoContractWrite], [PersoAdmin], [Honorar-Daten ändern]
GRANT UPDATE ON [dbo].ContractTypes_Templates TO [PersoContractWrite], [PersoAdmin], [Honorar-Daten ändern]
GO


IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'HourlyRate' AND o.id = OBJECT_ID(N'[dbo].SalaryLevelData') AND c.xType = 62) 
BEGIN
	EXEC DeleteConstraint 'SalaryLevelData', 'HourlyRate' 
	ALTER TABLE dbo.SalaryLevelData ADD  HourlyRateTemp float
	EXEC ('UPDATE dbo.SalaryLevelData  SET  HourlyRateTemp = Convert(float, Convert(VarChar(50), HourlyRate ))')
	ALTER TABLE dbo.SalaryLevelData ALTER COLUMN HourlyRate float NOT NULL
	ALTER TABLE SalaryLevelData ADD CONSTRAINT DF_SalaryLevelData_HourlyRate DEFAULT 0 FOR HourlyRate 
	EXEC ('UPDATE dbo.SalaryLevelData  SET  HourlyRate = HourlyRateTemp')
	EXEC ('ALTER TABLE dbo.SalaryLevelData  DROP COLUMN HourlyRateTemp')
END

UPDATE AufführgTabelle SET UhrBeg = '00:00' WHERE UhrBeg IS NULL
UPDATE AufführgTabelle SET UhrEnde = '00:00' WHERE UhrEnde IS NULL
GO
DropIndexByTable 'AufführgTabelle'

ALTER TABLE AufführgTabelle ALTER COLUMN Datum DATETIME NOT NULL 
ALTER TABLE AufführgTabelle ALTER COLUMN UhrBeg DATETIME NOT NULL 
ALTER TABLE AufführgTabelle ALTER COLUMN UhrEnde DATETIME NOT NULL 
ALTER TABLE AufführgTabelle ALTER COLUMN ZrNr INT NOT NULL 
ALTER TABLE AufführgTabelle ALTER COLUMN Art INT NOT NULL 
ALTER TABLE AufführgTabelle ALTER COLUMN Snr INT NOT NULL 
CREATE CLUSTERED  INDEX IX_Activities_Date ON dbo.AufführgTabelle (Datum) ON [PRIMARY]		
CREATE INDEX IX_Activities_ProductionId ON dbo.AufführgTabelle (Snr) ON [PRIMARY]		
CREATE INDEX IX_Activities_StageId ON dbo.AufführgTabelle (Zrnr) ON [PRIMARY]		
CREATE INDEX IX_Activities_ActivityType ON dbo.AufführgTabelle (Art) ON [PRIMARY]	

GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'Build' and o.id = OBJECT_ID(N'dbo.NVData'))
BEGIN
	ALTER TABLE [dbo].NVData ADD [Build] INT NOT NULL CONSTRAINT [DF_NVData_Build] DEFAULT (0)
END
GO

-- 2013-02-01 TH
--Neue Spalte im Zyklus für die Soll arbeitszeit
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'Debit' and o.id = OBJECT_ID(N'dbo.ZyklusWochen'))
BEGIN
	ALTER TABLE dbo.ZyklusWochen ADD Debit INT NULL
	ALTER TABLE dbo.VertragPerso ADD UseWorkTimeModelDebit BIT NOT NULL CONSTRAINT DF_VertragPerso_UseWorkTimeModelDebit DEFAULT (0)
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'ExternalId' and o.id = OBJECT_ID(N'dbo.AB'))
BEGIN
	ALTER TABLE dbo.AB ADD ExternalId VARCHAR(100) NULL
END
GO
--2013-02-15 Planrelationen erstellen
DELETE FROM PlanSpalte WHERE PlanId NOT IN (SELECT PlanId FROM [Plan])
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Plan_PlanColumn') AND type = 'F')
	ALTER TABLE dbo.[PlanSpalte]  WITH CHECK ADD  CONSTRAINT FK_Plan_PlanColumn FOREIGN KEY(PlanID)
	REFERENCES dbo.[Plan] (PlanID)  ON DELETE CASCADE
GO
ALTER TABLE dbo.PlanSpalte CHECK CONSTRAINT FK_Plan_PlanColumn

DELETE FROM PlanSort WHERE SpalteID NOT IN (SELECT SpalteID FROM [PlanSpalte])
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PlanColumn_PlanColumnField') AND type = 'F')
	ALTER TABLE dbo.PlanSort  WITH CHECK ADD  CONSTRAINT FK_PlanColumn_PlanColumnField FOREIGN KEY(SpalteID)
	REFERENCES dbo.[PlanSpalte] (SpalteID)  ON DELETE CASCADE
GO
ALTER TABLE dbo.PlanSort CHECK CONSTRAINT FK_PlanColumn_PlanColumnField
GO
DELETE FROM PlanZR WHERE SpalteID NOT IN (SELECT SpalteID FROM [PlanSpalte])
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_PlanColumn_PlanColumnStage') AND type = 'F')
	ALTER TABLE dbo.PlanZR  WITH CHECK ADD  CONSTRAINT FK_PlanColumn_PlanColumnStage FOREIGN KEY(SpalteID)
	REFERENCES dbo.[PlanSpalte] (SpalteID)  ON DELETE CASCADE
GO
ALTER TABLE dbo.PlanZR CHECK CONSTRAINT FK_PlanColumn_PlanColumnStage
UPDATE RingBez SET HauptAbo = NULL  WHERE HauptAbo NOT IN (SELECT zuAbo From RingBez)
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Subscription_Subscription') AND type = 'F')
	ALTER TABLE dbo.RingBez  WITH CHECK ADD  CONSTRAINT FK_Subscription_Subscription FOREIGN KEY(HauptAbo)
	REFERENCES dbo.RingBez (ZuAbo)
GO
ALTER TABLE dbo.RingBez CHECK CONSTRAINT FK_Subscription_Subscription

GO

-- 2014-04-05 sh
-- Umstellung des tägl. Sockelbetrages von real auf float
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'DailyRate' AND o.id = OBJECT_ID(N'[dbo].SalaryLevelData') AND c.xType = 62) 
BEGIN
	EXEC DeleteConstraint 'SalaryLevelData', 'DailyRate' 
	ALTER TABLE dbo.SalaryLevelData ADD  DailyRateTemp float
	EXEC ('UPDATE dbo.SalaryLevelData  SET  DailyRateTemp = Convert(float, Convert(VarChar(50), DailyRate ))')
	ALTER TABLE dbo.SalaryLevelData ALTER COLUMN DailyRate float NOT NULL
	ALTER TABLE SalaryLevelData ADD CONSTRAINT DF_SalaryLevelData_DailyRate DEFAULT 0 FOR DailyRate 
	EXEC ('UPDATE dbo.SalaryLevelData  SET  DailyRate = DailyRateTemp')
	EXEC ('ALTER TABLE dbo.SalaryLevelData  DROP COLUMN DailyRateTemp')
END
GO


--2013-02-18 SH
-- Tourneen wird erweitert um besitzerspalte (standard ist dispo) und währungsspalte
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'OwnerId' and o.id = OBJECT_ID(N'dbo.Tours'))
BEGIN
	--währungsspalte anlegen
	ALTER TABLE dbo.Tours ADD PaymentCurrencyId INT NULL
	ALTER TABLE Tours WITH CHECK ADD CONSTRAINT FK_Tours_Currency FOREIGN KEY(PaymentCurrencyId) REFERENCES Currency (CurrencyId)
	--ownerid spalte anlegen mit standardwert 1 füllen
	ALTER TABLE dbo.Tours ADD OwnerId INT NULL
	EXEC('UPDATE Tours SET OwnerId = 1')
	ALTER TABLE Tours ALTER COLUMN OwnerId INT NOT NULL
	ALTER TABLE Tours WITH CHECK ADD CONSTRAINT FK_Tours_Gruppe FOREIGN KEY(OwnerId) REFERENCES Gruppe (GruppeId)
END
GO

--rolle canwritetours umwandeln in berechtiungen
IF EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'CanWriteTours' AND issqlrole = 1)
BEGIN
	INSERT INTO [dbo].[UserGruppe] (
		[GruppeID], [UserID], [Schreiben], [LM], [UM], [LC], [UC], [BerechtigungsbereichID], [OptionsFlag]
	)
	SELECT 1, up.UserID, 1, GETDATE(), 0, GETDATE(), 0, 10, CASE WHEN u2.name IS NULL THEN 0 ELSE 1 END FROM UserPw up 
	INNER JOIN dbo.sysusers u ON u.[name] = up.UserName AND u.uid in (
		select memberuid from dbo.sysmembers
		where groupuid in (
			select uid FROM dbo.sysusers where [name] = 'CanWriteTours' AND issqlrole = 1
		)
	)
	LEFT JOIN dbo.sysusers u2 ON u2.[name] = up.UserName AND u2.uid in (
		select memberuid from dbo.sysmembers
		where groupuid in (
			select uid FROM dbo.sysusers where [name] = 'CanValidateTours' AND issqlrole = 1
		)
	)
	EXEC DropRoleWithDropRoleMember 'CanWriteTours'
	EXEC DropRoleWithDropRoleMember 'CanValidateTours'
END
-- View zum Abrufen der Tourneen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbTours'))
BEGIN
DROP VIEW [dbo].AbTours
END
go
CREATE VIEW [dbo].AbTours
AS 
SELECT  t.*  FROM  Tours AS t WHERE t.OwnerId IN (
	SELECT UserGruppe.GruppeID 
	FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
	WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 10
)
WITH CHECK OPTION
GO
GRANT SELECT ON AbTours TO public
GO
-- View zum Anlegen der Tourneen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbTours_Update'))
BEGIN
DROP VIEW [dbo].AbTours_Update
END
go
CREATE VIEW [dbo].AbTours_Update
AS 
SELECT  t.*  FROM  Tours AS t WHERE t.OwnerId IN (
	SELECT UserGruppe.GruppeID 
	FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
	WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 10 AND UserGruppe.Schreiben = 1
)
WITH CHECK OPTION
GO
GRANT SELECT ON AbTours_Update TO public
GRANT DELETE ON AbTours_Update TO public
GRANT UPDATE ON AbTours_Update TO public
GRANT INSERT ON AbTours_Update TO public
GO
-- View zum Abrufen der Tourneezulagen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbToursBonuses'))
BEGIN
DROP VIEW [dbo].AbToursBonuses
END
go
CREATE VIEW [dbo].AbToursBonuses
AS 
SELECT  tb.*  FROM  Tours_Bonuses AS tb WHERE tb.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN Gruppe g ON t.OwnerId = g.GruppeID
	INNER JOIN UserGruppe AS ug ON g.GruppeID = ug.GruppeID AND ug.BerechtigungsbereichID = 10
	INNER JOIN UserPW AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER 
)
WITH CHECK OPTION
GO
GRANT SELECT ON AbToursBonuses TO public
GO
-- View zum Anlegen der Tourneezulagen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbToursBonuses_Update'))
BEGIN
DROP VIEW [dbo].AbToursBonuses_Update
END
go
CREATE VIEW [dbo].AbToursBonuses_Update
AS 
SELECT  tb.*  FROM  Tours_Bonuses AS tb WHERE tb.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN Gruppe g ON t.OwnerId = g.GruppeID
	INNER JOIN UserGruppe AS ug ON g.GruppeID = ug.GruppeID AND ug.BerechtigungsbereichID = 10
	INNER JOIN UserPW AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER AND ug.Schreiben = 1
)
WITH CHECK OPTION
GO
GRANT SELECT ON AbToursBonuses_Update TO public
GRANT DELETE ON AbToursBonuses_Update TO public
GRANT UPDATE ON AbToursBonuses_Update TO public
GRANT INSERT ON AbToursBonuses_Update TO public
GO
-- View zum Abrufen der Tourneeverträge
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbToursContracts'))
BEGIN
DROP VIEW [dbo].AbToursContracts
END
go
CREATE VIEW [dbo].AbToursContracts
AS 
SELECT  tc.* FROM  Tours_Contracts AS tc WHERE tc.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN Gruppe g ON t.OwnerId = g.GruppeID
	INNER JOIN UserGruppe AS ug ON g.GruppeID = ug.GruppeID AND ug.BerechtigungsbereichID = 10
	INNER JOIN UserPW AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER 
)
WITH CHECK OPTION
GO
GRANT SELECT ON AbToursContracts TO public
GO
-- View zum Anlegen der Tourneeverträge
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbToursContracts_Update'))
BEGIN
DROP VIEW [dbo].AbToursContracts_Update
END
go
CREATE VIEW [dbo].AbToursContracts_Update
AS 
SELECT  tc.* FROM  Tours_Contracts AS tc WHERE tc.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN Gruppe g ON t.OwnerId = g.GruppeID
	INNER JOIN UserGruppe AS ug ON g.GruppeID = ug.GruppeID AND ug.BerechtigungsbereichID = 10
	INNER JOIN UserPW AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER AND ug.Schreiben = 1
)
WITH CHECK OPTION
GO
GRANT SELECT ON AbToursContracts_Update TO public
GRANT DELETE ON AbToursContracts_Update TO public
GRANT UPDATE ON AbToursContracts_Update TO public
GRANT INSERT ON AbToursContracts_Update TO public
GO
-- View zum Abrufen der Tourneekosten
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbToursCosts'))
BEGIN
DROP VIEW [dbo].AbToursCosts
END
go
CREATE VIEW [dbo].AbToursCosts
AS 
SELECT  tc.* FROM  Tours_Costs AS tc WHERE tc.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN Gruppe g ON t.OwnerId = g.GruppeID
	INNER JOIN UserGruppe AS ug ON g.GruppeID = ug.GruppeID AND ug.BerechtigungsbereichID = 10
	INNER JOIN UserPW AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER 
)
WITH CHECK OPTION
GO
GRANT SELECT ON AbToursCosts TO public
GO
-- View zum Anlegen der Tourneekosten
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbToursConsts_Update'))
BEGIN
	DROP VIEW [dbo].AbToursConsts_Update
END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbToursCosts_Update'))
BEGIN
	DROP VIEW [dbo].AbToursCosts_Update
END
GO
CREATE VIEW [dbo].AbToursCosts_Update
AS 
SELECT  tc.* FROM  Tours_Costs AS tc WHERE tc.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN Gruppe g ON t.OwnerId = g.GruppeID
	INNER JOIN UserGruppe AS ug ON g.GruppeID = ug.GruppeID AND ug.BerechtigungsbereichID = 10
	INNER JOIN UserPW AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER AND ug.Schreiben = 1
)
WITH CHECK OPTION
GO
GRANT SELECT ON AbToursCosts_Update TO public
GRANT DELETE ON AbToursCosts_Update TO public
GRANT UPDATE ON AbToursCosts_Update TO public
GRANT INSERT ON AbToursCosts_Update TO public
GO
--tk 2013-02-25
UPDATE Aufführgdetails SET TourId = NULL WHERE TourId NOT IN (SELECT Auffnr FROM AufführgTabelle)
DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
IF (@sql_server_version > 8)  BEGIN
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Tours_ActivityDetails') AND type = 'F')
		exec('ALTER TABLE dbo.AufführgDetails  WITH CHECK ADD CONSTRAINT FK_Tours_ActivityDetails FOREIGN KEY(TourId)
		REFERENCES dbo.Tours (TourId) ON DELETE SET NULL')
END

GO

EXEC DropRoleWithDropRoleMember 'SpielplanTeileÄndern'
--tk 2013-03-05
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'DebitServicesCount' and o.id = OBJECT_ID(N'dbo.VertragsVorlagen'))
BEGIN
	ALTER TABLE dbo.VertragsVorlagen ADD DebitServicesCount FLOAT NOT NULL CONSTRAINT [DF_ContractType_DebitServicesCount] DEFAULT (0) 
END
--tk 2013-03-15
GRANT SELECT ON dbo.Serienbrief TO [Public]
GRANT DELETE ON dbo.Serienbrief TO [Public]
GRANT INSERT ON dbo.Serienbrief TO [Public]
GRANT UPDATE ON dbo.Serienbrief TO [Public]

GRANT SELECT ON dbo.AbPersZusatzDaten_Update TO [Public]
GRANT DELETE ON dbo.AbPersZusatzDaten_Update TO [Public]
GRANT INSERT ON dbo.AbPersZusatzDaten_Update TO [Public]
GRANT UPDATE ON dbo.AbPersZusatzDaten_Update TO [Public]
Go
EXEC DropRoleWithDropRoleMember 'CashCommandWrite'
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCashCommandPos_Cast_Update]'))
BEGIN
	DROP VIEW [dbo].AbCashCommandPos_Cast_Update
END
GO
DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
DECLARE @SQL as varchar(4000) 
DECLARE @CreateViewStatement VARCHAR(5000)
IF(@sql_server_version > 8)
BEGIN
SET  @CreateViewStatement  = '

CREATE VIEW [dbo].AbCashCommandPos_Cast_Update
AS 
SELECT  ccpc.*  FROM  CashCommandPos_Cast  AS ccpc WHERE ccpc.CashCommandPosId IN
	   (SELECT CashCommandPos.CashCommandPosId
		FROM CashCommand AS cc INNER JOIN UserGruppe ON cc.ModulGroupId = UserGruppe.GruppeID 
			INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
			INNER JOIN CashCommandPos ON cc.CashCommandId = CashCommandPos.CashCommandId 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 7)
WITH CHECK OPTION
'
END
ELSE
BEGIN
SET  @CreateViewStatement  = '
CREATE VIEW [dbo].AbCashCommandPos_Cast_Update
AS 
SELECT  ccpc.*  FROM  CashCommandPos_Cast  AS ccpc WHERE ccpc.CashCommandPosId IN
	   (SELECT CashCommandPos.CashCommandPosId
		FROM CashCommand AS cc INNER JOIN UserGruppe ON cc.ModulGroupId = UserGruppe.GruppeID 
			INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
			INNER JOIN CashCommandPos ON cc.CashCommandId = CashCommandPos.CashCommandId 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 7)
'
END
EXEC(@CreateViewStatement)
GO
GRANT SELECT ON dbo.CashCommandPos_Cast TO Public
GRANT SELECT ON dbo.AbCashCommandPos_Cast_Update TO Public
GRANT DELETE ON dbo.AbCashCommandPos_Cast_Update TO Public
GRANT INSERT ON dbo.AbCashCommandPos_Cast_Update TO Public
GRANT UPDATE ON dbo.AbCashCommandPos_Cast_Update TO Public
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCashCommandPos_ContractDate_Update]'))
BEGIN
	DROP VIEW [dbo].AbCashCommandPos_ContractDate_Update
END
GO
CREATE VIEW [dbo].AbCashCommandPos_ContractDate_Update
AS 
SELECT  ccpc.*  FROM  CashCommandPos_ContractDate  AS ccpc WHERE ccpc.CashCommandPosId IN
	   (SELECT CashCommandPos.CashCommandPosId
		FROM CashCommand AS cc INNER JOIN UserGruppe ON cc.ModulGroupId = UserGruppe.GruppeID 
			INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
			INNER JOIN CashCommandPos ON cc.CashCommandId = CashCommandPos.CashCommandId 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 7)
WITH CHECK OPTION
GO

GRANT SELECT ON dbo.AbCashCommandPos_ContractDate_Update TO Public
GRANT DELETE ON dbo.AbCashCommandPos_ContractDate_Update TO Public
GRANT INSERT ON dbo.AbCashCommandPos_ContractDate_Update TO Public
GRANT UPDATE ON dbo.AbCashCommandPos_ContractDate_Update TO Public
GO
GRANT SELECT ON dbo.CashCommandPos_ContractDate TO Public
REVOKE DELETE ON dbo.CashCommandPos_ContractDate TO Public
REVOKE INSERT ON dbo.CashCommandPos_ContractDate TO Public
REVOKE UPDATE ON dbo.CashCommandPos_ContractDate TO Public

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[ProductionParts_Update]'))
BEGIN
	DROP VIEW [dbo].[ProductionParts_Update]
END
GO
CREATE VIEW [dbo].[ProductionParts_Update]
AS 
SELECT *
FROM StückeTeil 
WHERE Snr IN 
		(SELECT SNr 
		 FROM	UserGruppe 	INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
					 INNER JOIN Stücke AS P ON P.ModuleGroupId = UserGruppe.GruppeID
		 WHERE Username = CURRENT_USER  AND BerechtigungsbereichID = 3 ANd Schreiben = 1)	
WITH CHECK OPTION

GO
GRANT SELECT ON dbo.ProductionParts_Update TO Public
GRANT DELETE ON dbo.ProductionParts_Update TO Public
GRANT INSERT ON dbo.ProductionParts_Update TO Public
GRANT UPDATE ON dbo.ProductionParts_Update TO Public
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbVertragPerso_Update]'))
BEGIN
	DROP VIEW [dbo].AbVertragPerso_Update
END
GO
CREATE VIEW [dbo].[AbVertragPerso_Update]
AS 
SELECT * FROM VertragPerso WHERE VertragsNr 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
GRANT SELECT ON dbo.AbVertragPerso_Update TO Public
GRANT DELETE ON dbo.AbVertragPerso_Update TO Public
GRANT INSERT ON dbo.AbVertragPerso_Update TO Public
GRANT UPDATE ON dbo.AbVertragPerso_Update TO Public
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbTimeAccountUsage_Update]'))
BEGIN
	DROP VIEW [dbo].AbTimeAccountUsage_Update
END
GO
CREATE VIEW [dbo].AbTimeAccountUsage_Update
AS 
SELECT * FROM TimeAccountUsage 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 = 1 AND UserGruppe.Schreiben = 1) 
WITH CHECK OPTION
GO
GRANT SELECT ON dbo.AbTimeAccountUsage_Update TO Public
GRANT DELETE ON dbo.AbTimeAccountUsage_Update TO Public
GRANT INSERT ON dbo.AbTimeAccountUsage_Update TO Public
GRANT UPDATE ON dbo.AbTimeAccountUsage_Update TO Public
GO


IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbContract_Qualification_Person_Update]'))
BEGIN
	DROP VIEW [dbo].AbContract_Qualification_Person_Update
END
GO
CREATE VIEW [dbo].AbContract_Qualification_Person_Update
AS 
SELECT * FROM Contract_Qualification_Person 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 = 1 AND UserGruppe.Schreiben = 1) 
WITH CHECK OPTION
GO
GRANT SELECT ON dbo.AbContract_Qualification_Person_Update TO Public
GRANT DELETE ON dbo.AbContract_Qualification_Person_Update TO Public
GRANT INSERT ON dbo.AbContract_Qualification_Person_Update TO Public
GRANT UPDATE ON dbo.AbContract_Qualification_Person_Update TO Public
Go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbContractPartTimePeriods_Update]'))
BEGIN
	DROP VIEW [dbo].AbContractPartTimePeriods_Update
END
GO
CREATE VIEW [dbo].AbContractPartTimePeriods_Update
AS 
SELECT * FROM ContractPartTimePeriods 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 = 1 AND UserGruppe.Schreiben = 1) 
WITH CHECK OPTION
GO
GRANT SELECT ON dbo.AbContractPartTimePeriods_Update TO Public
GRANT DELETE ON dbo.AbContractPartTimePeriods_Update TO Public
GRANT INSERT ON dbo.AbContractPartTimePeriods_Update TO Public
GRANT UPDATE ON dbo.AbContractPartTimePeriods_Update TO Public
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbZeitkontenMonat_Update]'))
BEGIN
	DROP VIEW [dbo].AbZeitkontenMonat_Update
END
GO
CREATE VIEW [dbo].AbZeitkontenMonat_Update
AS 
SELECT * FROM ZeitkontenMonat WHERE VertragsNr 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 = 1 AND UserGruppe.Schreiben = 1) 
WITH CHECK OPTION
GO
GRANT SELECT ON dbo.AbZeitkontenMonat_Update TO Public
GRANT DELETE ON dbo.AbZeitkontenMonat_Update TO Public
GRANT INSERT ON dbo.AbZeitkontenMonat_Update TO Public
GRANT UPDATE ON dbo.AbZeitkontenMonat_Update TO Public
GO
EXEC DropRoleWithDropRoleMember 'PersoWorkContractWrite'
GO

-- 2013-03-27 SH
-- Zuordnungstabelle zw. Kostenstelle und Berechtigungsgruppen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CostCenter_OwnerGroup]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[CostCenter_OwnerGroup](
		[CostCenterOwnerGroupId] int IDENTITY(1,1) NOT NULL,
		[CostCenterId] int NOT NULL,
		[OwnerGroupId] int NOT NULL,
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
	 CONSTRAINT [PK_CostCenterOwnerGroup] PRIMARY KEY CLUSTERED  ([CostCenterOwnerGroupId] ASC) ON [PRIMARY],
	 CONSTRAINT [FK_CostCenterOwnerGroup_CostCenter] FOREIGN KEY([CostCenterId]) REFERENCES [dbo].[CostCenter] (CostCenterId) ON DELETE CASCADE,
	 CONSTRAINT [FK_CostCenterOwnerGroup_OwnerGroup] FOREIGN KEY([OwnerGroupId]) REFERENCES [dbo].Gruppe (GruppeID) ON DELETE CASCADE
	) ON [PRIMARY]
	
	CREATE NONCLUSTERED INDEX [IX_CostCenterOwnerGroup_OwnerGroupId] ON [dbo].[CostCenter_OwnerGroup] (OwnerGroupId)		
END

GRANT SELECT ON [dbo].[CostCenter_OwnerGroup] TO public

GRANT UPDATE ON [dbo].[CostCenter_OwnerGroup] TO CostsWrite
GRANT UPDATE ON [dbo].[CostCenter_OwnerGroup] TO [Stammdaten ändern]

GRANT INSERT ON [dbo].[CostCenter_OwnerGroup] TO CostsWrite
GRANT INSERT ON [dbo].[CostCenter_OwnerGroup] TO [Stammdaten ändern]

GRANT DELETE ON [dbo].[CostCenter_OwnerGroup] TO CostsWrite
GRANT DELETE ON [dbo].[CostCenter_OwnerGroup] TO [Stammdaten ändern]

GO
--2013-04-01 TK
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'IsInactive' and o.id = OBJECT_ID(N'dbo.Preise'))
BEGIN
	ALTER TABLE dbo.Preise ADD IsInactive BIT NOT NULL  CONSTRAINT DF_Preise_IsInactive DEFAULT (0)
END
Go
DELETE FROM PlanZR WHERE zrnr NOT IN (SELECT zrnr FROM zr)
GO
--2013-04-02 TK
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_Stage_PlanColumnStage') AND type = 'F')
	ALTER TABLE dbo.PlanZR  WITH CHECK ADD  CONSTRAINT FK_Stage_PlanColumnStage FOREIGN KEY(zrnr)
	REFERENCES dbo.zr (zrnr)  ON DELETE CASCADE
GO
go
--2013-04-11 TK
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'IsReplacement' and o.id = OBJECT_ID(N'dbo.BesetzungTabelle'))
BEGIN
	ALTER TABLE dbo.BesetzungTabelle ADD IsReplacement BIT NOT NULL  CONSTRAINT DF_Cast_IsReplacement DEFAULT (0)
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'Remarks' and o.id = OBJECT_ID(N'dbo.CashCommandPos'))
BEGIN
	ALTER TABLE dbo.CashCommandPos ADD Remarks VARCHAR(100)
END
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'BudgetItemId' and o.id = OBJECT_ID(N'dbo.Vertrag'))
BEGIN
ALTER TABLE dbo.Vertrag ADD BudgetItemId INT NULL 
CONSTRAINT [FK_Contract_BudgetItem] FOREIGN KEY(BudgetItemId) REFERENCES dbo.BudgetItem (BudgetItemId)
END
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Rolle' AND o.id = OBJECT_ID(N'[dbo].RollenLtg') AND c.prec < 80)
BEGIN
	ALTER TABLE RollenLtg ALTER COLUMN Rolle VARCHAR(80)
END
Go

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'FeeRuleSettings' and o.id = OBJECT_ID(N'dbo.SalaryLevelData'))
BEGIN
	ALTER TABLE dbo.SalaryLevelData ADD FeeRuleSettings TEXT
	INSERT INTO SalaryLevelData (SalaryLevelId,ValidFrom,ValidTo,LM,UM,LC,uc ) SELECT SalaryLevelId,'19000101','30000101',LM,UM,LC,uc FROM SalaryLevel WHERE NOT EXISTS(SELECT * FROM SalaryLevelData WHERE SalaryLevelData.SalaryLevelId = SalaryLevel.SalaryLevelId)	
	Exec ('UPDATE SalaryLevelData SET SalaryLevelData.FeeRuleSettings = SL.FeeRuleSettings FROM SalaryLevel AS SL INNER JOIN SalaryLevelData ON SL.SalaryLevelId = SalaryLevelData.SalaryLevelId')
END
Go
ALTER PROCEDURE [dbo].[AbBuenenProbenNr]
@lSnr int,
@DDatum  Datetime, 
@dVon  Datetime, 
@dspzStart  Datetime, 
@lZrNr As int
As

SELECT Count(*) AS [Anz] FROM AufführgTabelle INNER JOIN AuffTypen ON AufführgTabelle.Art = AuffTypen.AuffTNr  
WHERE 
Snr= @lSnr  and 
[Status] BETWEEN 0 AND 99 AND 
ZrNr= @lZrNr   and
KatNr=1 and
merkmal = 0 and
 ((Datum< @DDatum  and Datum>= @dspzStart ) or (Datum= @DDatum AND  CONVERT(varchar(5), uhrbeg, 8)<= CONVERT(varchar(5), @dvon, 8)))
GO



--2013-04-04 TH:
--Neue StoredProcedure und neue FormelConfiguration
--Spalte für Code vergrößert
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Code' AND o.id = OBJECT_ID(N'[dbo].FormulaConfiguration') AND c.prec < 6)
BEGIN
	ALTER TABLE FormulaConfiguration ALTER COLUMN Code VARCHAR(6)
END
GO
--StoredProcedure

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].SumToFormula'))
BEGIN
	DROP PROCEDURE dbo.SumToFormula 
END
go
 CREATE PROCEDURE [dbo].SumToFormula
	@FormulaName varchar(200), 
	@FormulaConfig TEXT,
	@SumValue INT
AS
BEGIN
	DECLARE @formulaId INT 
	SET @formulaId = -1
	--Temp-Tabelle mit betroffenen AbteilungsIds
	CREATE TABLE #departments( DepId INT)
	INSERT Into #departments SELECT DienstplanArtenID  FROM DienstplanArtenTabelle WHERE SumColVisible & @SumValue = @SumValue
	
	IF EXISTS (SELECT * FROM #departments)
	BEGIN
		--Ermitteln der neuen Id
		SELECT @formulaId = MAX(ISNULL([FormulaConfigurationId],0))+1 FROM [FormulaConfigurations]
	
		--Hinzufügen der Formel incl. Einstellungen
		SET IDENTITY_INSERT [dbo].[FormulaConfigurations] ON;
		INSERT INTO [dbo].[FormulaConfigurations]([FormulaConfigurationId], [Name], [Code], [SerializedParameter], [FormulaId], [Modul], [LC], [UC], [LM], [UM])
		SELECT @formulaId , N'Name', N'Code', @FormulaConfig, @FormulaName, 4, '19000101', 1, '19000101', 1
		SET IDENTITY_INSERT [dbo].[FormulaConfigurations] OFF;
	
		--Zuordnen der Neuen Formel zu den Abteilungen, die die Summe bisher verwendet haben
		INSERT INTO [FormulaConfigurations_Departments] ([FormulaConfigurationId],[DepartmentId],[LC],[UC],[LM],[UM])
           SELECT @formulaId, DepId, '19000101', 1, '19000101', 1 FROM #departments
		--Entfernen des Flags in den Abteilungen
		UPDATE DienstplanArtenTabelle SET SumColVisible = SumColVisible-@sumValue WHERE DienstplanArtenID IN (SELECT DepId FROM  #departments)
	END
	DROP TABLE #departments
	RETURN (@formulaId)
END
GO

--Neue FormelKonfiguration
DECLARE @formulaId INT

EXEC @formulaId = SumToFormula 'FreeDaysInPeriod', N'<?xml version="1.0" encoding="utf-16"?>
<FreeDaysInPeriodParameter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PeriodType>Weeks</PeriodType>
  <PeriodCount>2</PeriodCount>
  <EndIsCurrentWeek>false</EndIsCurrentWeek>
</FreeDaysInPeriodParameter>', 65536

--Lokalisieren der Formel
IF EXISTS(SELECT * FROM FormulaConfigurations WHERE [FormulaConfigurationId] = @formulaId)
BEGIN
	DECLARE @country VARCHAR(20)
	SELECT @country = WertText FROM Settings WHERE Form = 'Adresse' AND Control = 'Country'
	UPDATE [FormulaConfigurations] SET Name = 'Freie Tage der letzten 2 Wochen', Code = 'Frei 2' WHERE FormulaConfigurationId = @formulaId
	IF @country = 'FI'
	BEGIN--Finnisch
		UPDATE [FormulaConfigurations] SET Name = 'Viimeisten 2 viikon vapaapäivät', Code = 'Vp 2vk' WHERE FormulaConfigurationId = @formulaId
	END
	IF @country = 'EN'
	BEGIN--Englisch
		UPDATE [FormulaConfigurations] SET Name = 'Free Days of the last 2 weeks', Code = 'Free 2' WHERE FormulaConfigurationId = @formulaId
	END
	IF @country = 'F' OR @country = 'BE'
	BEGIN--Französisch
		UPDATE [FormulaConfigurations] SET Name = 'Jours libres des 2 dernières semaines', Code = 'Congé2' WHERE FormulaConfigurationId = @formulaId
	END
	IF @country = 'NL'
	BEGIN--Belgien
		UPDATE [FormulaConfigurations] SET Name = 'Vrije dagen van de laatste 2 weken', Code = 'Vrij 2' WHERE FormulaConfigurationId = @formulaId
	END
END

--2013-05-02 TH:
--Spalte für Planbezeichnung vergrößert
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].Plan') AND c.prec < 50)
BEGIN
	ALTER TABLE [Plan] ALTER COLUMN Bez VARCHAR(50)
END
GO


IF NOT EXISTS(SELECT * FROM PersoParameter WHERE Module = 1)
BEGIN
	INSERT INTO PersoParameter (Module, AzName,MonatsAbrechnung) VALUES (1,'NV',0)
END
IF NOT EXISTS(SELECT * FROM PersoParameter WHERE Module = 2)
BEGIN
	INSERT INTO PersoParameter (Module, AzName,MonatsAbrechnung) VALUES (2,'TVK',0)
END
IF NOT EXISTS(SELECT * FROM PersoParameter WHERE Module = 4)
BEGIN
	INSERT INTO PersoParameter (Module, AzName,MonatsAbrechnung) VALUES (4,'Perso',0)
END
IF NOT EXISTS(SELECT * FROM PersoParameter WHERE Module = 16)
BEGIN
	INSERT INTO PersoParameter (Module, AzName,MonatsAbrechnung) VALUES (16,'Chor',0)
END
GO
UPDATE VertragsVorlagen SET persoParameterID = (SELECT MIN(persoParameterID) FROM PersoParameter WHERE Module = 1) WHERE persoParameterID IS NULL AND Module = 1
UPDATE VertragsVorlagen SET persoParameterID = (SELECT MIN(persoParameterID) FROM PersoParameter WHERE Module = 2) WHERE persoParameterID IS NULL AND Module = 2
UPDATE VertragsVorlagen SET persoParameterID = (SELECT MIN(persoParameterID) FROM PersoParameter WHERE Module = 4) WHERE persoParameterID IS NULL AND Module = 4
UPDATE VertragsVorlagen SET persoParameterID = (SELECT MIN(persoParameterID) FROM PersoParameter WHERE Module = 16) WHERE persoParameterID IS NULL AND Module = 16
UPDATE VertragsVorlagen SET persoParameterID = (SELECT MIN(persoParameterID) FROM PersoParameter) WHERE persoParameterID IS NULL
GO

ALTER TABLE VertragsVorlagen ALTER COLUMN persoParameterID INT NOT NULL 
GO

-- 2013-05-16 SH
-- Tabelle zum Speichern der Standartbeträge für Zulagen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[BonusDefaultAmounts]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[BonusDefaultAmounts](
		[BonusDefaultAmountId] int IDENTITY(1,1) NOT NULL,
		[BonusId] int NOT NULL,
		[ValidFrom] DATETIME NULL,
		[ValidTo] DATETIME NULL,
		[DefaultAmount] float NOT NULL CONSTRAINT DF_BonusDefaultAmounts_DefaultAmount DEFAULT(0),
		[FilterSettings] TEXT NULL,
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
	 CONSTRAINT [PK_BonusDefaultAmounts] PRIMARY KEY CLUSTERED  ([BonusDefaultAmountId] ASC) ON [PRIMARY],
	 CONSTRAINT [FK_BonusDefaultAmounts_Bonuses] FOREIGN KEY([BonusId]) REFERENCES [dbo].[Zulagen] (ZulagenNr) ON DELETE CASCADE
	) ON [PRIMARY]
END
GO

GRANT SELECT ON [dbo].[BonusDefaultAmounts] TO public

GRANT UPDATE ON [dbo].[BonusDefaultAmounts] TO PersoAdmin
GRANT INSERT ON [dbo].[BonusDefaultAmounts] TO PersoAdmin
GRANT DELETE ON [dbo].[BonusDefaultAmounts] TO PersoAdmin

GRANT UPDATE ON [dbo].[BonusDefaultAmounts] TO TheaOrchester
GRANT INSERT ON [dbo].[BonusDefaultAmounts] TO TheaOrchester
GRANT DELETE ON [dbo].[BonusDefaultAmounts] TO TheaOrchester
GO

-- umschreiben der alten werte
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 135 OR (Minor = 135 AND Build < 110))))) AND
NOT EXISTS (SELECT * FROM [BonusDefaultAmounts])
BEGIN
	EXEC ('INSERT INTO BonusDefaultAmounts (BonusId,ValidFrom,ValidTo,DefaultAmount,FilterSettings,LM,UM,LC,UC) 
	SELECT z.ZulagenNr, NULL, NULL, Convert(float, Convert(VarChar(50), z.StdWertVst)), ''<?xml version="1.0" encoding="utf-16"?>
<FilterData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ValidActivityTypeNodeNames>
    <string>pubPerformance</string>
  </ValidActivityTypeNodeNames>
</FilterData>'', GETDATE(), 0, GETDATE(), 0 FROM Zulagen z WHERE z.StdWertVst > 0')

	EXEC('INSERT INTO BonusDefaultAmounts (BonusId,ValidFrom,ValidTo,DefaultAmount,FilterSettings,LM,UM,LC,UC) 
	SELECT z.ZulagenNr, NULL, NULL,  Convert(float, Convert(VarChar(50), z.StdWertPro)), ''<?xml version="1.0" encoding="utf-16"?>
<FilterData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ValidActivityTypeNodeNames>
    <string>privRehearsal</string>
  </ValidActivityTypeNodeNames>
</FilterData>'', GETDATE(), 0, GETDATE(), 0 FROM Zulagen z WHERE z.StdWertPro > 0')

END
-- erstmal auskommentiert da die alten spalten evtl. noch in altem dispo und altem orchester verwendet werden
----entfernen der alten spalten
--IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
--	WHERE c.name = 'StdWertVst' AND o.id = OBJECT_ID(N'[dbo].Zulagen'))
--BEGIN
--	ALTER TABLE Zulagen DROP COLUMN StdWertVst
--	ALTER TABLE Zulagen DROP COLUMN StdWertPro
--END
--GO

GO
--2013-05-23 TH: 
--Spalte für die Anzahl einer CashCommandPos auf FLOAT (c# DOUBLE) geändert um Kommazahlen aus PerformancePoints abbilden zu können.
DropDefault 'CashCommandPos','Quantity'
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Quantity' AND o.id = OBJECT_ID(N'[dbo].CashCommandPos') AND c.xtype <> 62)
BEGIN

	ALTER TABLE CashCommandPos ALTER COLUMN Quantity FLOAT
	ALTER TABLE CashCommandPos
            ADD CONSTRAINT DF_CashCommandPos_Quantity
            DEFAULT 0 FOR Quantity
END
GO

--2013-05-27 TH
--Spalte für PageBreak in Arbeitsbereiche eingefügt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'PageBreakBefore' and o.id = OBJECT_ID(N'dbo.AB'))
BEGIN
	ALTER TABLE dbo.AB ADD PageBreakBefore BIT NOT NULL  CONSTRAINT DF_AB_PageBreakBefore DEFAULT (0)
END

GO

-- 2013-05-28 SH
-- FK Constraint von Contract_Qualification_Person neu anlegen mit DELETE CASCADE auf Vertrag
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Contract_Qualification_Person_Contract]') ) AND
	EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 135 OR (Minor = 135 AND Build < 110)))))
BEGIN
	EXEC('ALTER TABLE dbo.Contract_Qualification_Person DROP CONSTRAINT FK_Contract_Qualification_Person_Contract')
	EXEC ('ALTER TABLE dbo.Contract_Qualification_Person WITH CHECK ADD CONSTRAINT FK_Contract_Qualification_Person_Contract FOREIGN KEY(ContractId) REFERENCES dbo.Vertrag (VertragsNr) ON DELETE CASCADE')
END
GO

-- 2013-05-29 SH
-- umstellung fahrplan.diff und fahrplanstd.diff auf float
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'Diff' AND o.id = OBJECT_ID(N'[dbo].Fahrplan') AND c.xType = 62) 
BEGIN
	ALTER TABLE dbo.Fahrplan ADD  DiffTemp float
	EXEC ('UPDATE dbo.Fahrplan  SET DiffTemp = Convert(float, Convert(VarChar(50), Diff))')
	ALTER TABLE dbo.Fahrplan ALTER COLUMN Diff float NULL
	EXEC ('UPDATE dbo.Fahrplan  SET  Diff = DiffTemp')
	EXEC ('ALTER TABLE dbo.Fahrplan  DROP COLUMN DiffTemp')
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'Diff' AND o.id = OBJECT_ID(N'[dbo].FahrplanStd') AND c.xType = 62) 
BEGIN
	ALTER TABLE dbo.FahrplanStd ADD  DiffTemp float
	EXEC ('UPDATE dbo.FahrplanStd  SET DiffTemp = Convert(float, Convert(VarChar(50), Diff))')
	ALTER TABLE dbo.FahrplanStd ALTER COLUMN Diff float NULL
	EXEC ('UPDATE dbo.FahrplanStd  SET  Diff = DiffTemp')
	EXEC ('ALTER TABLE dbo.FahrplanStd  DROP COLUMN DiffTemp')
END
GO

--2013-05-23 TK
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'BreakRules' and o.id = OBJECT_ID(N'dbo.persoParameter'))
BEGIN
	ALTER TABLE dbo.persoParameter ADD BreakRules VARCHAR(2000)
END
GO

--2013-05-28 TK
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'BonusValue' and o.id = OBJECT_ID(N'dbo.RoleBonus'))
BEGIN
	ALTER TABLE dbo.RoleBonus ADD BonusValue MONEY NULL
	ALTER TABLE dbo.AB ADD NumberOfPositions INT NULL
END
GO

-- TK 2013-06-04 FK Beziehung Abt / Schicht hinzugefügt 
UPDATE AZTypen SET InDienstplan = NULL WHERE not InDienstplan  IS NULL AND InDienstplan NOT IN (SELECT DienstplanArtenID FROM DienstplanArtenTabelle WHERE DienstplanArtenID <> 0)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Shift_Department]') AND type = 'F')
ALTER TABLE [dbo].AZTypen  WITH CHECK ADD  CONSTRAINT FK_Shift_Department FOREIGN KEY(InDienstplan)
REFERENCES [dbo].DienstplanArtenTabelle (DienstplanArtenID)
GO
ALTER TABLE [dbo].AZTypen CHECK CONSTRAINT FK_Shift_Department
GO


--2013-06-03 TH
--Spalte für die AZ bei einer Abwesenheitsschicht hinzufügen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'Worktime' and o.id = OBJECT_ID(N'dbo.AzTypen'))
BEGIN
	ALTER TABLE dbo.AzTypen ADD Worktime INT NULL
END

--2013-06-10 SH
-- neue berechtigungsgruppe zum verwalten von werken
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'WorksWrite')
BEGIN
	EXEC sp_addrole @rolename = N'WorksWrite'
END
GO

--tabelle für werke
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.Works') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.Works (
		[WorkId] [int] IDENTITY(1,1) NOT NULL,
		[OriginalTitle] NVARCHAR(250) NOT NULL,
		[Title] NVARCHAR(20) NOT NULL,
		[SubTitle] NVARCHAR(255) NULL,
		[DebutDateOrYear] VARCHAR(10) NULL,
		[DebutPlace] VARCHAR(30) NULL,
		[LanguageCode] VARCHAR(2) NULL,
		[Description] text NULL,
		[GenreId] INT NOT NULL,
		[LM] datetime NOT NULL,
		[UM] int NOT NULL,
		[LC] datetime NOT NULL,
		[UC] int NOT NULL,
		CONSTRAINT PK_Works PRIMARY KEY CLUSTERED (WorkId ASC) ON [PRIMARY],	
		CONSTRAINT [FK_Works_Genres] FOREIGN KEY([GenreId]) REFERENCES [dbo].[Typ] (TypID)
	) ON [PRIMARY]
END
GO

-- da die tabelle in bayreuth schon da ist, werden gewisse anpassungen vorgenommen
-- author wird entfernt
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'Author' and o.id = OBJECT_ID(N'dbo.Works'))
BEGIN
	ALTER TABLE dbo.Works DROP COLUMN Author
END
GO

-- alte titel spalte umbenennen in originaltitle
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'Titel' and o.id = OBJECT_ID(N'dbo.Works'))
BEGIN
	EXEC sp_rename 'Works.Titel', 'OriginalTitle', 'COLUMN'
END
GO

-- spalte für title wird hizugefügt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'Title' and o.id = OBJECT_ID(N'dbo.Works'))
BEGIN
	EXEC('ALTER TABLE dbo.Works ADD Title NVARCHAR(20) NULL')
	EXEC('UPDATE dbo.Works SET Title = Substring(OriginalTitle, 0, 20)')
	EXEC('ALTER TABLE dbo.Works ALTER COLUMN Title NVARCHAR(20) NOT NULL')
END
GO

-- spalte für subtitle wird hinzugefügt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'SubTitle' and o.id = OBJECT_ID(N'dbo.Works'))
BEGIN
	ALTER TABLE dbo.Works ADD [SubTitle] NVARCHAR(255) NULL 
END
GO

-- spalte für genreid wird hinzugefügt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'GenreId' and o.id = OBJECT_ID(N'dbo.Works'))
BEGIN
	ALTER TABLE dbo.Works ADD GenreId INT NULL 
	-- da bisher nur in bayreuth vorhanden wird werkeart auf oper gesetzt
	EXEC('UPDATE Works SET GenreId = 31')
	ALTER TABLE Works ALTER COLUMN GenreId INT NOT NULL
	ALTER TABLE dbo.Works ADD CONSTRAINT [FK_Works_Genres] FOREIGN KEY([GenreId]) REFERENCES [dbo].[Typ] (TypID)
END
GO

-- spalten für uraufführung wird hinzugefügt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'DebutDateOrYear' and o.id = OBJECT_ID(N'dbo.Works'))
BEGIN
	ALTER TABLE dbo.Works ADD [DebutDateOrYear] VARCHAR(10) NULL
	ALTER TABLE dbo.Works ADD [DebutPlace] VARCHAR(30) NULL
	EXEC('UPDATE Works SET DebutDateOrYear = DebutYear WHERE NOT DebutYear IS NULL')
	EXEC('ALTER TABLE Works DROP COLUMN DebutYear')
END
GO
-- berechtigung für works setzen
GRANT SELECT ON dbo.Works TO [Public]
GRANT DELETE ON dbo.Works TO [WorksWrite]
GRANT INSERT ON dbo.Works TO [WorksWrite]
GRANT UPDATE ON dbo.Works TO [WorksWrite]
GO

-- tabelle für den author/komponisten des werkes
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.WorkCreators') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.WorkCreators (
		[WorkCreatorId] [int] IDENTITY(1,1) NOT NULL,
		[WorkId] [int] NOT NULL,
		[PersonId] [int] NOT NULL,
		[JobId] INT NOT NULL,
		[Note] varchar(250) NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		CONSTRAINT PK_WorkCreators PRIMARY KEY CLUSTERED ([WorkCreatorId] ASC) ON [PRIMARY],
		CONSTRAINT [FK_WorkCreators_Works] FOREIGN KEY([WorkId]) REFERENCES [dbo].Works (WorkId) ON DELETE CASCADE,
		CONSTRAINT [FK_WorkCreators_Persons] FOREIGN KEY(PersonId) REFERENCES [dbo].PersH (PersNr)	
	) ON [PRIMARY]
END
GO

-- berechtigung für workcreators setzen
GRANT SELECT ON dbo.WorkCreators TO [Public]
GRANT DELETE ON dbo.WorkCreators TO [WorksWrite]
GRANT INSERT ON dbo.WorkCreators TO [WorksWrite]
GRANT UPDATE ON dbo.WorkCreators TO [WorksWrite]
GO

-- tabelle für workversions
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.WorkVersions') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.WorkVersions (
		[WorkVersionId] [int] IDENTITY(1,1) NOT NULL,
		[WorkId] [int] NOT NULL,
		[Version] varchar(100) NOT NULL,
		[PublisherId] [int] NULL,
		[PublicationYear] INT NULL,
		[CatalogNumber] VARCHAR(100) NULL,
		[AdditionalMaterial] VARCHAR(100) NULL,
		[Duration] INT NULL,
		[Note] TEXT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		CONSTRAINT PK_WorkVersions PRIMARY KEY CLUSTERED (WorkVersionId ASC) ON [PRIMARY],
		CONSTRAINT [FK_WorkVersions_Works] FOREIGN KEY([WorkId]) REFERENCES [dbo].Works (WorkId) ON DELETE CASCADE,
		CONSTRAINT [FK_WorkVersions_Persons] FOREIGN KEY([PublisherId]) REFERENCES [dbo].PersH (PersNr)	
	) ON [PRIMARY]
END
GO

-- tabelle für workversions
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.WorkVersions') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.WorkVersions (
		[WorkVersionId] [int] IDENTITY(1,1) NOT NULL,
		[WorkId] [int] NOT NULL,
		[Version] varchar(100) NOT NULL,
		[PublisherId] [int] NULL,
		[PublicationYear] INT NULL,
		[CatalogNumber] VARCHAR(100) NULL,
		[AdditionalMaterial] VARCHAR(100) NULL,
		[Duration] INT NULL,
		[Note] TEXT NULL,
		[LM] [datetime] NOT NULL,
		[UM] [int] NOT NULL,
		[LC] [datetime] NOT NULL,
		[UC] [int] NOT NULL,
		CONSTRAINT PK_WorkVersions PRIMARY KEY CLUSTERED (WorkVersionId ASC) ON [PRIMARY],
		CONSTRAINT [FK_WorkVersions_Works] FOREIGN KEY([WorkId]) REFERENCES [dbo].Works (WorkId) ON DELETE CASCADE,
		CONSTRAINT [FK_WorkVersions_Persons] FOREIGN KEY([PublisherId]) REFERENCES [dbo].PersH (PersNr)	
	) ON [PRIMARY]
END
GO

-- berechtigung für workcreators setzen
GRANT SELECT ON dbo.WorkVersions TO [Public]
GRANT DELETE ON dbo.WorkVersions TO [WorksWrite]
GRANT INSERT ON dbo.WorkVersions TO [WorksWrite]
GRANT UPDATE ON dbo.WorkVersions TO [WorksWrite]
GO

--verweis auf Works in Resources hinzufügen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'WorkVersionId' and o.id = OBJECT_ID(N'dbo.Resources'))
BEGIN
	ALTER TABLE dbo.Resources ADD WorkVersionId INT NULL
END
GO
--mit fremdschlüssel
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Resources_WorkVersions]') AND type = 'F')
BEGIN
	ALTER TABLE dbo.Resources WITH CHECK ADD CONSTRAINT FK_Resources_WorkVersions FOREIGN KEY(WorkVersionId) REFERENCES dbo.WorkVersions (WorkVersionId) ON DELETE CASCADE
END
GO

GRANT DELETE ON dbo.Resources TO [WorksWrite]
GRANT INSERT ON dbo.Resources TO [WorksWrite]
GRANT UPDATE ON dbo.Resources TO [WorksWrite]
GO


--2013-06-10 TH
--Neue Tabellen für dynamische Felder in Verträgen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ContractFieldTypes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.ContractFieldTypes(
		ContractFieldTypeId int IDENTITY(1,1) NOT NULL,
		CategoryName VARCHAR(100) NOT NULL,
		CategoryCode VARCHAR(20) NULL,
		Note TEXT,
		Sort int NOT NULL CONSTRAINT DF_ContractFieldTypes_Sort DEFAULT(0),
		LM datetime NOT NULL,
		UM int NOT NULL,
		LC datetime NOT NULL,
		UC int NOT NULL,
		CONSTRAINT PK_ContractFieldType PRIMARY KEY CLUSTERED (ContractFieldTypeId ASC) ON [PRIMARY],
	) ON [PRIMARY]

	CREATE UNIQUE NONCLUSTERED INDEX [IX_CategoryCode] ON dbo.ContractFieldTypes (CategoryCode)
	CREATE NONCLUSTERED INDEX [IX_Sort] ON dbo.ContractFieldTypes (Sort)

END

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

-- 2013-06-21

CREATE PROCEDURE [dbo].[DeleteCast] 
	@CastId INT
AS
BEGIN
	SET NOCOUNT ON
 
	DECLARE @UserGroupId INT 
	DECLARE @RoleId INT
	DECLARE @JobId INT

	CREATE TABLE #Msg(attribut int, msg varchar(200), [count] int)


	--Rolle oder Job ermitteln
	SELECT @RoleId = ISNULL(RolleID, -10), @JobId = ISNULL(AuffTechAufgabeID, -10)  
		FROM BesetzungTabelle 
		WHERE BesetzungTabelle.ID = @CastId

	--Keine Rolle (perso), RolleId aus Aufgabe ermitteln
	IF (@RoleId  = -10) 
	BEGIN 
		SELECT @RoleId = RolleID 
			FROM AuffTechAufgabe
			WHERE AuffTechAufgabeID = @JobId
	END
	
	IF (@RoleId  = -0) --Aufgabe ohne Vorlage (Rolle), keine weitere Prüfung möglich
		BEGIN 
			DELETE FROM VertragsBesetzungsHonorar WHERE BesID = @CastId
			UPDATE ContractDates SET  CastId = NULL WHERE CastId = @CastId
			DELETE FROM BesetzungTabelle WHERE Id = @CastId
		END
	ELSE
		BEGIN

		--BesitzerId der Rolle
		SELECT @UserGroupId = ISNULL(Besitzer, -10) 
			FROM BesetzungStd
			WHERE BesetzungStd.Id = @RoleId


		IF (dbo.GetCurrentPermission(@UserGroupId, 4) < 2) 
			BEGIN
				INSERT INTO #Msg (attribut, msg) VALUES (1,'No Permission')
			END
		ELSE
			BEGIN 
				IF (@CastId <= 0 OR @RoleId <= -10)	
					BEGIN
						INSERT INTO #Msg (attribut, msg) VALUES (0,'Keine gültige Besetzung')
					END
				ELSE
					BEGIN
						DELETE FROM VertragsBesetzungsHonorar WHERE BesID = @CastId
						UPDATE ContractDates SET  CastId = NULL WHERE CastId = @CastId
						DELETE FROM BesetzungTabelle WHERE Id = @CastId
					END
			END
	END
END	
	SELECT * FROM #Msg

GO




GRANT EXECUTE ON DeleteCast TO Public
GRANT SELECT ON [dbo].[ContractFieldTypes] TO [public]
GRANT SELECT ON [dbo].[ContractFieldTypes] TO [PersoContractWrite]
GRANT DELETE ON [dbo].[ContractFieldTypes] TO [PersoContractWrite]
GRANT INSERT ON [dbo].[ContractFieldTypes] TO [PersoContractWrite]
GRANT UPDATE ON [dbo].[ContractFieldTypes] TO [PersoContractWrite]


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ContractFields]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.ContractFields(
		ContractFieldId int IDENTITY(1,1) NOT NULL,
		ContractFieldTypeId int NOT NULL,
		PersContractId int NOT NULL,
		TextValue VARCHAR(250) NOT NULL,
		LM datetime NOT NULL,
		UM int NOT NULL,
		LC datetime NOT NULL,
		UC int NOT NULL,
		CONSTRAINT PK_ContractFields PRIMARY KEY CLUSTERED (ContractFieldId ASC) ON [PRIMARY],
		CONSTRAINT [FK_ContractFields_ContractFieldTypes] FOREIGN KEY(ContractFieldTypeId) REFERENCES dbo.ContractFieldTypes (ContractFieldTypeId),
		CONSTRAINT [FK_ContractFields_PersContract] FOREIGN KEY(PersContractId) REFERENCES dbo.Vertrag (VertragsNr)  ON DELETE CASCADE
	) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX [IX_ContractFieldTypeId] ON dbo.ContractFields (ContractFieldTypeId)
	CREATE NONCLUSTERED INDEX [IX_PersContractId] ON dbo.ContractFields (PersContractId)
	CREATE UNIQUE NONCLUSTERED INDEX IX_ContractFieldTypeId_PersContractId ON dbo.ContractFields
		(ContractFieldTypeId, PersContractId) ON [PRIMARY]
	
	
END

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbContractFields_Update]'))
BEGIN
	DROP VIEW [dbo].AbContractFields_Update
END
GO
CREATE VIEW [dbo].AbContractFields_Update
AS 
SELECT * FROM ContractFields WHERE PersContractId 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 = 1 AND UserGruppe.Schreiben = 1) 
WITH CHECK OPTION
GO
GRANT SELECT ON dbo.AbContractFields_Update TO Public
GRANT DELETE ON dbo.AbContractFields_Update TO Public
GRANT INSERT ON dbo.AbContractFields_Update TO Public
GRANT UPDATE ON dbo.AbContractFields_Update TO Public
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbContractFields]'))
BEGIN
	DROP VIEW [dbo].AbContractFields
END
GO
CREATE VIEW [dbo].AbContractFields
AS 
SELECT * FROM ContractFields WHERE PersContractId 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 = 1 ) 
WITH CHECK OPTION
GO
GRANT SELECT ON dbo.AbContractFields TO Public

GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ContractTypes_ContractFieldTypes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.ContractTypes_ContractFieldTypes(
		ContractType_ContractFieldTypeId int IDENTITY(1,1) NOT NULL,
		ContractFieldTypeId int NOT NULL,
		ContractTypeId int NOT NULL,
		LM datetime NOT NULL,
		UM int NOT NULL,
		LC datetime NOT NULL,
		UC int NOT NULL,
		CONSTRAINT PK_ContractTypes_ContractFieldTypes PRIMARY KEY CLUSTERED (ContractType_ContractFieldTypeId ASC) ON [PRIMARY],
		CONSTRAINT [FK_ContractTypes_ContractFieldTypes_ContractFieldTypes] FOREIGN KEY(ContractFieldTypeId) REFERENCES dbo.ContractFieldTypes (ContractFieldTypeId),
		CONSTRAINT [FK_ContractTypes_ContractFieldTypes_ContractTypes] FOREIGN KEY(ContractTypeId) REFERENCES dbo.VertragsVorlagen (VorlagenID)
	) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX [IX_ContractFieldTypeId] ON dbo.ContractTypes_ContractFieldTypes (ContractFieldTypeId)
	CREATE NONCLUSTERED INDEX [IX_ContractTypeId] ON dbo.ContractTypes_ContractFieldTypes (ContractTypeId)
	CREATE UNIQUE NONCLUSTERED INDEX IX_ContractFieldTypeId_ContractTypeId ON dbo.ContractTypes_ContractFieldTypes
		(ContractFieldTypeId, ContractTypeId) ON [PRIMARY]
	
	
END

GRANT SELECT ON [dbo].ContractTypes_ContractFieldTypes TO [public]
GRANT SELECT ON [dbo].ContractTypes_ContractFieldTypes TO [PersoContractWrite]
GRANT DELETE ON [dbo].ContractTypes_ContractFieldTypes TO [PersoContractWrite]
GRANT INSERT ON [dbo].ContractTypes_ContractFieldTypes TO [PersoContractWrite]
GRANT UPDATE ON [dbo].ContractTypes_ContractFieldTypes TO [PersoContractWrite]

GO

--TK2013-06-17 Der Suchname darf nicht leer sein
UPDATE PersH Set Suchname = LEFT(Nachname,20) FROM PersH WHERE PersNr <> 0 AND PersNr <> 260 AND  ISNULL(Suchname,'') = '' AND ISNULL(Nachname,'') <> '' 
UPDATE PersH Set Suchname = LEFT(Vorname,20) FROM PersH WHERE PersNr <> 0 AND PersNr <> 260 AND   ISNULL(Suchname,'') = ''  AND ISNULL(Vorname,'') <> '' 
UPDATE PersH Set Suchname = LEFT('_Name fehlt:' + CAST(persnr AS varchar(15)),20) FROM PersH WHERE PersNr <> 0 AND PersNr <> 260 AND   ISNULL(Suchname,'') = '' 

--2013-07-01 TH:
--2 Neue Felder (Kategorie und Sortiernummer) in der Tabelle PersonAttachments hinzugefügt

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.PersonAttachments'))
BEGIN
	ALTER TABLE dbo.PersonAttachments ADD Category INT NULL
	ALTER TABLE dbo.PersonAttachments ADD Sort INT NOT NULL CONSTRAINT DF_PersonAttachments_Sort DEFAULT(0)
END




--TK 2013-06-24
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Kurz' AND o.id = OBJECT_ID(N'[dbo].Preise') AND c.prec < 15)
BEGIN
	ALTER TABLE Preise ALTER COLUMN Kurz VARCHAR(15)
END

GO
--TK2013-06-24 Bonus der das vertragliche Honorar pro Vst ersetzt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'ReplacedContractFee' and o.id = OBJECT_ID(N'dbo.Zulagen'))
BEGIN
	ALTER TABLE dbo.Zulagen ADD ReplacedContractFee BIT NOT NULL CONSTRAINT DF_Bonus_ReplacedContractFee DEFAULT(0)
END
GO
UPDATE RepArt SET ShowInModul = 1 WHERE ISNULL(ShowInModul,1) = 0
GO



--TK 2013-06-24
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Kurz' AND o.id = OBJECT_ID(N'[dbo].Preise') AND c.prec < 15)
BEGIN
	ALTER TABLE Preise ALTER COLUMN Kurz VARCHAR(15)
END

GO
--TK2013-06-24 Bonus der das vertragliche Honorar pro Vst ersetzt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'ReplacedContractFee' and o.id = OBJECT_ID(N'dbo.Zulagen'))
BEGIN
	ALTER TABLE dbo.Zulagen ADD ReplacedContractFee BIT NOT NULL CONSTRAINT DF_Bonus_ReplacedContractFee DEFAULT(0)
END
GO
UPDATE RepArt SET ShowInModul = 1 WHERE ISNULL(ShowInModul,1) = 0
GO

--2013-07-15 sh
--verweis von produktionen auf werke
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'WorkVersionId' and o.id = OBJECT_ID(N'dbo.stücke'))
BEGIN
	ALTER TABLE dbo.Stücke ADD WorkVersionId INT NULL
END
GO
--mit fremdschlüssel

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Productions_WorkVersions]') AND type = 'F')
BEGIN
	ALTER TABLE dbo.Stücke DROP CONSTRAINT FK_Productions_WorkVersions 
END
--2013-09-13 Mit SET NULL
DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
IF @sql_server_version > 8 AND NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Productions_WorkVersions2]') AND type = 'F')
BEGIN
	EXEC('ALTER TABLE dbo.Stücke WITH CHECK ADD CONSTRAINT FK_Productions_WorkVersions2 FOREIGN KEY(WorkVersionId) REFERENCES dbo.WorkVersions (WorkVersionId) ON DELETE SET NULL')
END
GO

--2013-07-15 sh
-- tabelle workroles und wrokroles_repertoire umbennen sowie spalten umbennen und erweitern
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[WorkRoles]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	-- fremdschlüssel und indizes von workroles_reperoire löschen
	EXEC('DROP INDEX IX_WorkRoles_Repertoire_PersonId ON WorkRoles_Repertoire')
	EXEC('DROP INDEX IX_WorkRoles_Repertoire_WorkRoleId ON WorkRoles_Repertoire')
	ALTER TABLE WorkRoles_Repertoire DROP CONSTRAINT PK_WorkRoles_RepertoireId
	ALTER TABLE WorkRoles_Repertoire DROP CONSTRAINT FK_WorkRoles_Repertoire_Person
	ALTER TABLE WorkRoles_Repertoire DROP CONSTRAINT FK_WorkRoles_Repertoire_Theater
	ALTER TABLE WorkRoles_Repertoire DROP CONSTRAINT FK_WorkRoles_Repertoire_WorkRoles
	ALTER TABLE WorkRoles_Repertoire DROP CONSTRAINT FK_WorkRoles_RepertoireTypeId
	-- fremdschlüssel und indizes von workroles löschen
	ALTER TABLE WorkRoles DROP CONSTRAINT PK_WorkRoleId
	ALTER TABLE WorkRoles DROP CONSTRAINT FK_Works_WorkRoles
	ALTER TABLE WorkRoles DROP CONSTRAINT DF_WorkRoles_IsStarRole
	-- umbennenungen für workroles_reperoire
	EXEC sp_rename 'WorkRoles_Repertoire', 'WorkVersionRoles_Repertoire'
	EXEC sp_rename @objname='WorkVersionRoles_Repertoire.WorkRoles_RepertoireId', @newname='WorkVersionRoleRepertoireId', @objtype = 'COLUMN'
	EXEC sp_rename @objname='WorkVersionRoles_Repertoire.WorkRoleId', @newname='WorkVersionRoleId', @objtype = 'COLUMN'
	-- umbennenungen für workroles
	EXEC sp_rename 'WorkRoles', 'WorkVersionRoles'
	EXEC sp_rename @objname='WorkVersionRoles.WorkRoleId', @newname='WorkVersionRoleId', @objtype = 'COLUMN'
	EXEC sp_rename @objname='WorkVersionRoles.WorkId', @newname='WorkVersionId', @objtype = 'COLUMN'
	-- neue spalten für workversionroles
	EXEC('ALTER TABLE WorkVersionRoles ADD RoleCategoryId INT NULL')
	EXEC('ALTER TABLE WorkVersionRoles ALTER COLUMN Name VARCHAR(250) NOT NULL')
	EXEC('ALTER TABLE WorkVersionRoles ADD [Count] INT NOT NULL CONSTRAINT [DF_WorkVersionRoles_Count] DEFAULT (1)')
	-- für jede work eine workversion anlegen
	EXEC('SET IDENTITY_INSERT WorkVersions ON;INSERT INTO WorkVersions (WorkVersionId, WorkId,[Version],LM,UM,LC,UC) SELECT w.WorkId, w.WorkId, ''Originalfassung'', GETDATE(), 0, GETDATE(), 0 FROM Works w;SET IDENTITY_INSERT WorkVersions OFF')
	-- schlüssel und indizes für workversionroles anlegen
	EXEC('ALTER TABLE WorkVersionRoles WITH CHECK ADD CONSTRAINT PK_WorkVersionRoles PRIMARY KEY CLUSTERED (WorkVersionRoleId)')
	EXEC('ALTER TABLE WorkVersionRoles WITH CHECK ADD CONSTRAINT FK_WorkVersionRoles_WorkVersions FOREIGN KEY(WorkVersionId) REFERENCES WorkVersions
	(WorkVersionId)')
	EXEC('ALTER TABLE WorkVersionRoles WITH CHECK ADD CONSTRAINT FK_WorkVersionRoles_RoleCategories FOREIGN KEY(RoleCategoryId) REFERENCES RollenLtg
	(RollenLtgId)')
	EXEC('ALTER TABLE WorkVersionRoles ADD CONSTRAINT DF_WorkVersionRoles_IsStarRole DEFAULT (0) FOR IsStarRole')
	EXEC('CREATE NONCLUSTERED INDEX IX_WorkVersionRoles_WorkVersionId ON WorkVersionRoles (WorkVersionId) ON [PRIMARY]')
	-- schlüssel und indizes für workversionroles_reperoire anlegen
	EXEC('ALTER TABLE WorkVersionRoles_Repertoire WITH CHECK ADD CONSTRAINT PK_WorkVersionRoles_Repertoire PRIMARY KEY CLUSTERED (WorkVersionRoleRepertoireId)')
	EXEC('ALTER TABLE WorkVersionRoles_Repertoire WITH CHECK ADD CONSTRAINT FK_WorkVersionRoles_Repertoire_Persons_PersonId FOREIGN KEY(PersonId) REFERENCES PersH
	(PersNr)')
	EXEC('ALTER TABLE WorkVersionRoles_Repertoire WITH CHECK ADD CONSTRAINT FK_WorkVersionRoles_Repertoire_Persons_TheaterId FOREIGN KEY(TheaterId) REFERENCES PersH
	(PersNr)')
	EXEC('ALTER TABLE WorkVersionRoles_Repertoire WITH CHECK ADD CONSTRAINT FK_WorkVersionRoles_Repertoire_WorkVersionRoles FOREIGN KEY(WorkVersionRoleId) REFERENCES WorkVersionRoles
	(WorkVersionRoleId)')
	EXEC('ALTER TABLE WorkVersionRoles_Repertoire WITH CHECK ADD CONSTRAINT FK_WorkVersionRoles_Repertoire_RepertoireTypes FOREIGN KEY(RepertoireTypeId) REFERENCES RepArt
	(ID)')
	EXEC('CREATE NONCLUSTERED INDEX IX_WorkVersionRoles_Repertoire_PersonId ON WorkVersionRoles_Repertoire (PersonId) ON [PRIMARY]')
	EXEC('CREATE NONCLUSTERED INDEX IX_WorkVersionRoles_Repertoire_WorkVersionRoleId ON WorkVersionRoles_Repertoire (WorkVersionRoleId) ON [PRIMARY]')
END
GO

-- tabelle workversionroles und workversionroles_repertoire neu anlegen (für nicht bayreuth)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[WorkVersionRoles]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.WorkVersionRoles(
		WorkVersionRoleId INT IDENTITY(1,1) NOT NULL,
		WorkVersionId INT NOT NULL,
		Sort INT NOT NULL,
		Name NVARCHAR(250) NOT NULL,
		IsStarRole BIT NOT NULL CONSTRAINT DF_WorkVersionRoles_IsStarRole DEFAULT 0,
		[Description] TEXT NULL,
		[Count] INT NOT NULL CONSTRAINT [DF_WorkVersionRoles_Count] DEFAULT 1,
		RoleCategoryId INT NOT NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,		
		CONSTRAINT PK_WorkVersionRoles PRIMARY KEY CLUSTERED (WorkVersionRoleId ASC) ON [PRIMARY],
		CONSTRAINT FK_WorkVersionRoles_WorkVersions FOREIGN KEY(WorkVersionId) REFERENCES dbo.WorkVersions (WorkVersionId),
		CONSTRAINT FK_WorkVersionRoles_RoleCategories FOREIGN KEY(RoleCategoryId) REFERENCES RollenLtg (RollenLtgId)
	) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX IX_WorkVersionRoles_WorkVersionId ON WorkVersionRoles (WorkVersionId) ON [PRIMARY]	
END

GRANT SELECT ON [dbo].WorkVersionRoles TO [public]
GRANT DELETE ON [dbo].WorkVersionRoles TO WorksWrite
GRANT INSERT ON [dbo].WorkVersionRoles TO WorksWrite
GRANT UPDATE ON [dbo].WorkVersionRoles TO WorksWrite
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[WorkVersionRoles_Repertoire]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.WorkVersionRoles_Repertoire(
		WorkVersionRoleRepertoireId INT IDENTITY(1,1) NOT NULL,
		WorkVersionRoleId INT NOT NULL,
		PersonId INT NOT NULL,
		RepertoireTypeId INT NOT NULL,
		TheaterId INT NULL,
		LanguageCode VARCHAR(2) NULL,
		LastPerformanceYear INT NULL,
		[Description] TEXT NULL,		
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_WorkVersionRoles_Repertoire PRIMARY KEY CLUSTERED (WorkVersionRoleRepertoireId) ON [PRIMARY],
		CONSTRAINT FK_WorkVersionRoles_Repertoire_Persons_PersonId FOREIGN KEY(PersonId) REFERENCES PersH (PersNr),
		CONSTRAINT FK_WorkVersionRoles_Repertoire_Persons_TheaterId FOREIGN KEY(TheaterId) REFERENCES PersH (PersNr),
		CONSTRAINT FK_WorkVersionRoles_Repertoire_WorkVersionRoles FOREIGN KEY(WorkVersionRoleId) REFERENCES WorkVersionRoles (WorkVersionRoleId),
		CONSTRAINT FK_WorkVersionRoles_Repertoire_RepertoireTypes FOREIGN KEY(RepertoireTypeId) REFERENCES RepArt (ID)
	) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX IX_WorkVersionRoles_Repertoire_PersonId ON WorkVersionRoles_Repertoire (PersonId) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IX_WorkVersionRoles_Repertoire_WorkVersionRoleId ON WorkVersionRoles_Repertoire (WorkVersionRoleId) ON [PRIMARY]
END

GRANT SELECT ON [dbo].WorkVersionRoles_Repertoire TO [public]
GRANT DELETE ON [dbo].WorkVersionRoles_Repertoire TO WorksWrite
GRANT INSERT ON [dbo].WorkVersionRoles_Repertoire TO WorksWrite
GRANT UPDATE ON [dbo].WorkVersionRoles_Repertoire TO WorksWrite
GO

--2013-07-19 sh
--neue spalte für resourcetypes, categoryid
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'CategoryId' and o.id = OBJECT_ID(N'dbo.ResourceTypes'))
BEGIN
	ALTER TABLE dbo.ResourceTypes ADD CategoryId int NOT NULL CONSTRAINT DF_ResourceTypes_CategoryId DEFAULT 0
END
GO

--2013-07-25
--neue spalte workroleid für besetzungstd
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'WorkVersionRoleId' and o.id = OBJECT_ID(N'dbo.BesetzungStd'))
BEGIN
	ALTER TABLE dbo.BesetzungStd ADD WorkVersionRoleId int NULL
END
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_BesetzungStd_WorkVersionRoles]') AND type = 'F')
BEGIN
	ALTER TABLE dbo.BesetzungStd DROP CONSTRAINT FK_BesetzungStd_WorkVersionRoles 
END
--2013-09-13 Mit SET NULL
DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
IF @sql_server_version > 8 AND NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_BesetzungStd_WorkVersionRoles2]') AND type = 'F')
BEGIN
EXEC ('ALTER TABLE dbo.BesetzungStd WITH CHECK ADD CONSTRAINT FK_BesetzungStd_WorkVersionRoles2 FOREIGN KEY(WorkVersionRoleId) REFERENCES dbo.WorkVersionRoles (WorkVersionRoleId) ON DELETE SET NULL')
END

GO

--2013-08-09 sh
--neue settingsspalte für resourceobjects
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ResourceData' AND o.id = OBJECT_ID(N'[dbo].ResourceObjects'))
BEGIN
	DECLARE @serverVersion INT
	SELECT @serverVersion = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
	--PRINT @serverVersion
	IF @serverVersion < 9
		EXEC('ALTER TABLE ResourceObjects ADD ResourceData VARCHAR(6000)')
	ELSE
		EXEC('ALTER TABLE ResourceObjects ADD ResourceData VARCHAR(MAX)')

	EXEC('UPDATE ResourceObjects SET ResourceData = (
		SELECT 
			''<InstrumentResourceObjectData
			 IsForOpenAirTheater="'' + CASE InstrumentResourceObjectData.IsOutdoorCapable WHEN 1 THEN ''true'' ELSE ''false'' END + ''"
			 IsPrivate="'' + CASE InstrumentResourceObjectData.IsPrivate WHEN 1 THEN ''true'' ELSE ''false'' END + ''"
			 ValueEstimatedBy="''+ISNULL(InstrumentResourceObjectData.ValueEstimatedBy, '''')+''"
			 HasDecreaseInValue="'' + CASE  InstrumentResourceObjectData.HasDecreaseInValue WHEN 1 THEN ''true'' ELSE ''false'' END + ''"
			 IsGuestPerformanceCapable="'' + CASE InstrumentResourceObjectData.IsGuestPerformanceCapable WHEN 1 THEN ''true'' ELSE ''false'' END + ''"
			 IsAssured="'' + CASE InstrumentResourceObjectData.IsAssured WHEN 1 THEN ''true'' ELSE ''false'' END + ''" />''
		FROM ResourceObjects InstrumentResourceObjectData 
		WHERE InstrumentResourceObjectData.ResourceObjectId = ResourceObjects.ResourceObjectId 
	) WHERE ResourceId IN (
		SELECT r.ResourceId FROM Resources r JOIN ResourceTypes rt ON r.ResourceTypeId = rt.ResourceTypeId	WHERE rt.Module = 2
	)')
END
GO

--2013-08-13 sh
--neue code spalte für resourceobjects
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'IdentificationCode' AND o.id = OBJECT_ID(N'[dbo].ResourceObjects'))
BEGIN
	ALTER TABLE ResourceObjects ADD IdentificationCode VARCHAR(30)
END
GO

-- alten uniquekey löschen
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UQ_ResourceTypes_Name]') AND xtype = 'UQ')
BEGIN
	ALTER TABLE dbo.ResourceTypes DROP CONSTRAINT UQ_ResourceTypes_Name
END
GO

-- neuen unique key für name/categoryid von resourcetypes
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UQ_ResourceTypes_Name_CategoryId]') AND xtype = 'UQ')
BEGIN
	ALTER TABLE dbo.ResourceTypes ADD CONSTRAINT UQ_ResourceTypes_Name_CategoryId UNIQUE NONCLUSTERED (Name, CategoryId) ON [PRIMARY]
END
GO

--einmalig resourcentypen einstellen, categorie gemäß modul.
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (
Major < 4 OR (Major = 4 AND (Minor < 135 OR (Minor = 135 AND Build < 110)))))
BEGIN
	UPDATE ResourceTypes SET CategoryId = 0 WHERE Module = 1 -- sonstiges = dispo
	UPDATE ResourceTypes SET CategoryId = 1 WHERE Module = 2 -- instrumente = orchester
	UPDATE ResourceTypes SET CategoryId = 2 WHERE Module = 64 -- noten = library
END

-- 2013-08-15 sh
-- stored procedures zum entfernen der verbindung zw. werkefassung und produktion (bei delete von workversion)
-- ursprüngliche version löschen (wurde umbenannt inzwischen)
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].RemoveWorkVersionFromProductions'))
BEGIN
	DROP PROCEDURE dbo.RemoveWorkVersionFromProductions
END
GO
-- prozedur neu aerstellen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].NullifyProductionReferencesToWorkVersion'))
BEGIN
	DROP PROCEDURE dbo.NullifyProductionReferencesToWorkVersion
END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].RemoveWorkVersionReference'))
BEGIN
	DROP PROCEDURE dbo.RemoveWorkVersionReference
END
GO


CREATE PROCEDURE [dbo].RemoveWorkVersionReference 
	@productionId INT, @workVersionId INT
AS
BEGIN
	SET NOCOUNT ON
	UPDATE BesetzungStd SET WorkVersionRoleId = NULL WHERE SNr = @productionId AND EXISTS(SELECT * FROM Stücke s WHERE s.WorkVersionId = @workVersionId AND s.SNr = BesetzungStd.Snr)
	UPDATE Stücke SET WorkVersionId = NULL WHERE WorkVersionId = @workVersionId AND Snr = @productionId 
END	
GO

GRANT EXECUTE ON RemoveWorkVersionReference TO WorksWrite

-- stored procedures zum entfernen der verbindung zw. werkrollen und produktionsrollen (bei delete von workversionrole)
-- ursprüngliche version löschen (wurde umbenannt inzwischen)
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].RemoveWorkVersionRoleFromBasicCast'))
BEGIN
	DROP PROCEDURE dbo.RemoveWorkVersionRoleFromBasicCast
END
GO
-- prozedur neu erstellen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].NullifyBasicCastReferencesToWorkVersionRole'))
BEGIN
	DROP PROCEDURE dbo.NullifyBasicCastReferencesToWorkVersionRole
END	
GO

--CREATE PROCEDURE [dbo].NullifyBasicCastReferencesToWorkVersionRole 
--	@workVersionRoleId INT
--AS
--BEGIN
--	SET NOCOUNT ON
--	UPDATE BesetzungStd SET WorkVersionRoleId = NULL WHERE WorkVersionRoleId = @workVersionRoleId
--END	
--GO

--GRANT EXECUTE ON NullifyBasicCastReferencesToWorkVersionRole TO WorksWrite

-- stored procedures zum entfernen der verbindung zw. werkrollen und produktionsrollen (beim ändern von werk in produktion)
-- ursprüngliche version löschen (wurde umbenannt inzwischen)
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].ClearWorkVersionRolesFromBasicCast'))
BEGIN
	DROP PROCEDURE dbo.ClearWorkVersionRolesFromBasicCast
END
GO
-- prozedur neu erstellen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].NullifyBasicCastReferencesToWorkVersionRoles'))
BEGIN
	DROP PROCEDURE dbo.NullifyBasicCastReferencesToWorkVersionRoles
END
GO

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

	DECLARE @UserGroup int

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

GRANT EXECUTE ON NullifyBasicCastReferencesToWorkVersionRoles TO Public
GO

-- 2013-08-21 sh
-- FK für vertrag in besetzung
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].BesetzungTabelle'))
BEGIN
	ALTER TABLE BesetzungTabelle ADD ContractId INT NULL
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Cast_Contract]') AND type = 'F')
BEGIN
	ALTER TABLE dbo.BesetzungTabelle DROP CONSTRAINT FK_Cast_Contract
END
GO
DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
IF @sql_server_version > 8 AND NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Cast_Contract2]') AND type = 'F')
BEGIN
	UPDATE BesetzungTabelle SET ContractId = NULL WHERE ContractId IS NOT NULL AND NOT EXISTS (SELECT VertragsNr FROM Vertrag WHERE VertragsNr = ContractId)
	EXEC('ALTER TABLE dbo.BesetzungTabelle WITH CHECK ADD CONSTRAINT FK_Cast_Contract2 FOREIGN KEY(ContractId) REFERENCES dbo.Vertrag (VertragsNr) ON DELETE SET NULL')
END
GO

-- FK in vertragrolle entfernen
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Cast_ContractRole]') AND type = 'F')
BEGIN
	ALTER TABLE dbo.BesetzungTabelle DROP CONSTRAINT FK_Cast_ContractRole
END
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ContractRoleId' AND o.id = OBJECT_ID(N'[dbo].BesetzungTabelle'))
BEGIN
	ALTER TABLE BesetzungTabelle DROP COLUMN ContractRoleId
END
GO

-- 2013-08-23 sh
-- stored procedures zum entfernen der verbindung zw. besetzung und vertrag
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].NullifyCastReferencesToContract'))
BEGIN
	DROP PROCEDURE dbo.NullifyCastReferencesToContract
END
GO

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

	DECLARE @UserGroup int

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

GRANT EXECUTE ON NullifyCastReferencesToContract TO Public
GO

--Spalte für Anzahl Ensemble eingefügt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'EnsembleCount' and o.id = OBJECT_ID(N'dbo.BesetzungStdSoliTabelle'))
BEGIN
	ALTER TABLE dbo.BesetzungStdSoliTabelle ADD Fee FLOAT NULL
	ALTER TABLE dbo.BesetzungStdSoliTabelle ADD EnsembleCount INT NOT NULL CONSTRAINT DF_BesetzungStdSoliTabelle_EnsembleCount DEFAULT(0)
END 
GO

--TK2013-08-19
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ColumnSettings' AND o.id = OBJECT_ID('dbo.HDM'))
BEGIN
	ALTER TABLE dbo.HDM ADD ColumnSettings VARCHAR(4000)
END
GO

--2013-08-16 TH
-- Neuer View für ZeitkontenMonat für Berechtigungsprüfungen
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[ZeitkontenMonat_Update]'))
BEGIN
	DROP VIEW [dbo].[ZeitkontenMonat_Update]
END
GO

CREATE VIEW [dbo].[ZeitkontenMonat_Update]
AS 
SELECT * FROM ZeitkontenMonat WHERE zmID IN (
	SELECT ZM.zmId

	FROM ZeitkontenMonat AS ZM 
		INNER JOIN Vertrag AS V ON V.VertragsNr = ZM.VertragsNr
		INNER JOIN VertragPerso AS VP ON VP.VertragsNr = V.VertragsNr
		INNER JOIN AB ON AB.ABId = VP.ABId
		INNER JOIN Dienstplanarten AS DP ON DP.DienstplanArtenID = AB.DienstplanArtenID
		INNER JOIN UserGruppe AS UG ON 
			   (UG.GruppeID = V.ModulGruppeID AND UG.BerechtigungsbereichID = 1) 
			OR (UG.GruppeID = DP.ModulGruppeID AND UG.BerechtigungsbereichID = 5)
		INNER JOIN UserPw AS UP ON UP.UserID = UG.UserID
	WHERE UP.UserName = CURRENT_USER)
	WITH CHECK OPTION
GO
GRANT SELECT ON [dbo].[ZeitkontenMonat_Update] TO [public]
GRANT DELETE ON [dbo].[ZeitkontenMonat_Update] TO [public]
GRANT INSERT ON [dbo].[ZeitkontenMonat_Update] TO [public]
GRANT UPDATE ON [dbo].[ZeitkontenMonat_Update] TO [public]
GO

-- 2013-08-28 TH: 
-- Neue Spalte für XML-Settings im HDM-Layout
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ColumnSettings' AND o.id = OBJECT_ID('dbo.HDMVorlagen'))
BEGIN
	ALTER TABLE dbo.HDMVorlagen ADD ColumnSettings VARCHAR(4000)
END
GO

ALTER TABLE dbo.BodyMeasures DROP CONSTRAINT FK_BodyMeasures_BodyMeasureCategories
GO
ALTER TABLE dbo.BodyMeasures ADD CONSTRAINT FK_BodyMeasures_BodyMeasureCategories FOREIGN KEY
	(BodyMeasureCategoryId) REFERENCES dbo.BodyMeasureCategories (BodyMeasureCategoryId)  
GO
GRANT SELECT ON [dbo].ResourceObjects TO [public]
GRANT DELETE ON [dbo].ResourceObjects TO WorksWrite
GRANT INSERT ON [dbo].ResourceObjects TO WorksWrite
GRANT UPDATE ON [dbo].ResourceObjects TO WorksWrite
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'FixedColumnSettings' AND o.id = OBJECT_ID('dbo.HDMVorlagen'))
BEGIN
	ALTER TABLE dbo.HDMVorlagen ADD FixedColumnSettings VARCHAR(4000)
END
GO
--2013-09-12
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'OpusNumber' AND o.id = OBJECT_ID('dbo.WorkVersions'))
BEGIN
	ALTER TABLE dbo.WorkVersions ADD OpusNumber VARCHAR(10)
	ALTER TABLE dbo.WorkVersions ADD ISMN VARCHAR(10)
	ALTER TABLE dbo.Works ADD Tonality VARCHAR(20)
	ALTER TABLE dbo.WorkVersions ADD SetNumber VARCHAR(10)
	ALTER TABLE dbo.WorkVersions ADD OrderNumber VARCHAR(10) 
	ALTER TABLE dbo.WorkVersions ADD PurchaseNote TEXT
	ALTER TABLE dbo.PersonalDetails ADD DayOfDeath DATETIME
	--Ändern
	ALTER TABLE dbo.WorkVersions ALTER COLUMN CatalogNumber VARCHAR(20) 
	ALTER TABLE dbo.WorkVersions ALTER COLUMN AdditionalMaterial VARCHAR(4000)

END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].SetWorkVersionReferenceToProduction'))
BEGIN
	DROP PROCEDURE dbo.SetWorkVersionReferenceToProduction
END
GO
CREATE PROCEDURE [dbo].SetWorkVersionReferenceToProduction
	@productionId INT, @workVersionId INT
AS
BEGIN
	SET NOCOUNT ON
	UPDATE Stücke SET WorkVersionId = @workVersionId WHERE Snr = @productionId
END	
GRANT EXECUTE ON SetWorkVersionReferenceToProduction TO  WorksWrite 

GO
-- 2013-09-17 TH
-- Neue Tabellen für Checklisten

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CheckListTemplate]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.CheckListTemplate(
		CheckListTemplateId INT IDENTITY(1,1) NOT NULL,
		Name VARCHAR(250) NOT NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_CheckListTemplate PRIMARY KEY CLUSTERED (CheckListTemplateId) ON [PRIMARY],
) ON [PRIMARY]
END
GO
GRANT SELECT ON [dbo].CheckListTemplate TO [public]
GRANT DELETE ON [dbo].CheckListTemplate TO [Spielplan ändern]
GRANT INSERT ON [dbo].CheckListTemplate TO [Spielplan ändern]
GRANT UPDATE ON [dbo].CheckListTemplate TO [Spielplan ändern]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CheckListItemTemplate]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.CheckListItemTemplate(
		CheckListItemTemplateId INT IDENTITY(1,1) NOT NULL,
		CheckListTemplateId INT NOT NULL,
		MainCheckListItemTemplateId INT NULL,
		Sort INT NOT NULL CONSTRAINT DF_CheckListItemTemplate_Sort DEFAULT(0),
		Name VARCHAR(250) NOT NULL,
		[Description] VARCHAR(800) NULL,
		PersonId INT NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_CheckListItemTemplate PRIMARY KEY CLUSTERED (CheckListItemTemplateId) ON [PRIMARY],
		CONSTRAINT FK_CheckListItemTemplate_CheckListTemplate FOREIGN KEY(CheckListTemplateId) REFERENCES CheckListTemplate (CheckListTemplateId) ON DELETE CASCADE,
	) ON [PRIMARY]
END
GO
DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
IF @sql_server_version > 8 AND NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_CheckListItemTemplate_Person]') AND type = 'F')
BEGIN
	UPDATE CheckListItemTemplate SET PersonId = NULL WHERE PersonId IS NOT NULL AND NOT EXISTS (SELECT PersNr FROM PersH WHERE PersNr = PersonId)
	EXEC('ALTER TABLE dbo.CheckListItemTemplate WITH CHECK ADD CONSTRAINT FK_CheckListItemTemplate_Person FOREIGN KEY(PersonId) REFERENCES dbo.PersH (PersNr) ON DELETE SET NULL')
END
GO

GO
GRANT SELECT ON [dbo].CheckListItemTemplate TO [public]
GRANT DELETE ON [dbo].CheckListItemTemplate TO [Spielplan ändern]
GRANT INSERT ON [dbo].CheckListItemTemplate TO [Spielplan ändern]
GRANT UPDATE ON [dbo].CheckListItemTemplate TO [Spielplan ändern]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[CheckListItem]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.CheckListItem(
		CheckListItemId INT IDENTITY(1,1) NOT NULL,
		CheckListItemTemplateId INT NULL,
		MainCheckListItemId INT NULL,
		ProductionId INT NOT NULL,
		Sort INT NOT NULL CONSTRAINT DF_CheckListItem_Sort DEFAULT(0),
		[Status] INT NOT NULL CONSTRAINT DF_CheckListItem_Status DEFAULT(0),
		Available BIT NOT NULL CONSTRAINT DF_CheckListItem_Available DEFAULT(0), 
		Name VARCHAR(250) NOT NULL,
		[Description] VARCHAR(800) NULL,
		PersonId INT NULL,
		Note TEXT NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_CheckListItem PRIMARY KEY CLUSTERED (CheckListItemId) ON [PRIMARY],
	) ON [PRIMARY]
END
GO
DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
IF @sql_server_version > 8 AND NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_CheckListItem_CheckListItemTemplate]') AND type = 'F')
BEGIN
	UPDATE CheckListItem SET CheckListItemTemplateId = NULL WHERE CheckListItemTemplateId IS NOT NULL AND NOT EXISTS (SELECT CheckListItemTemplate.CheckListItemTemplateId FROM CheckListItemTemplate WHERE CheckListItem.CheckListItemTemplateId = CheckListItemTemplate.CheckListItemTemplateId)
	EXEC('ALTER TABLE dbo.CheckListItem WITH CHECK ADD CONSTRAINT FK_CheckListItem_CheckListItemTemplate FOREIGN KEY(CheckListItemTemplateId) REFERENCES dbo.CheckListItemTemplate (CheckListItemTemplateId) ON DELETE SET NULL')
END
IF @sql_server_version > 8 AND NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_CheckListItem_Person]') AND type = 'F')
BEGIN
	UPDATE CheckListItem SET PersonId = NULL WHERE PersonId IS NOT NULL AND NOT EXISTS (SELECT PersNr FROM PersH WHERE PersNr = PersonId)
	EXEC('ALTER TABLE dbo.CheckListItem WITH CHECK ADD CONSTRAINT FK_CheckListItem_Person FOREIGN KEY(PersonId) REFERENCES dbo.PersH (PersNr) ON DELETE SET NULL')
END
GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCheckListItem]'))
BEGIN
	DROP VIEW [dbo].AbCheckListItem
END
GO
CREATE VIEW [dbo].AbCheckListItem
AS 
SELECT  cli.*  FROM  CheckListItem  AS cli WHERE cli.ProductionId IN
	   (SELECT S.Snr
		FROM Stücke AS S 
			INNER JOIN UserGruppe ON S.ModuleGroupId = UserGruppe.GruppeID 
			INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 3)
WITH CHECK OPTION
GO
GRANT SELECT ON [dbo].AbCheckListItem TO [public]
GRANT DELETE ON [dbo].AbCheckListItem TO [public]
GRANT INSERT ON [dbo].AbCheckListItem TO [public]
GRANT UPDATE ON [dbo].AbCheckListItem TO [public]
GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCheckListItem_Update]'))
BEGIN
	DROP VIEW [dbo].AbCheckListItem_Update
END
GO
CREATE VIEW [dbo].AbCheckListItem_Update
AS 
SELECT  cli.*  FROM  CheckListItem  AS cli WHERE cli.ProductionId IN
	   (SELECT S.Snr
		FROM Stücke AS S 
			INNER JOIN UserGruppe ON S.ModuleGroupId = UserGruppe.GruppeID 
			INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 3 AND UserGruppe.Schreiben = 1)
WITH CHECK OPTION
GO
GRANT SELECT ON [dbo].AbCheckListItem_Update TO [public]
GRANT DELETE ON [dbo].AbCheckListItem_Update TO [public]
GRANT INSERT ON [dbo].AbCheckListItem_Update TO [public]
GRANT UPDATE ON [dbo].AbCheckListItem_Update TO [public]
GO
--TK 2013-09-25
GO
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ActivityTypeGroups]')  AND name = 'IX_ActivityTypeGroups_ActivityTypeId_GroupId')
BEGIN
	DELETE FROM ActivityTypeGroups  WHERE GroupId = -1
	DELETE FROM ActivityTypeGroups  WHERE ActivityTypeGroupId IN (SELECT MAX(ActivityTypeGroups.ActivityTypeGroupId) FROM ActivityTypeGroups Group BY ActivityTypeId, GroupId HAVING COUNT(*)> 1)
	DELETE FROM ActivityTypeGroups  WHERE ActivityTypeGroupId IN (SELECT MAX(ActivityTypeGroups.ActivityTypeGroupId) FROM ActivityTypeGroups Group BY ActivityTypeId, GroupId HAVING COUNT(*)> 1)
	CREATE UNIQUE NONCLUSTERED INDEX IX_ActivityTypeGroups_ActivityTypeId_GroupId ON dbo.ActivityTypeGroups
		(ActivityTypeId, GroupId) ON [PRIMARY]
END


GO
-- 2013-09-24 TH:
-- Neue Spalte für XML-Settings in Urlaubsberechnungsmodellen

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'XmlSettings' AND o.id = OBJECT_ID('dbo.UrlaubsberechnungsModell'))
BEGIN
	ALTER TABLE dbo.UrlaubsberechnungsModell ADD XmlSettings TEXT
END
GO

-- 2013-10-30 SH
-- AbContractConfirmations
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbContractConfirmations'))
BEGIN
DROP VIEW [dbo].[AbContractConfirmations]
END
GO

CREATE VIEW [dbo].[AbContractConfirmations]
AS 
SELECT
	cc.*
FROM ContractConfirmations cc
	INNER JOIN Vertrag AS v ON cc.ContractId = v.VertragsNr
	INNER JOIN	(SELECT GruppeID, Schreiben
						FROM			UserGruppe 
						INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
						WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 1
						AND ( OptionsFlag&1 = 1 OR OptionsFlag & 2 = 2 OR OptionsFlag&4 = 4)) AS UG
				ON v.ModulGruppeID = UG.GruppeID
GO
GRANT SELECT ON [AbContractConfirmations] TO public
GO
-- AbContractConfirmations_Update
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbContractConfirmations_Update'))
BEGIN
DROP VIEW [dbo].[AbContractConfirmations_Update]
END
GO
CREATE VIEW [dbo].[AbContractConfirmations_Update]
AS 
SELECT
	cc.*
FROM ContractConfirmations cc WHERE cc.ContractId IN (
	SELECT v.VertragsNr FROM Vertrag AS v 
	INNER JOIN	(SELECT 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)
WITH CHECK OPTION
GO

GRANT SELECT ON AbContractConfirmations_Update TO public
GRANT DELETE ON AbContractConfirmations_Update TO public
GRANT INSERT ON AbContractConfirmations_Update TO public
GRANT UPDATE ON AbContractConfirmations_Update TO public
GO

-- 2013-10-31 sh
-- AbContractDateConfirmations
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbContractDateConfirmations'))
BEGIN
DROP VIEW [dbo].[AbContractDateConfirmations]
END
GO

CREATE VIEW [dbo].[AbContractDateConfirmations]
AS 
SELECT
	cdc.*
FROM
	ContractDateConfirmations cdc
	INNER JOIN ContractConfirmations cc ON cdc.ContractConfirmationId = cc.ContractConfirmationId
	INNER JOIN Vertrag AS v ON cc.ContractId = v.VertragsNr
	INNER JOIN	(SELECT GruppeID, Schreiben
						FROM			UserGruppe 
						INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
						WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 1
						AND ( OptionsFlag&1 = 1 OR OptionsFlag & 2 = 2 OR OptionsFlag&4 = 4)) AS UG
				ON v.ModulGruppeID = UG.GruppeID
GO
GRANT SELECT ON [AbContractDateConfirmations] TO public
GO
-- AbContractDateConfirmations_Update
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbContractDateConfirmations_Update'))
BEGIN
DROP VIEW [dbo].[AbContractDateConfirmations_Update]
END
GO
CREATE VIEW [dbo].[AbContractDateConfirmations_Update]
AS 
SELECT
	cdc.*
FROM ContractDateConfirmations cdc
WHERE cdc.ContractConfirmationId IN (
	SELECT cc.ContractConfirmationId FROM ContractConfirmations cc
	INNER JOIN vertrag AS v ON cc.ContractId = v.VertragsNr
	INNER JOIN	(SELECT GruppeID, Schreiben
						FROM			UserGruppe 
						INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
						WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 1
						AND ( OptionsFlag&1 = 1 OR OptionsFlag&4 = 4)) AS UG
				ON v.ModulGruppeID = UG.GruppeID
WHERE UG.Schreiben = 1)
WITH CHECK OPTION
GO

GRANT SELECT ON AbContractDateConfirmations_Update TO public
GRANT DELETE ON AbContractDateConfirmations_Update TO public
GRANT INSERT ON AbContractDateConfirmations_Update TO public
GRANT UPDATE ON AbContractDateConfirmations_Update TO public
GO

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

CREATE VIEW [dbo].[AbContractDates]
AS 
SELECT
	cd.*
FROM  
	ContractDates cd
	INNER JOIN VertragRolle vr ON cd.ContractRoleId = vr.VRID
	INNER JOIN Vertrag v ON vr.VertragsNr = v.VertragsNr
	INNER JOIN	(SELECT GruppeID, Schreiben
						FROM			UserGruppe 
						INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
						WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 1) AS UG
				ON v.ModulGruppeID = UG.GruppeID
GO

GRANT SELECT ON [AbContractDates] TO public
GO

-- AbContractDates_Update
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbContractDates_Update'))
BEGIN
DROP VIEW [dbo].[AbContractDates_Update]
END
go
CREATE VIEW [dbo].[AbContractDates_Update]
AS 
SELECT
	cd.*
FROM  
	ContractDates cd
WHERE 
	cd.ContractRoleId IN (
	SELECT vr.VRID FROM VertragRolle vr
	INNER JOIN Vertrag v ON vr.VertragsNr = v.VertragsNr
	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 OR (OptionsFlag&4) = 4)) AS UG
				ON v.ModulGruppeID = UG.GruppeID
		WHERE UG.Schreiben = 1)
GO

GRANT SELECT ON [AbContractDates_Update] TO public
GRANT DELETE ON [AbContractDates_Update] TO public
GRANT INSERT ON [AbContractDates_Update] TO public
GRANT UPDATE ON [AbContractDates_Update] TO public
GO

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

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

GRANT SELECT ON [AbContractDateMaturities] TO public
GO

-- AbContractDateMaturities_Update
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbContractDateMaturities_Update'))
BEGIN
DROP VIEW [dbo].[AbContractDateMaturities_Update]
END
go
CREATE VIEW [dbo].[AbContractDateMaturities_Update]
AS 
SELECT
	cdm.*
FROM
	ContractDateMaturities cdm
WHERE 
	cdm.ContractDateId IN (
	SELECT cd.ContractDateId FROM
	ContractDates cd
	INNER JOIN VertragRolle vr ON cd.ContractRoleId = vr.VRID
	INNER JOIN Vertrag v ON vr.VertragsNr = v.VertragsNr
	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

GRANT SELECT ON [AbContractDateMaturities_Update] TO public
GRANT DELETE ON [AbContractDateMaturities_Update] TO public
GRANT INSERT ON [AbContractDateMaturities_Update] TO public
GRANT UPDATE ON [AbContractDateMaturities_Update] TO public
GO

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

CREATE VIEW [dbo].[AbContractTrackings]
AS 
SELECT
	ct.*
FROM
	ContractTracking ct
	INNER JOIN ContractConfirmations cc ON ct.ContractConfirmationId = cc.ContractConfirmationId
	INNER JOIN Vertrag v ON cc.ContractId = v.VertragsNr
	INNER JOIN	(SELECT GruppeID, Schreiben
						FROM			UserGruppe 
						INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
						WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 1 AND
						(OptionsFlag&2 = 2 OR OptionsFlag&4 = 4)) AS UG
				ON v.ModulGruppeID = UG.GruppeID
GO

GRANT SELECT ON [AbContractTrackings] TO public
GO

-- AbContractTrackings_Update
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbContractTrackings_Update'))
BEGIN
DROP VIEW [dbo].[AbContractTrackings_Update]
END
GO
CREATE VIEW [dbo].[AbContractTrackings_Update]
AS 
SELECT
	ct.*
FROM
	ContractTracking ct
WHERE 
	ct.ContractConfirmationId IN (
	SELECT cc.ContractConfirmationId FROM
	ContractConfirmations cc
	INNER JOIN Vertrag v ON cc.ContractId = v.VertragsNr
	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&4) = 4) AS UG
				ON v.ModulGruppeID = UG.GruppeID
		WHERE UG.Schreiben = 1)
GO

GRANT SELECT ON [AbContractTrackings_Update] TO public
GRANT DELETE ON [AbContractTrackings_Update] TO public
GRANT INSERT ON [AbContractTrackings_Update] TO public
GRANT UPDATE ON [AbContractTrackings_Update] TO public
GO

-- umwandlung berechtigungsgruppe in flags
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (
Major < 4 OR (Major = 4 AND (Minor < 135 OR (Minor = 135 AND Build < 110)))))
BEGIN
	
	-- honorarzugriff (1) bei vertragsdaten (1) wo momentan rolle honorar-daten lesen bzw. schreiben
	UPDATE UserGruppe SET OptionsFlag = OptionsFlag | 1 WHERE BerechtigungsbereichID = 1 AND UserID IN (
	(SELECT p.UserID FROM [dbo].[sysusers] AS u
	INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
	INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
	INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
	WHERE g.name = 'Honorar-Daten lesen' OR g.name = 'Honorar-Daten ändern' OR g.name = 'db_owner'))

	-- contracttracking lesen (2) bei vertragsdaten (1) wo momentan rolle contractrackingread
	UPDATE UserGruppe SET OptionsFlag = OptionsFlag | 2 WHERE BerechtigungsbereichID = 1 AND UserID IN (
	(SELECT p.UserID FROM [dbo].[sysusers] AS u
	INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
	INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
	INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
	WHERE g.name = 'ContractTrackingRead' OR g.name = 'db_owner'))

	-- contracttracking schreiben (4) bei vertragsdaten (1) wo momentan rolle contractrackingwrite
	UPDATE UserGruppe SET OptionsFlag = OptionsFlag | 4 WHERE BerechtigungsbereichID = 1 AND UserID IN (
	(SELECT p.UserID FROM [dbo].[sysusers] AS u
	INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
	INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
	INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
	WHERE g.name = 'ContractTrackingWrite' OR g.name = 'db_owner'))
END
GO

--TK 2013-10-25 Dienstplan in mehreren Abteilungen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IsMainWorkArea' AND o.id = OBJECT_ID('dbo.VertragPerso'))
BEGIN
ALTER TABLE dbo.Dienstplan DROP CONSTRAINT FK_Dienstplan_VertragPerso
ALTER TABLE dbo.ContractPartTimePeriods DROP CONSTRAINT FK_ContractPartTimePeriods_VertragPerso
ALTER TABLE dbo.TimeAccountUsage DROP CONSTRAINT FK_TimeAccountUsage_VertragPerso
ALTER TABLE dbo.VertragPerso DROP CONSTRAINT PK_VertragPerso

ALTER TABLE dbo.VertragPerso ADD
	ContractPersoId INT NOT NULL IDENTITY (1, 1),
	IsMainWorkArea BIT NULL,
	Start DATETIME NULL,
	[End] DATETIME NULL

ALTER TABLE dbo.VertragPerso ADD CONSTRAINT
	PK_VertragPerso PRIMARY KEY CLUSTERED 
	(ContractPersoId)  ON [PRIMARY]
	
CREATE NONCLUSTERED INDEX IX_VertragPerso ON dbo.VertragPerso
	(VertragsNr)  ON [PRIMARY]

CREATE UNIQUE NONCLUSTERED INDEX IX_OnlyOneMain ON dbo.VertragPerso
	(VertragsNr, IsMainWorkArea)  ON [PRIMARY]

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_RosterContract]') AND type = 'F')
ALTER TABLE dbo.Dienstplan  WITH CHECK ADD  CONSTRAINT FK_RosterContract FOREIGN KEY(VertragsNr)
REFERENCES dbo.Vertrag (VertragsNr)
ALTER TABLE dbo.Dienstplan CHECK CONSTRAINT FK_RosterContract

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_ContractPartTimePeriods_Contract]') AND type = 'F')
ALTER TABLE dbo.ContractPartTimePeriods  WITH CHECK ADD  CONSTRAINT FK_ContractPartTimePeriods_Contract FOREIGN KEY(ContractId)
REFERENCES dbo.Vertrag (VertragsNr) ON DELETE CASCADE
ALTER TABLE dbo.ContractPartTimePeriods CHECK CONSTRAINT FK_ContractPartTimePeriods_Contract

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_TimeAccountUsage_VertragPerso]') AND type = 'F')
ALTER TABLE dbo.TimeAccountUsage  WITH CHECK ADD  CONSTRAINT FK_TimeAccountUsage_VertragPerso FOREIGN KEY(ContractId)
REFERENCES dbo.Vertrag (VertragsNr) ON DELETE CASCADE
ALTER TABLE dbo.TimeAccountUsage CHECK CONSTRAINT FK_TimeAccountUsage_VertragPerso
Exec ('UPDATE VertragPerso SET IsMainWorkArea = 1')
Exec ('ALTER TABLE dbo.VertragPerso ADD CONSTRAINT
	CK_VertragPerso_IsMainWorkArea CHECK (IsMainWorkArea = 1 OR IsMainWorkArea IS NULL)')
END

GO

--TH 2013-11-07
--Wenn Version kleiner= ... 
--Update aller Artistic-Jahresvorträge in Monatswerte
--Auskommentiert, da dies eine Falsche Annahme war und echte Jahresvorträge nicht in Monatswerte umgewandelt werden dürfen (Die Formeln verwendet keine Monatswerte aus dem Aktuellen Zeitraum)
--IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (
--Major < 4 OR (Major = 4 AND (Minor < 136 OR (Minor = 136 AND Build < 1)))))
--BEGIN
--UPDATE ZeitkontenMonat SET ZmType = 1 WHERE zmId IN(
--SELECT ZMId FROM ZeitkontenMonat AS ZM 
--INNER JOIN Vertrag AS V ON V.VertragsNr = ZM.VertragsNr
--WHERE V.ModulGruppeID IN (SELECT GruppeId FROM Gruppe WHERE Modul <> 4) AND ZmType = 32
--)
--Print 'ZeitkontenMonat-Daten für Artisic Modules Aktualisiert'
--END

--TH-2013-11-20
-- Neue Schlüssel auf StückeTeil
DELETE FROM StückeTeil WHERE StückeTeilId IN(
SELECT StückeTEilID FROM StückeTeil AS ST
LEFT JOIN Stücke AS SP ON SP.Snr = ST.Snr
LEFT JOIN Stücke AS SC ON SC.Snr = ST.SnrTeil
WHERE SP.SNr IS NULL OR SC.Snr IS NULL
)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_StückeTeil_Stücke_Parent]') AND type = 'F')
BEGIN
ALTER TABLE [dbo].[StückeTeil]  WITH CHECK ADD  CONSTRAINT [FK_StückeTeil_Stücke_Parent] FOREIGN KEY(Snr)
REFERENCES [dbo].[Stücke] ([Snr]) ON DELETE CASCADE
ALTER TABLE [dbo].[StückeTeil]  WITH CHECK ADD  CONSTRAINT [FK_StückeTeil_Stücke_Child] FOREIGN KEY(SnrTeil)
REFERENCES [dbo].[Stücke] ([Snr])
CREATE UNIQUE NONCLUSTERED INDEX [StückeTeil_ParentChild] ON dbo.[StückeTeil]
	(
	Snr,
	SnrTeil
	) ON [PRIMARY]
END
GO

-- 2013-11-25 sh
-- setzen des statusfilter der planeinstellungen auf master wo nichts eingestellt ist
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 135 OR (Minor = 135 AND Build < 111)))))
BEGIN
	DECLARE @serverVersion INT
	SELECT @serverVersion = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
	--da der sql server 2000 kein varchar(max) kennt werden nur einstellungen aktualisiert die weniger als 8000 zeichen haben
	--nachdem sie gecastet wurden. der rest wurde abgeschnitten und somit sind die einstellungen keine gültigen xml strings mehr
	IF @serverVersion < 9
	BEGIN
		PRINT 'update plansettings sql2000'
		EXEC('UPDATE [Plan]
		SET Settings = REPLACE(CAST(Settings AS varchar(8000)), ''<StatusNames />'', ''<StatusNames><string>master</string></StatusNames>'')
		WHERE NOT Settings IS NULL AND LEN(CAST(Settings AS varchar(8000))) < 8000')
	END
	ELSE
	BEGIN
		PRINT 'update plansettings sql2005+'
		EXEC('UPDATE [Plan]
		SET Settings = REPLACE(CAST(Settings AS varchar(MAX)), ''<StatusNames />'', ''<StatusNames><string>master</string></StatusNames>'')
		 WHERE NOT Settings IS NULL')
	END
END
GO
--TK 2013-11-13
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IsManualEntry' AND o.id = OBJECT_ID('dbo.ZeitkontenMonat'))
BEGIN
	ALTER TABLE dbo.ZeitkontenMonat ADD IsManualEntry BIT NOT NULL CONSTRAINT DF_ZeitkontenMonat_IsManualEntry DEFAULT(0)
	--Auszahlungen die nicht auto sind markieren
	EXEC ('UPDATE dbo.ZeitkontenMonat SET IsManualEntry = 1 WHERE ZmType IN (2,8) AND Bem IS NULL ')
END
GO
-- 2013-11-28 TH
-- Stücke um eine Spalte für Format-Einstellungen erweitern
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'FormatSettings' AND o.id = OBJECT_ID('dbo.Stücke'))
BEGIN
	ALTER TABLE dbo.Stücke ADD FormatSettings VARCHAR(4000) NULL
END
GO

--2013-11-28 TH
-- Neue Tabelle für Produktionsattachments
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.ProductionAttachments') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.ProductionAttachments (
			ProductionAttachmentsId INT IDENTITY(1,1) NOT NULL,--ID
			ProductionId INT NOT NULL, 
			AttachmentId INT NOT NULL, 
			Note VARCHAR (255) NULL,
			Sort INT NOT NULL CONSTRAINT DF_ProductionAttachments_Sort DEFAULT(0),
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_ProductionAttachments PRIMARY KEY CLUSTERED (ProductionAttachmentsId ASC) ON [PRIMARY]
			CONSTRAINT FK_ProductionAttachments_Production FOREIGN KEY (ProductionId) REFERENCES dbo.Stücke (Snr),
			CONSTRAINT FK_ProductionAttachments_Attachment FOREIGN KEY (AttachmentId) REFERENCES dbo.[Attachments] (AttachmentId),
	) ON [PRIMARY]
	GRANT SELECT ON dbo.ProductionAttachments TO [Public]
	GRANT DELETE ON dbo.ProductionAttachments TO [Public]
	GRANT INSERT ON dbo.ProductionAttachments TO [Public]
	GRANT UPDATE ON dbo.ProductionAttachments TO [Public]
END
GO
--TK 2013-11-28
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IsSecret' AND o.id = OBJECT_ID('dbo.PersAdresse'))
BEGIN
	ALTER TABLE dbo.PersAdresse ADD IsSecret BIT NOT NULL CONSTRAINT DF_PersAdresse_IsSecret DEFAULT(0)

END
GO
		
ALTER VIEW [dbo].[ABPersAdresse]
	AS 
		SELECT 
			pa.AdressID, pa.PersNr, 
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission=0 THEN '**********' ELSE pa.[Str] END AS [Str],
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission=0 THEN '*****' ELSE pa.Plz END AS Plz,
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission=0 THEN '**********' ELSE pa.Ort END AS Ort,
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission=0 THEN '***' ELSE pa.Land END AS Land,
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission=0 THEN '**********' ELSE pa.co END AS Co,
			  pa.Sort, pa.AdrName, pa.IsSecret, pa.LM, pa.UM, pa.LC, pa.UC
		FROM PersAdresse  AS pa
			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 pa.PersNr = sub.PersonId

GO
GRANT SELECT ON AbPersAdresse TO public
GO

ALTER VIEW [dbo].[ABPersAdresse_Update]
AS
	SELECT 
		Pa.*
	FROM PersAdresse as Pa
	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
GRANT SELECT ON dbo.ABPersAdresse_Update TO [Public]
GRANT DELETE ON dbo.ABPersAdresse_Update TO [Public]
GRANT INSERT ON dbo.ABPersAdresse_Update TO [Public]
GRANT UPDATE ON dbo.ABPersAdresse_Update TO [Public]


GO

-- 2013-11-19 sh
--view zum schreiben für personalqualifikationen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbQualification_Person_Update'))
BEGIN
DROP VIEW [dbo].[AbQualification_Person_Update]
END
go
CREATE VIEW [dbo].[AbQualification_Person_Update]
AS 
SELECT
	qp.*
FROM
	Qualification_Person qp
WHERE 
	qp.PersonId IN (
	SELECT p.PersNr FROM PersH p
	INNER JOIN (SELECT DISTINCT GruppeID 
						FROM			UserGruppe 
						INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
						WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 0 AND (OptionsFlag&2) = 2) AS UG
				ON p.Besitzer = UG.GruppeID)
WITH CHECK OPTION
GO

GRANT SELECT ON [AbQualification_Person_Update] TO public
GRANT DELETE ON [AbQualification_Person_Update] TO public
GRANT INSERT ON [AbQualification_Person_Update] TO public
GRANT UPDATE ON [AbQualification_Person_Update] TO public
GO

-- setzen vom flag "qualifikationen schreiben" für mitglieder in "Soli-Daten ändern" und dbo
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 136 OR (Minor = 136 AND Build < 2)))))
BEGIN
	UPDATE UserGruppe SET OptionsFlag = OptionsFlag | 2 WHERE BerechtigungsbereichID = 0 AND UserID IN (
	(SELECT p.UserID FROM [dbo].[sysusers] AS u
	INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
	INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
	INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
	WHERE g.name = 'Soli-Daten ändern' OR g.name = 'db_owner'))
END
GO

--TK-2013-12-10 Referenz Stücke / Besitzer
UPDATE Stücke SET Stücke.ModuleGroupId = 1 WHERE ModuleGroupId NOT IN (SELECT GruppeID FROM Gruppe)
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Productions_Groups]') AND type = 'F')
BEGIN
	ALTER TABLE [dbo].[Stücke]  WITH CHECK ADD  CONSTRAINT [FK_Productions_Groups] FOREIGN KEY(ModuleGroupId)
	REFERENCES [dbo].Gruppe (GruppeID)  
	ALTER TABLE dbo.[Stücke] CHECK CONSTRAINT [FK_Productions_Groups]
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[AuffDienstplanArten]')  AND name = 'IX_ActivityDepartment_ActivityId')
CREATE INDEX IX_ActivityDepartment_ActivityId ON dbo.AuffDienstplanArten
	(AuffNr) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[AuffDienstplanArten]')  AND name = 'IX_ActivityDepartment_ActivityId_DepartmentId')
BEGIN
	DELETE FROM AuffDienstplanArten 
	WHERE AuffDienstplanArtenID IN (
		SELECT  MAX(ad.AuffDienstplanArtenID) 
		FROM dbo.AuffDienstplanArten as ad 
		GROUP BY ad.AuffNr, ad.DienstplanArtenID HAVING COUNT(*) > 0)

	DELETE FROM AuffDienstplanArten 
	WHERE AuffDienstplanArtenID IN (
		SELECT  MAX(ad.AuffDienstplanArtenID) 
		FROM dbo.AuffDienstplanArten as ad 
		GROUP BY ad.AuffNr, ad.DienstplanArtenID HAVING COUNT(*) > 0)

CREATE UNIQUE NONCLUSTERED INDEX IX_ActivityDepartment_ActivityId_DepartmentId ON dbo.AuffDienstplanArten
	(AuffNr, DienstplanArtenID)  ON [PRIMARY]
END
GO

--TK 2013-12 Aushilfen an das Ende sortieren
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'InfoCode' AND o.id = OBJECT_ID('dbo.VertragsVorlagen'))
BEGIN
	ALTER TABLE dbo.VertragsVorlagen ADD InfoCode VARCHAR(3) NULL
	ALTER TABLE dbo.VertragsVorlagen ADD TemporaryOrderNumber INT NOT NULL CONSTRAINT DF_ContractType_OrderNumber DEFAULT(0)
	UPDATE VertragPerso 
	SET PersSort = PersSort + 1000 
	WHERE PersSort < 1000 AND  VertragsNr IN (
		SELECT V.VertragsNr fROM Vertrag AS V INNER JOIN VertragsVorlagen AS CT ON V.VorlagenID = CT.VorlagenID WHERE CT.Module IN (2,16) AND CT.VArt < 255 ) 
END
GO


--TK 2013-12-20  Precedure zum löschen von Gruppen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DeleteGroup'))
BEGIN
DROP PROCEDURE[dbo].DeleteGroup
END
GO
CREATE PROCEDURE [dbo].DeleteGroup 
	@Id INT
AS

BEGIN
	SET NOCOUNT ON

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

	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Contacts'		FROM PersH			WHERE  Besitzer = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Productions'	FROM Stücke			WHERE  ModuleGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Contracts'	FROM Vertrag		WHERE  ModulGruppeID = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Roles'		FROM Besetzungstd	WHERE  Besitzer = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Departments'	FROM DienstplanArtenTabelle WHERE  ModulGruppeID = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Tours'		FROM Tours WHERE OwnerId = @id

	IF NOT EXISTS (SELECT * FROM  #Msg) 
		BEGIN
			DELETE FROM UserGruppe WHERE GruppeID = @id
			DELETE FROM PersonModulGroupPermission WHERE ModulGroupId = @id
			DELETE FROM CostCenter_OwnerGroup WHERE OwnerGroupId = @id
			DELETE FROM ActivityTypeGroups WHERE GroupId = @id
			DELETE FROM Gruppe WHERE GruppeID = @id
		END
	
	SELECT * FROM #Msg
END

GRANT EXECUTE ON DeleteGroup TO  SecurityAdmin 
GO

--TK 2013-12-20 Referenzen
DECLARE @sql_server_version INTEGER
SELECT @sql_server_version = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
IF @sql_server_version > 8 AND NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Bonus_TimeAccount]') AND type = 'F')
BEGIN
	UPDATE Zulagen SET ZeitKtoNr = NULL WHERE ZeitKtoNr NOT IN (SELECT ZeitKtoNr FROM Zeitkonten)
	EXEC('ALTER TABLE dbo.Zulagen WITH CHECK ADD CONSTRAINT FK_Bonus_TimeAccount FOREIGN KEY(ZeitKtoNr) REFERENCES dbo.Zeitkonten (ZeitKtoNr) ON DELETE SET NULL')

	UPDATE [Status] SET TimeAccountId = NULL WHERE TimeAccountId NOT IN (SELECT ZeitKtoNr FROM Zeitkonten)
	EXEC('ALTER TABLE dbo.[Status] WITH CHECK ADD CONSTRAINT FK_Status_TimeAccount FOREIGN KEY(TimeAccountId) REFERENCES dbo.Zeitkonten (ZeitKtoNr) ON DELETE SET NULL')
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IsCreditAccount' AND o.id = OBJECT_ID('dbo.Zeitkonten'))
BEGIN
	ALTER TABLE dbo.Zeitkonten ADD IsCreditAccount BIT NOT NULL CONSTRAINT DF_TimeAccount_IsCreditAccount DEFAULT(0)

	UPDATE CostUnit SET CostUnitType = 0 WHERE CostUnitType IN (1, 2)
	--CostUnitId u BudgetItemId Nullable
	ALTER TABLE dbo.CashCommandPos ALTER COLUMN BudgetItemId INT NULL
	ALTER TABLE dbo.CashCommandPos ALTER COLUMN CostUnitId INT NULL
END


GO

-- 2013-12-11 TH:
-- Neue Spalte für den Standardstatus für Aktivitäten
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'DefaultActivityStatus' AND o.id = OBJECT_ID('dbo.Gruppe'))
BEGIN
	ALTER TABLE dbo.Gruppe ADD DefaultActivityStatus INT NOT NULL CONSTRAINT DF_Gruppe_DefaultActivityStatus DEFAULT(10)
END
GO

-- 2013-12-18 TH:
-- Neue Spalte für den Besitzer eines Plans
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'OwnerId' AND o.id = OBJECT_ID('dbo.Plan'))
BEGIN
	ALTER TABLE [Plan] ADD [OwnerId] INT NOT NULL CONSTRAINT DF_Plan_OwnerId DEFAULT(1)

	DELETE FROM UserGruppe WHERE BerechtigungsbereichID = 11
	INSERT INTO [dbo].[UserGruppe]
           ([GruppeID]
           ,[UserID]
           ,[Schreiben]
           ,[LM]
           ,[UM]
           ,[LC]
           ,[UC]
           ,[BerechtigungsbereichID]
           ,[OptionsFlag]
           ,[IsInherited]
           ,[Options])
     SELECT GruppeID, UserID, 1, GETDATE(), 1, GETDATE(),1,11,0, 0,NULL
FROM Gruppe
CROSS JOIN UserPW
WHERE GruppeID IN (SELECT GruppeID FROM Gruppe WHERE Modul = 1) AND IsInactive = 0 AND UserID IN
(SELECT p.UserID FROM [dbo].[sysusers] AS u
	INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
	INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
	INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
	WHERE g.name = 'VorlagenSchreiben' OR g.name = 'db_owner')
END
GO

-- 2013-12-19 TH:
-- Neue Spalte in RoleSeason, die angibt, ob die Rolle in einer bestimmten Spielzeit nicht verwendet wird.
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'RoleNotNeeded' AND o.id = OBJECT_ID('dbo.Role_Season'))
BEGIN
	ALTER TABLE Role_Season ADD RoleNotNeeded BIT NOT NULL CONSTRAINT DF_Role_Season_RoleNotNeeded DEFAULT(0)
END
GO
GRANT SELECT ON [dbo].[Role_Season] TO [public]
GO

-- 2013-12-23 TH:
-- Neue Spalte in ProductionDepartmentInfo, die angibt, in welcher Spielzeit die Daten verwendet werden.
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'SeasonId' AND o.id = OBJECT_ID('dbo.StückeDienstplan'))
BEGIN
	ALTER TABLE StückeDienstplan ADD SeasonId INT NULL CONSTRAINT [FK_StückeDienstplan_Spielzeit] FOREIGN KEY(SeasonId)
	REFERENCES [dbo].SpielzeitTabelle (Spznr)  
END
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'WertText' AND o.id = OBJECT_ID(N'[dbo].Settings') AND c.prec < 7000  AND c.prec > -1)
BEGIN
	DECLARE @serverVersion INT
	SELECT @serverVersion = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
	IF @serverVersion < 9
	BEGIN
		PRINT 'sql2000'
		EXEC('ALTER TABLE Settings ALTER COLUMN WertText VARCHAR(7000)')
	END
	ELSE
	BEGIN
		PRINT 'sql2005+'
		EXEC('ALTER TABLE Settings ALTER COLUMN WertText VARCHAR(MAX)')
	END
END
GO

-- 2014-01-31 sh
-- FK zw. Kassenanordnungespositionen und Steuern
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_CashCommandPos_Taxes]') AND type = 'F')
BEGIN
	ALTER TABLE [dbo].[CashCommandPos] WITH CHECK ADD CONSTRAINT FK_CashCommandPos_Taxes
	FOREIGN KEY([TaxId]) REFERENCES [dbo].[Taxes] ([TaxId])
END
GO

--2014-01-16 TH
-- Neue Tabelle für TourStatus und TourStatusValidation
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.TourStatus') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.TourStatus (
			TourStatusId INT IDENTITY(1,1) NOT NULL,--ID
			Name VARCHAR(50) NOT NULL,
			ShortName VARCHAR(15) NOT NULL,
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_TourStatus PRIMARY KEY CLUSTERED (TourStatusId ASC) ON [PRIMARY]
	) ON [PRIMARY]
	--TODO: Berechtigung prüfen
	GRANT SELECT ON dbo.TourStatus TO [Public]
	GRANT DELETE ON dbo.TourStatus TO [Public]
	GRANT INSERT ON dbo.TourStatus TO [Public]
	GRANT UPDATE ON dbo.TourStatus TO [Public]

	SET IDENTITY_INSERT TourStatus ON
	INSERT INTO TourStatus (TourStatusId, Name, ShortName, LC, UC, LM, UM) VALUES (0, 'Neu', 'Neu', GETDATE(), 0, GETDATE(), 0)
	INSERT INTO TourStatus (TourStatusId, Name, ShortName, LC, UC, LM, UM) VALUES (1, 'Validiert', 'Val', GETDATE(), 0, GETDATE(), 0)
	SET IDENTITY_INSERT TourStatus OFF
	DECLARE @country VARCHAR(20)
	SELECT @country = WertText FROM Settings WHERE Form = 'Adresse' AND Control = 'Country'
	IF @country <> 'DE' AND @country <> ''
	BEGIN--alle nicht deutschen bekommen eine Englische bezeichnung
		UPDATE TourStatus SET Name = 'New', ShortName = 'New' WHERE [TourStatusId] = 0
		UPDATE TourStatus SET Name = 'Validated', ShortName = 'Val' WHERE [TourStatusId] = 1
	END
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.TourValidationStatus') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.TourValidationStatus (
			TourValidationStatusId INT IDENTITY(1,1) NOT NULL,--ID
			TourStatusId INT NOT NULL,
			GroupId INT NOT NULL,
			OwnerGroupId INT NOT NULL,
			MailingListId INT NULL,
			Sort INT NOT NULL CONSTRAINT DF_TourValidationStatus_Sort DEFAULT(0),
			IsEditable BIT NOT NULL CONSTRAINT DF_TourValidationstatus_IsEditable DEFAULT(0),
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_TourValidationStatus PRIMARY KEY CLUSTERED (TourValidationStatusId ASC) ON [PRIMARY]
			CONSTRAINT [FK_TourValidationStatus_TourStatus] FOREIGN KEY(TourStatusId) REFERENCES dbo.[TourStatus] (TourStatusId) ON DELETE CASCADE,
			CONSTRAINT [FK_TourValidationStatus_UserPw] FOREIGN KEY(GroupId) REFERENCES dbo.[UserPw] (UserId) ON DELETE CASCADE,
			CONSTRAINT [FK_TourValidationStatus_OwnerGroup] FOREIGN KEY(OwnerGroupId) REFERENCES dbo.[Gruppe] (GruppeId) ON DELETE CASCADE,
			CONSTRAINT [FK_TourValidationStatus_MailingList] FOREIGN KEY(MailingListId) REFERENCES dbo.[Verteiler] (VerteilerId),
	) ON [PRIMARY]
	--TODO: Berechtigung prüfen
	GRANT SELECT ON dbo.TourValidationStatus TO [Public]
	GRANT DELETE ON dbo.TourValidationStatus TO [Public]
	GRANT INSERT ON dbo.TourValidationStatus TO [Public]
	GRANT UPDATE ON dbo.TourValidationStatus TO [Public]
END
GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.TourValidationStatus') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.TourValidationStatus (
			TourValidationStatusId INT IDENTITY(1,1) NOT NULL,--ID
			TourStatusId INT NOT NULL,
			GroupId INT NOT NULL,
			OwnerGroupId INT NOT NULL,
			MailingListId INT NULL,
			Sort INT NOT NULL CONSTRAINT DF_TourValidationStatus_Sort DEFAULT(0),
			IsEditable BIT NOT NULL CONSTRAINT DF_TourValidationstatus_IsEditable DEFAULT(0),
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_TourValidationStatus PRIMARY KEY CLUSTERED (TourValidationStatusId ASC) ON [PRIMARY]
			CONSTRAINT [FK_TourValidationStatus_TourStatus] FOREIGN KEY(TourStatusId) REFERENCES dbo.[TourStatus] (TourStatusId) ON DELETE CASCADE,
			CONSTRAINT [FK_TourValidationStatus_UserPw] FOREIGN KEY(GroupId) REFERENCES dbo.[UserPw] (UserId) ON DELETE CASCADE,
			CONSTRAINT [FK_TourValidationStatus_OwnerGroup] FOREIGN KEY(OwnerGroupId) REFERENCES dbo.[Gruppe] (GruppeId) ON DELETE CASCADE,
			CONSTRAINT [FK_TourValidationStatus_MailingList] FOREIGN KEY(MailingListId) REFERENCES dbo.[Verteiler] (VerteilerId),
	) ON [PRIMARY]
	--TODO: Berechtigung prüfen
	GRANT SELECT ON dbo.TourValidationStatus TO [Public]
	GRANT DELETE ON dbo.TourValidationStatus TO [Public]
	GRANT INSERT ON dbo.TourValidationStatus TO [Public]
	GRANT UPDATE ON dbo.TourValidationStatus TO [Public]
END
GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.YearCloseTypes') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN

	CREATE TABLE dbo.YearCloseTypes (
			YearCloseTypeId INT IDENTITY(1,1) NOT NULL,--ID
			Name VARCHAR(50) NOT NULL,
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_YearCloseTypes PRIMARY KEY CLUSTERED (YearCloseTypeId ASC) ON [PRIMARY]
	) ON [PRIMARY]
	--TODO: Berechtigung prüfen
	GRANT SELECT ON dbo.YearCloseTypes TO [Public]
	GRANT DELETE ON dbo.YearCloseTypes TO PersoAdmin
	GRANT INSERT ON dbo.YearCloseTypes TO PersoAdmin
	GRANT UPDATE ON dbo.YearCloseTypes TO PersoAdmin


	SET IDENTITY_INSERT YearCloseTypes ON
		INSERT INTO YearCloseTypes (YearCloseTypeId, Name, LC, UC, LM, UM) VALUES (10,'Urlaub', GETDATE(), 0, GETDATE(), 0) 
		INSERT INTO YearCloseTypes (YearCloseTypeId, Name, LC, UC, LM, UM)  VALUES (25,'Frei', GETDATE(), 0, GETDATE(), 0) 
		INSERT INTO YearCloseTypes (YearCloseTypeId, Name, LC, UC, LM, UM)  VALUES (52,'Überstunden', GETDATE(), 0, GETDATE(), 0) 
		INSERT INTO YearCloseTypes (YearCloseTypeId, Name, LC, UC, LM, UM)  VALUES (60,'Dienste', GETDATE(), 0, GETDATE(), 0) 
	SET IDENTITY_INSERT YearCloseTypes OFF
	
	ALTER TABLE Zeitkonten ADD YearCloseTypeId INT NULL
	ALTER TABLE Jahresabschluss ADD YearCloseTypeId INT NULL
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_TimeAccount_YearCloseTypes]') AND type = 'F')
BEGIN
	
	UPDATE Zeitkonten SET YearCloseTypeId = CASE WHEN Formel = 3050 THEN 25 WHEN Formel = 4000 THEN 60 WHEN Formel = 3010 OR  Formel = 3013 THEN 10 ELSE 52 END
	ALTER TABLE Zeitkonten ALTER COLUMN  YearCloseTypeId INT NOT NULL

	ALTER TABLE [dbo].Zeitkonten  WITH CHECK ADD  CONSTRAINT [FK_TimeAccount_YearCloseTypes] FOREIGN KEY(YearCloseTypeId)
	REFERENCES [dbo].YearCloseTypes (YearCloseTypeId)  
	ALTER TABLE dbo.Zeitkonten CHECK CONSTRAINT [FK_TimeAccount_YearCloseTypes]

	EXEC ('UPDATE Jahresabschluss SET YearCloseTypeId = CASE WHEN Formel = 3050 THEN 25 WHEN Formel = 4000 THEN 60 WHEN Formel = 3010 OR  Formel = 3013 THEN 10 ELSE 52 END FROM Jahresabschluss INNER JOIN Zeitkonten ON  Jahresabschluss.ZeitKtoNr = Zeitkonten.ZeitKtoNr')
	ALTER TABLE Jahresabschluss ALTER COLUMN  YearCloseTypeId INT NOT NULL

	ALTER TABLE [dbo].Jahresabschluss  WITH CHECK ADD  CONSTRAINT [FK_YearClose_YearCloseTypes] FOREIGN KEY(YearCloseTypeId)
	REFERENCES [dbo].YearCloseTypes (YearCloseTypeId)  
	ALTER TABLE dbo.Jahresabschluss CHECK CONSTRAINT [FK_YearClose_YearCloseTypes]
	ALTER TABLE Jahresabschluss DROP CONSTRAINT [FK_ClosePeriod_TimeAccount]
	ALTER TABLE Jahresabschluss DROP COLUMN ZeitKtoNr

END


GO
--TK 2014-01
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'FormatSettings' AND o.id = OBJECT_ID('dbo.RingBez'))
BEGIN
	ALTER TABLE dbo.RingBez ADD FormatSettings VARCHAR(4000) NULL
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'Unit' AND o.id = OBJECT_ID('dbo.Currency'))
BEGIN
	ALTER TABLE dbo.Currency ADD Unit INT NOT NULL CONSTRAINT DF_Currency_Unit DEFAULT(0)
END

GO
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].AdressPlan') AND c.prec < 50)
BEGIN
	UPDATE AdressPlan SET BEZ = AdressPlanID WHERE Bez IS NULL
	ALTER TABLE AdressPlan ALTER COLUMN Bez VARCHAR(50) NOT NULL
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.CostTypes') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN

	CREATE TABLE dbo.CostTypes (
			CostTypeId INT IDENTITY(1,1) NOT NULL,--ID
			Name VARCHAR(50) NOT NULL,
			CostTypeCategory INT NOT NULL  CONSTRAINT DF_CostType_CostTypeCategory DEFAULT(0), 
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_CostTypes PRIMARY KEY CLUSTERED (CostTypeId ASC) ON [PRIMARY]
	) ON [PRIMARY]
	GRANT SELECT ON dbo.CostTypes TO [Public]
	GRANT DELETE ON dbo.CostTypes TO CostsWrite
	GRANT INSERT ON dbo.CostTypes TO CostsWrite
	GRANT UPDATE ON dbo.CostTypes TO CostsWrite


	SET IDENTITY_INSERT CostTypes ON
	INSERT INTO CostTypes (CostTypeId, Name, LC, UC, LM, UM) VALUES (1, 'Personalkosten',  GETDATE(), 0, GETDATE(), 0)
	SET IDENTITY_INSERT CostTypes OFF

END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'BudgetItemId' AND o.id = OBJECT_ID('dbo.Budgets'))
BEGIN
	ALTER TABLE Budgets ALTER COLUMN CostUnitId INT NULL

	ALTER TABLE Budgets ADD BudgetItemId INT NULL
	ALTER TABLE [dbo].Budgets  WITH CHECK ADD  CONSTRAINT [FK_Budgets_BudgetItem] FOREIGN KEY(BudgetItemId)
		REFERENCES [dbo].BudgetItem (BudgetItemId)  

	ALTER TABLE Budgets ADD CostTypeId INT NULL
	ALTER TABLE [dbo].Budgets  WITH CHECK ADD  CONSTRAINT [FK_Budgets_ CostType] FOREIGN KEY(CostTypeId)
		REFERENCES [dbo].CostTypes (CostTypeId) 
		EXEC ('UPDATE Budgets SET CostTypeId = 1')

	ALTER TABLE Budgets ALTER COLUMN  CostTypeId INT NOT NULL

	ALTER TABLE BudgetItem ADD CostTypeId INT NULL
	ALTER TABLE [dbo].BudgetItem  WITH CHECK ADD  CONSTRAINT [FK_BudgetItem_CostTypeId] FOREIGN KEY(CostTypeId)
		REFERENCES [dbo].CostTypes (CostTypeId)  

	ALTER TABLE Budgets ADD  ReserveBudgetValue FLOAT NOT NULL CONSTRAINT DF_Budgets_ReserveBudgetValue DEFAULT (0)
		
	EXEC ('ALTER TABLE dbo.Budgets ADD CONSTRAINT
		CK_Budgets_BudgetReserveValue CHECK (BudgetValue >= ReserveBudgetValue)')

	ALTER TABLE Budgets ADD IsInactive BIT NOT NULL CONSTRAINT DF_Budgets_IsInactive DEFAULT (0)
END

GO
IF (SELECT c.cdefault FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id
	WHERE c.name = 'Pl' AND o.id = OBJECT_ID(N'dbo.AufführgTabelle')) <> 0
	EXECUTE sp_unbindefault N'dbo.AufführgTabelle.PL'
GO

--TK 2014-02
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.ContractBonus') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.ContractBonus (
			ContractBonusId INT IDENTITY(1,1) NOT NULL,--ID
			ContractId INT NOT NULL,
			BonusId INT NOT NULL,
			FixBonusValue MONEY NULL,
			Note VARCHAR(250),
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_ContractBonus PRIMARY KEY CLUSTERED (ContractBonusId ASC) ON [PRIMARY]
			CONSTRAINT [FK_ContractBonus_Contact] FOREIGN KEY(ContractId) REFERENCES dbo.Vertrag (VertragsNr) ON DELETE CASCADE,
			CONSTRAINT [FK_ContractBonus_Bonus] FOREIGN KEY(BonusId) REFERENCES dbo.Zulagen (ZulagenNr),
			CONSTRAINT [UQ_ContractId_BonusId] UNIQUE NONCLUSTERED (ContractId, BonusId) ON [PRIMARY]	
	) ON [PRIMARY]


	UPDATE UserGruppe SET OptionsFlag = 1 WHERE BerechtigungsbereichID = 4 AND UserID IN (
		(SELECT p.UserID FROM [dbo].[sysusers] AS u
			INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
			INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
			INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
		WHERE g.name = 'Spielplan alles lesen' OR g.name = 'db_owner'))
END
GO

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

CREATE VIEW [dbo].AbContractBonus
AS 
SELECT v.* FROM  ContractBonus AS v  
	INNER  JOIN	
		(	SELECT Vertrag.VertragsNr 
			FROM Vertrag INNER JOIN  UserGruppe ON Vertrag.ModulGruppeID = UserGruppe.GruppeID
				INNER JOIN	UserPW ON UserGruppe.Userid = UserPW.Userid 
			WHERE Username = CURRENT_USER AND BerechtigungsbereichID IN (1, 4, 5) --Vertrag, Besetzung, Dienstplan
		) AS UG	ON v.ContractId = UG.VertragsNr

GO
GRANT SELECT ON AbContractBonus TO public
GO


GRANT SELECT ON [dbo].Role_Season TO Public

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

CREATE VIEW [dbo].AbContractBonus_Update
AS 
SELECT v.* FROM  ContractBonus AS v  
	INNER  JOIN	
		(	SELECT Vertrag.VertragsNr 
			FROM Vertrag INNER JOIN  UserGruppe ON Vertrag.ModulGruppeID = UserGruppe.GruppeID
				INNER JOIN	UserPW ON UserGruppe.Userid = UserPW.Userid 
			WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 1 AND UserGruppe.Schreiben = 1
		) AS UG	ON v.ContractId = UG.VertragsNr
GO

GRANT SELECT ON AbContractBonus_Update TO public
GRANT DELETE ON AbContractBonus_Update TO public
GRANT INSERT ON AbContractBonus_Update TO public
GRANT UPDATE ON AbContractBonus_Update TO public
GO

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

GO
CREATE VIEW [dbo].[AbBesetzungStdSoli]
	AS
	SELECT      S.*
	FROM        BesetzungStdSoliTabelle AS S 
					INNER JOIN BesetzungStd AS R ON S.RolleID = R.Id
					INNER JOIN Gruppe AS G ON R.Besitzer = G.GruppeID
					INNER JOIN UserGruppe AS Ug ON G.GruppeID = Ug.GruppeID   
					INNER JOIN UserPW ON Ug.Userid  = UserPW.Userid 
	WHERE BerechtigungsbereichID = 4 AND (S.Gesperrt = 0 OR (Ug.OptionsFlag&1 = 1)) AND UserPW.Username = CURRENT_USER
GO
GRANT SELECT ON [dbo].[AbBesetzungStdSoli] TO Public
GO

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

CREATE VIEW [dbo].[AbBesetzungStdSoli_Update]
	AS
	SELECT      S.*
	FROM        BesetzungStdSoliTabelle AS S 
	WHERE S.BesetzungStdSoliID IN(
	SELECT BesetzungStdSoliID FROM BesetzungStdSoliTabelle
					INNER JOIN BesetzungStd AS R ON BesetzungStdSoliTabelle.RolleID = R.Id
					INNER JOIN Gruppe AS G ON R.Besitzer = G.GruppeID
					INNER JOIN UserGruppe AS Ug ON G.GruppeID = Ug.GruppeID   
					INNER JOIN UserPW ON Ug.Userid  = UserPW.Userid 
					WHERE ug.BerechtigungsbereichID = 4 AND ug.Schreiben = 1  AND UserPW.Username = CURRENT_USER)
	--Bei Schreibrechten keine Prüfung auf gesperrt
	WITH CHECK OPTION

GO
GRANT SELECT ON [dbo].[AbBesetzungStdSoli_Update]   TO Public
GRANT DELETE ON [dbo].[AbBesetzungStdSoli_Update]   TO Public
GRANT INSERT ON [dbo].[AbBesetzungStdSoli_Update]   TO Public
GRANT UPDATE ON [dbo].[AbBesetzungStdSoli_Update]   TO Public
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[CastPublic]'))	DROP VIEW [dbo].[CastPublic]

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

GO
CREATE VIEW [dbo].[AbCast]
AS
	SELECT	ca.*
	FROM    BesetzungTabelle		AS ca 
		LEFT JOIN BesetzungStd		AS ro ON ca.RolleID = ro.ID
		INNER JOIN Gruppe            AS g  ON g.GruppeID = ro.Besitzer	
		INNER JOIN UserGruppe AS Ug ON G.GruppeID = Ug.GruppeID   
		INNER JOIN UserPW ON Ug.Userid  = UserPW.Userid 
	WHERE (BerechtigungsbereichID = 4 AND  (ca.Gesperrt = 0 OR (Ug.OptionsFlag&1 = 1)) AND UserPW.Username = CURRENT_USER) OR ca.RolleId IS NULL
	GO
GRANT SELECT ON [dbo].AbCast   TO Public
GO


IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCast_Update]')) DROP VIEW [dbo].[AbCast_Update]
GO
CREATE VIEW [dbo].[AbCast_Update]
AS
		SELECT   C.*
	FROM  BesetzungTabelle		AS C 
	WHERE RolleID IS NULL OR RolleId IN (
	
	SELECT ID FROM BesetzungStd		AS Ro
		INNER JOIN Gruppe           AS g  ON g.GruppeID = ro.Besitzer	
		INNER JOIN UserGruppe		AS Ug ON G.GruppeID = Ug.GruppeID   
		INNER JOIN UserPW				  ON Ug.Userid  = UserPW.Userid 
	WHERE (BerechtigungsbereichID = 4 OR BerechtigungsbereichID = 2) AND  schreiben <> 0 AND UserPW.Username = CURRENT_USER)
	
WITH CHECK OPTION
GO
GRANT SELECT ON [dbo].[AbCast_Update]   TO Public
GRANT DELETE ON [dbo].[AbCast_Update]   TO Public
GRANT INSERT ON [dbo].[AbCast_Update]   TO Public
GRANT UPDATE ON [dbo].[AbCast_Update]   TO Public


GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCastBonus_Update]'))	DROP VIEW [dbo].AbCastBonus_Update
GO
CREATE VIEW [dbo].AbCastBonus_Update
AS
	SELECT   CB.*
		FROM  CastBonus		AS CB 
		WHERE cb.CastId  IN (
		SELECT c.ID FROM BesetzungTabelle		AS C 
			INNER JOIN Vertrag		AS Co ON c.ContractId = Co.Vertragsnr
			INNER JOIN Gruppe           AS g  ON g.GruppeID = Co.ModulGruppeID	
			INNER JOIN UserGruppe		AS Ug ON G.GruppeID = Ug.GruppeID   
			INNER JOIN UserPW				  ON Ug.Userid  = UserPW.Userid 
		WHERE BerechtigungsbereichID = 1 AND  schreiben <> 0 AND (OptionsFlag&1 = 1) AND UserPW.Username = CURRENT_USER)
	--Es kann nur 
WITH CHECK OPTION
GO
GRANT SELECT ON [dbo].AbCastBonus_Update   TO Public
GRANT DELETE ON [dbo].AbCastBonus_Update   TO Public
GRANT INSERT ON [dbo].AbCastBonus_Update   TO Public
GRANT UPDATE ON [dbo].AbCastBonus_Update   TO Public
GO

--Änderung AbCastBonus 
--2014-05-21 SH
--prüfung auf besitzer der verträge wenn besetzung vertrag hat, sonst auf besitzer der person
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCastBonus]'))	DROP VIEW [dbo].AbCastBonus
GO
CREATE VIEW [dbo].AbCastBonus
AS
	SELECT   CB.*
		FROM  CastBonus		            AS CB 
			INNER JOIN BesetzungTabelle AS C   ON  cb.CastId = C.Id
			INNER JOIN Vertrag          AS Co  ON c.ContractId = Co.Vertragsnr
			INNER JOIN UserGruppe       AS Ug  ON Co.ModulGruppeID = Ug.GruppeID   
			INNER JOIN UserPW           AS UPW ON Ug.Userid  = UPW.Userid 

		WHERE
			Ug.BerechtigungsbereichID = 1
			AND  (Ug.OptionsFlag&1 = 1)
			AND UPW.Username = CURRENT_USER
	UNION
	SELECT   CB.*
		FROM  CastBonus		            AS CB 
			INNER JOIN BesetzungTabelle AS C   ON  cb.CastId = C.Id
			INNER JOIN PersH            AS P   ON C.PersNr = P.PersNr
			INNER JOIN UserGruppe       AS Ug  ON P.Besitzer = Ug.GruppeID   
			INNER JOIN UserPW           AS UPW ON Ug.Userid  = UPW.Userid 
		WHERE
			c.ContractId IS NULL
			AND Ug.BerechtigungsbereichID = 1
			AND (Ug.OptionsFlag&1 = 1)
			AND UPW.Username = CURRENT_USER 
GO

GRANT SELECT ON [dbo].AbCastBonus   TO Public
GO

--update verträge mit vertragsterminen (dispo)
UPDATE BesetzungTabelle 
	SET ContractId = Co.VertragsNr  
FROM BesetzungTabelle AS C 
	INNER  JOIN ContractDates AS CD ON C.ID = CD.CastId 
	INNER JOIN VertragRolle AS Co ON cd.ContractRoleId = Co.VRID 
WHERE c.ContractId IS NULL
GO

--update verträge mit rollen (dispo-gast)		
UPDATE BesetzungTabelle SET ContractId = v.VertragsNr
FROM		   VertragRolle			AS vr
	INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
	INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
	INNER JOIN BesetzungTabelle		AS b	ON vr.Rolleid = b.Rolleid AND v.PersNr = b.persnr
	INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr	
WHERE 
	vr.RolleId > 0 AND 
	b.ContractId IS NULL  
	AND (a.Datum >= vr.vrvon OR vr.vrvon IS NULL) AND (a.Datum >= v.vvon OR v.vvon IS NULL)
	AND (a.Datum <= vr.vrbis OR vr.vrbis IS NULL) AND (a.Datum <= v.vbis OR v.vbis IS NULL)
GO

--update verträge mit productionen (produktionsvertrag) (chor/orchester gast)
UPDATE BesetzungTabelle SET ContractId = v.VertragsNr
FROM		   VertragRolle			AS vr
	INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
	INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
	INNER JOIN BesetzungTabelle		AS b	ON v.PersNr = b.persnr
	INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr AND a.SNr = vr.ProductionId	
WHERE 
	vr.RolleId = 0 AND NOT ProductionId IS NULL
	AND b.ContractId IS NULL  
	AND (a.Datum >= vr.vrvon OR vr.vrvon IS NULL) AND (a.Datum >= v.vvon OR v.vvon IS NULL)
	AND (a.Datum <= vr.vrbis OR vr.vrbis IS NULL) AND (a.Datum <= v.vbis OR v.vbis IS NULL)

--update verträge ohne rolle oder produktion (spielzeitgage, honorare in dispo/orchester/chor)
UPDATE BesetzungTabelle SET ContractId = v.VertragsNr
FROM		   VertragRolle			AS vr
	INNER JOIN Vertrag				AS v	ON vr.VertragsNr = v.VertragsNr
	INNER JOIN VertragsVorlagen		AS vv	ON v.VorlagenID = vv.VorlagenID
	INNER JOIN BesetzungTabelle		AS b	ON v.PersNr = b.persnr
	INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr	
WHERE 
	vr.RolleId = 0 AND ProductionId IS NULL
	AND b.ContractId IS NULL  
	AND (a.Datum >= vr.vrvon OR vr.vrvon IS NULL) AND (a.Datum >= v.vvon OR v.vvon IS NULL)
	AND (a.Datum <= vr.vrbis OR vr.vrbis IS NULL) AND (a.Datum <= v.vbis OR v.vbis IS NULL)

--update verträge ohne rollen, produktionen oder honoraren (dispo ensemble, chor/orchester ensemble oder gast)
UPDATE BesetzungTabelle SET ContractId = v.VertragsNr
FROM		   Vertrag				AS v
	LEFT  JOIN VertragRolle         AS vr	ON v.VertragsNr = vr.VertragsNr
	INNER JOIN Gruppe       		AS g	ON v.ModulGruppeID = g.GruppeID 
	INNER JOIN BesetzungTabelle		AS b	ON v.PersNr = b.persnr
	INNER JOIN BesetzungStd			AS bs	ON b.RolleID = bs.ID
	INNER JOIN AufführgTabelle		AS a	ON b.Auffnr = a.auffnr	
WHERE 
	b.ContractId IS NULL  
	AND vr.VertragsNr IS NULL
	AND (a.Datum >= v.vvon OR v.vvon IS NULL)
	AND (a.Datum <= v.vbis OR v.vbis IS NULL)
	AND g.GruppeID = bs.Besitzer
	AND (g.Modul & (1|2|16|32)) <> 0
	AND (
		SELECT COUNT(*) FROM Vertrag v2
		LEFT  JOIN VertragRolle vr2	ON v2.VertragsNr = vr2.VertragsNr
		INNER JOIN Gruppe g2 ON v2.ModulGruppeID = g2.GruppeID
		WHERE v2.PersNr = b.PersNr
		 AND (g2.Modul & (1|2|16|32)) <> 0
		 AND (a.Datum >= v2.vvon OR v2.vvon IS NULL)
		AND (a.Datum <= v2.vbis OR v2.vbis IS NULL)
	) = 1
GO 

--Doublette aus StückeDienstplan entfernen
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Notiz' AND o.id = OBJECT_ID(N'[dbo].StückeDienstplan') AND c.prec < 1000)
BEGIN
	ALTER TABLE StückeDienstplan ALTER COLUMN Notiz VARCHAR(1000)
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UQ_ProductionDepartment]') AND xtype = 'UQ')
BEGIN
		--Leere "StückeDienstplan" Zeile löschen
		DELETE FROM StückeDienstplan WHERE Notiz IS NULL and Note2 IS NULL AND ShiftCount = 1
		
		--Doppelte geleiche Zeilen löschen
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		DELETE FROM StückeDienstplan WHERE StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan GROUP BY Snr, DienstplanArtenID, ISNULL(SeasonId, 0), Notiz, Note2  HAVING COUNT(*) > 1)
		
		--Doppelte Zeilen mit unterschiedlichen Inhalt zusammenfühen u. löschen
		UPDATE StückeDienstplan SET Note2 = ISNULL(StückeDienstplan.Note2,'')  + ' ' + ISNULL(sd2.Note2,''),  Notiz = ISNULL(StückeDienstplan.Notiz,'') + ' ' +  ISNULL(sd2.Notiz,'') FROM 
			(SELECT MIN(StückeDienstplanID) AS ID ,Snr,  DienstplanArtenID,  ISNULL(SeasonId,0) AS SI FROM StückeDienstplan  GROUP BY Snr,  DienstplanArtenID,  ISNULL(SeasonId,0)   HAVING COUNT(*)>1) AS Mi 
			INNER JOIN  (SELECT Max(StückeDienstplanID) AS ID ,Snr,  DienstplanArtenID,  ISNULL(SeasonId,0) AS SI FROM StückeDienstplan  GROUP BY Snr,  DienstplanArtenID,  ISNULL(SeasonId,0)   HAVING COUNT(*)>1) AS Ma ON mi.Snr = Ma.Snr AND mi.DienstplanArtenID = ma.DienstplanArtenID AND Mi.SI = Ma.SI
			INNER JOIN StückeDienstplan ON MI.ID =StückeDienstplan.StückeDienstplanID
			INNER JOIN StückeDienstplan as SD2 ON MI.ID =Sd2.StückeDienstplanID
		DELETE FROM StückeDienstplan WHERE StückeDienstplan.StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan  GROUP BY Snr,  DienstplanArtenID,  ISNULL(SeasonId,0)  HAVING COUNT(*)>1)

		UPDATE StückeDienstplan SET Note2 = ISNULL(StückeDienstplan.Note2,'')  + ' ' + ISNULL(sd2.Note2,''),  Notiz = ISNULL(StückeDienstplan.Notiz,'') + ' ' +  ISNULL(sd2.Notiz,'') FROM 
			(SELECT MIN(StückeDienstplanID) AS ID ,Snr,  DienstplanArtenID,  ISNULL(SeasonId,0) AS SI FROM StückeDienstplan  GROUP BY Snr,  DienstplanArtenID,  ISNULL(SeasonId,0)   HAVING COUNT(*)>1) AS Mi 
			INNER JOIN  (SELECT Max(StückeDienstplanID) AS ID ,Snr,  DienstplanArtenID,  ISNULL(SeasonId,0) AS SI FROM StückeDienstplan  GROUP BY Snr,  DienstplanArtenID,  ISNULL(SeasonId,0)   HAVING COUNT(*)>1) AS Ma ON mi.Snr = Ma.Snr AND mi.DienstplanArtenID = ma.DienstplanArtenID AND Mi.SI = Ma.SI
			INNER JOIN StückeDienstplan ON MI.ID =StückeDienstplan.StückeDienstplanID
			INNER JOIN StückeDienstplan as SD2 ON MI.ID =Sd2.StückeDienstplanID
		DELETE FROM StückeDienstplan WHERE StückeDienstplan.StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan  GROUP BY Snr,  DienstplanArtenID,  ISNULL(SeasonId,0)  HAVING COUNT(*)>1)

		UPDATE StückeDienstplan SET Note2 = ISNULL(StückeDienstplan.Note2,'')  + ' ' + ISNULL(sd2.Note2,''),  Notiz = ISNULL(StückeDienstplan.Notiz,'') + ' ' +  ISNULL(sd2.Notiz,'') FROM 
			(SELECT MIN(StückeDienstplanID) AS ID ,Snr,  DienstplanArtenID,  ISNULL(SeasonId,0) AS SI FROM StückeDienstplan  GROUP BY Snr,  DienstplanArtenID,  ISNULL(SeasonId,0)   HAVING COUNT(*)>1) AS Mi 
			INNER JOIN  (SELECT Max(StückeDienstplanID) AS ID ,Snr,  DienstplanArtenID,  ISNULL(SeasonId,0) AS SI FROM StückeDienstplan  GROUP BY Snr,  DienstplanArtenID,  ISNULL(SeasonId,0)   HAVING COUNT(*)>1) AS Ma ON mi.Snr = Ma.Snr AND mi.DienstplanArtenID = ma.DienstplanArtenID AND Mi.SI = Ma.SI
			INNER JOIN StückeDienstplan ON MI.ID =StückeDienstplan.StückeDienstplanID
			INNER JOIN StückeDienstplan as SD2 ON MI.ID =Sd2.StückeDienstplanID
		DELETE FROM StückeDienstplan WHERE StückeDienstplan.StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan  GROUP BY Snr,  DienstplanArtenID,  ISNULL(SeasonId,0)  HAVING COUNT(*)>1)

		UPDATE StückeDienstplan SET Note2 = ISNULL(StückeDienstplan.Note2,'')  + ' ' + ISNULL(sd2.Note2,''),  Notiz = ISNULL(StückeDienstplan.Notiz,'') + ' ' +  ISNULL(sd2.Notiz,'') FROM 
			(SELECT MIN(StückeDienstplanID) AS ID ,Snr,  DienstplanArtenID,  ISNULL(SeasonId,0) AS SI FROM StückeDienstplan  GROUP BY Snr,  DienstplanArtenID,  ISNULL(SeasonId,0)   HAVING COUNT(*)>1) AS Mi 
			INNER JOIN  (SELECT Max(StückeDienstplanID) AS ID ,Snr,  DienstplanArtenID,  ISNULL(SeasonId,0) AS SI FROM StückeDienstplan  GROUP BY Snr,  DienstplanArtenID,  ISNULL(SeasonId,0)   HAVING COUNT(*)>1) AS Ma ON mi.Snr = Ma.Snr AND mi.DienstplanArtenID = ma.DienstplanArtenID AND Mi.SI = Ma.SI
			INNER JOIN StückeDienstplan ON MI.ID =StückeDienstplan.StückeDienstplanID
			INNER JOIN StückeDienstplan as SD2 ON MI.ID =Sd2.StückeDienstplanID
		DELETE FROM StückeDienstplan WHERE StückeDienstplan.StückeDienstplanID IN (SELECT MAX(StückeDienstplanID) FROM StückeDienstplan  GROUP BY Snr,  DienstplanArtenID,  ISNULL(SeasonId,0)  HAVING COUNT(*)>1)

	ALTER TABLE dbo.StückeDienstplan ADD CONSTRAINT [UQ_ProductionDepartment] UNIQUE NONCLUSTERED (Snr, DienstplanArtenID, SeasonId) ON [PRIMARY]	
	CREATE NONCLUSTERED INDEX IX_ProductionDepartment_Production ON dbo.StückeDienstplan (Snr)  ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IX_ProductionDepartment_Department ON dbo.StückeDienstplan (DienstplanArtenID)  ON [PRIMARY]

END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.BudgetPeriods') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN

	CREATE TABLE dbo.BudgetPeriods (
			BudgetPeriodId INT IDENTITY(1,1) NOT NULL,--ID
			Name VARCHAR(50) NOT NULL,
			StartDate DATETIME NOT NULL, 
			EndDate DATETIME NOT NULL, 
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_BudgetPeriods PRIMARY KEY CLUSTERED (BudgetPeriodId ASC) ON [PRIMARY]
	) ON [PRIMARY]
	GRANT SELECT ON dbo.BudgetPeriods TO [Public]
	GRANT DELETE ON dbo.BudgetPeriods TO CostsWrite
	GRANT INSERT ON dbo.BudgetPeriods TO CostsWrite
	GRANT UPDATE ON dbo.BudgetPeriods TO CostsWrite

	SET IDENTITY_INSERT BudgetPeriods ON
	INSERT INTO BudgetPeriods (BudgetPeriodId, Name, StartDate, EndDate, LC, UC, LM, UM) 
	SELECT spznr, CAST(YEAR(SpzEnde) AS VARCHAR(4)), CAST(YEAR(SpzEnde) AS VARCHAR(4)) +'0101' , CAST(YEAR(SpzEnde) AS VARCHAR(4)) +'1231', '19000101',0,'19000101',0    FROM SpielzeitTabelle WHERE SpzNr > 0 AND SpzStart > '20100101'
	SET IDENTITY_INSERT BudgetPeriods OFF
	
		ALTER TABLE Budgets ADD BudgetPeriodId INT NULL
		EXEC ('UPDATE Budgets SET BudgetPeriodId = seasonId WHERE BudgetPeriodId IS NULL ')
		ALTER TABLE [dbo].Budgets  WITH CHECK ADD  CONSTRAINT [FK_Budgets_BudgetPeriods] FOREIGN KEY(BudgetPeriodId)
		REFERENCES [dbo].BudgetPeriods (BudgetPeriodId) 
		ALTER TABLE Budgets ALTER COLUMN BudgetPeriodId INT NOT NULL
		ALTER TABLE [dbo].Budgets  DROP CONSTRAINT FK_Budgets_Seasons


	Exec ('ALTER TABLE dbo.BudgetPeriods ADD CONSTRAINT
	CK_BudgetPeriods_Period CHECK (StartDate <=  EndDate)')

	UPDATE StatusZeitR SET  StatusZeitR.Bis = StatusZeitR.Von, StatusZeitR.Von = StatusZeitR.Bis  WHERE StatusZeitR.Von > StatusZeitR.Bis

	Exec ('ALTER TABLE dbo.StatusZeitR ADD CONSTRAINT
	CK_StatusZeitR_Period CHECK (Von <=  Bis)')

	CREATE NONCLUSTERED INDEX IX_Budgets_BudgetPeriodId ON dbo.Budgets (BudgetPeriodId)  ON [PRIMARY]
END
GO

IF EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.Budgets') AND name = 'SeasonId')
BEGIN
		ALTER TABLE Budgets DROP COLUMN SeasonId
END
GO

GRANT SELECT ON [dbo].Role_Season TO Public
GO
--2014-02-27 TK
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'DebutPlace' AND o.id = OBJECT_ID(N'[dbo].Works') AND c.prec < 50)
BEGIN
	ALTER TABLE Works ALTER COLUMN DebutPlace VARCHAR(50)
	ALTER TABLE Works ALTER COLUMN Title NVARCHAR(50)
	ALTER TABLE Works ALTER COLUMN Tonality VARCHAR(100)
	ALTER TABLE WorkVersions ADD LanguageCodes VARCHAR(50)
	ALTER TABLE WorkVersions ALTER COLUMN OpusNumber VARCHAR(100)
	ALTER TABLE WorkVersions ALTER COLUMN SetNumber VARCHAR(50)
	ALTER TABLE WorkVersions ALTER COLUMN OrderNumber VARCHAR(50)
	ALTER TABLE PersoParameter ADD Check24HourMaxWorkingTime BIT NOT NULL  CONSTRAINT DF_PersoParameter_Check24HourMaxWorkingTime DEFAULT(0)
	
END

GO



--TK 2014-03-12 Index umstellen, hierfür muss der COMPATIBILITY_LEVEL min 90 (2005) sein
DECLARE @serverVersion INT
DECLARE @sql VARCHAR(255)
SELECT @serverVersion = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
IF @serverVersion > 9 AND EXISTS (SELECT compatibility_level FROM sys.databases WHERE name =  DB_NAME() AND compatibility_level = 80) 
BEGIN
set @sql= ('ALTER DATABASE ' + quotename(DB_NAME()) + ' SET COMPATIBILITY_LEVEL = 90')
exec(@sql)
END
IF @serverVersion = 9 AND EXISTS (SELECT compatibility_level FROM sys.databases WHERE name =  DB_NAME() AND compatibility_level = 80) 
BEGIN
DECLARE @dbname1 NVARCHAR(255)
SELECT @dbname1 = DB_NAME()
USE [master]
EXEC sp_dbcmptlevel @dbname=@dbname1, @new_cmptlevel=90
RAISERROR('Der Kompatibilitätsmodus der Datenbank wurde umgestellt. Bitte führen Sie das Script erneut aus', 20, -1) WITH LOG 
END
GO
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[VertragPerso]')  AND name = 'IX_OnlyOneMain') 
BEGIN
	DROP INDEX dbo.VertragPerso.IX_OnlyOneMain
	ALTER TABLE VertragPerso DROP CONSTRAINT CK_VertragPerso_IsMainWorkArea
	UPDATE VertragPerso SET IsMainWorkArea = 0 WHERE IsMainWorkArea IS NULL

	ALTER TABLE VertragPerso ALTER COLUMN IsMainWorkArea BIT NOT NULL 
	ALTER TABLE VertragPerso ADD CONSTRAINT DF_VertragPerso_IsMainWorkArea DEFAULT(0) FOR IsMainWorkArea
	
	DECLARE @serverVersion INT
	SELECT @serverVersion = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
	IF @serverVersion > 9
	BEGIN
	EXEC('CREATE UNIQUE NONCLUSTERED INDEX UQ_VertragPerso_OnlyOneMain ON VertragPerso (VertragsNr, IsMainWorkArea ) WHERE IsMainWorkArea = 1')
	END
END
GO

--2014-0314 TH:
--Besetzungs/Abwesenheitspläne in die neue Planart kopieren
IF NOT EXISTS (SELECT * FROM [Plan] WHERE Planart = 170)
BEGIN
INSERT INTO [Plan] (Bez, PlanArt, Settings, OwnerId, UC, LC, UM, LM) SELECT Bez, 170, Settings, OwnerId, 0, GETDATE(), 0, GETDATE() FROM [Plan] WHERE PlanArt = 110
END
GO


--2014-03-13 SH
--spalte showhistorysince auf nullable datetime setzen
IF EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'ShowHistorySince' AND o.id = OBJECT_ID(N'[dbo].PlanPermissionSettings') AND c.isnullable = 0)
BEGIN
	ALTER TABLE dbo.PlanPermissionSettings ALTER COLUMN ShowHistorySince DATETIME NULL
END
GO

--2014-03-18 SH
--Berechtigung von Honorardaten ändern auf AbPersDetaisl entfernen da es nicht wirklich benötigt wird
--und zu Fehlern führt in v4 das Update aber keine Select Berechtigung
REVOKE UPDATE ON [dbo].[AbPersonalDetails] TO [Honorar-Daten ändern] AS [dbo]
GO

--2014-03-21 SH
--neue spalte in den abteilungen zum deaktivieren der anzeige von unbesetzen planstellen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ShowEmptyPermanentPosts' AND o.id = OBJECT_ID('dbo.DienstplanArtenTabelle'))
BEGIN
	ALTER TABLE dbo.DienstplanArtenTabelle ADD ShowEmptyPermanentPosts BIT NOT NULL CONSTRAINT [DF_Departments_ShowEmptyPermanentPosts] DEFAULT (0)
END
GO
--TK 2014-03-17 Order
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.[OrderApprovalStatus]') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.OrderApprovalStatus (
		OrderApprovalStatusId INT IDENTITY(1, 1) NOT NULL,
		Name VARCHAR(50) NOT NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_OrderApprovalStatus PRIMARY KEY CLUSTERED (OrderApprovalStatusId ASC) ON [PRIMARY]
	) ON [PRIMARY]
END
GO
GRANT SELECT ON dbo.OrderApprovalStatus TO Public
GO
--2014-03-21 TH
--OrderValidation
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.[OrderValidationTypes]') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.OrderValidationTypes(
		OrderValidationTypeId INT IDENTITY(1,1) NOT NULL,
		Name VARCHAR(50) NOT NULL,
		OrderType INT NOT NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_OrderValidationTypeId PRIMARY KEY CLUSTERED (OrderValidationTypeId ASC) ON [PRIMARY]
	) ON [PRIMARY]
END
GO
GRANT SELECT ON dbo.OrderValidationTypes TO Public
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.[OrderValidationApprovalStatus]') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.OrderValidationApprovalStatus (
		OrderValidationApprovalStatusId INT IDENTITY(1, 1) NOT NULL,
		OrderApprovalStatusId INT NOT NULL,
		OrderValidationTypeId INT NOT NULL,
		UserGroupId INT NOT NULL,
		MailingListId INT NULL,
		CanChangeData BIT NOT NULL CONSTRAINT DF_OrderValidationApprovalStatus_CanChangeData DEFAULT 0,
		Sort INT NOT NULL CONSTRAINT DF_OrderValidationApprovalStatus_Sort DEFAULT 0,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_OrderValidationApprovalStatusId PRIMARY KEY CLUSTERED (OrderValidationApprovalStatusId ASC) ON [PRIMARY],
		CONSTRAINT FK_OrderValidationApprovalStatus_OrderValidationType FOREIGN KEY (OrderValidationTypeId) REFERENCES dbo.OrderValidationTypes (OrderValidationTypeId),
		CONSTRAINT FK_OrderValidationApprovalStatus_User FOREIGN KEY (UserGroupId) REFERENCES dbo.UserPW (UserId),
		CONSTRAINT FK_OrderValidationApprovalStatus_MailingList FOREIGN KEY (MailingListId) REFERENCES dbo.Verteiler (VerteilerId),
	) ON [PRIMARY]
END
GO
GRANT SELECT ON dbo.OrderValidationApprovalStatus TO Public
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.[Orders]') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.Orders (
		OrderId INT IDENTITY(1, 1) NOT NULL,
		OrderDate DATETIME NOT NULL,
		OrderApprovalStatusId INT NOT NULL CONSTRAINT DF_Orders_OrderApprovalStatusId DEFAULT 0,
		OrderStatus INT NOT NULL CONSTRAINT DF_Orders_OrderStatus DEFAULT 0,
		BudgetId INT NULL,
		CostTypeId INT NOT NULL,
		CostCenterId INT NOT NULL,
		CostUnitId INT NULL,
		BudgetItemId INT NOT NULL,
		SupplierId INT NULL, --PersId Lieferant
		OrderType INT NOT NULL CONSTRAINT DF_Orders_OrderType DEFAULT 0,
		SupplierAddress VARCHAR(500) NULL,
		DeliveryAddress VARCHAR(500) NULL,
		DelivaryUntilDate DATETIME NULL,
		ConditionsOfPayment VARCHAR(500) NULL,
		Note VARCHAR(1000) NULL,
		InternalNote VARCHAR(1000) NULL,
		CashDiscountPercent FLOAT NOT NULL CONSTRAINT DF_Orders_CashDiscountPercent DEFAULT 0,
		DiscountPercent FLOAT NOT NULL CONSTRAINT DF_Orders_DiscountPercent DEFAULT 0,
		CurrencyId INT NOT NULL,
		CurrencyRate FLOAT NOT NULL CONSTRAINT DF_Orders_CurrencyRate DEFAULT 1,
		IsCanceled BIT NOT NULL CONSTRAINT DF_Orders_IsCanceled DEFAULT 0,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_Orders PRIMARY KEY CLUSTERED (OrderId ASC) ON [PRIMARY],
		CONSTRAINT FK_Orders_OrderBudgetStatus FOREIGN KEY(OrderApprovalStatusId) REFERENCES dbo.OrderApprovalStatus (OrderApprovalStatusId),
		CONSTRAINT FK_Orders_Budgets FOREIGN KEY(BudgetId) REFERENCES dbo.Budgets (BudgetId),
		CONSTRAINT FK_Orders_Suppliers FOREIGN KEY(SupplierId) REFERENCES dbo.PersH (Persnr),
		CONSTRAINT FK_Orders_CostTypes FOREIGN KEY(CostTypeId) REFERENCES dbo.CostTypes (CostTypeId),
		CONSTRAINT FK_Orders_CostCenters FOREIGN KEY(CostCenterId) REFERENCES dbo.CostCenter (CostCenterId),
		CONSTRAINT FK_Orders_CostUnits FOREIGN KEY(CostUnitId) REFERENCES dbo.CostUnit (CostUnitId),
		CONSTRAINT FK_Orders_BudgetItems FOREIGN KEY(BudgetItemId) REFERENCES dbo.BudgetItem (BudgetItemId)

	) ON [PRIMARY]
	CREATE INDEX IX_Orders_CostCenterId ON dbo.Orders(CostCenterId)
	CREATE INDEX IX_Orders_SupplierId ON dbo.Orders(SupplierId)
	CREATE INDEX IX_Orders_BudgetId ON dbo.Orders (BudgetId)
	CREATE INDEX IX_Orders_OrderStatus ON dbo.Orders (OrderStatus)
END
GO
REVOKE SELECT ON dbo.Orders TO Public
REVOKE DELETE ON dbo.Orders TO Public
REVOKE UPDATE ON dbo.Orders TO Public
REVOKE INSERT ON dbo.Orders TO Public
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.[OrderPos]') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.OrderPos (
		OrderPosId INT IDENTITY(1, 1) NOT NULL,
		OrderId INT NOT NULL,
		Sort INT NOT NULL,
		[Description] VARCHAR(1000) NULL,
		Quantity MONEY NOT NULL CONSTRAINT DF_OrderPos_Quantity DEFAULT 1, 
		Unity MONEY NOT NULL CONSTRAINT DF_OrderPos_Unity DEFAULT 0, 
		NetPrice MONEY NOT NULL CONSTRAINT DF_OrderPos_NetPrice DEFAULT 0, 
		TaxId INT NULL,
		PositionType INT NOT NULL CONSTRAINT DF_OrderPos_PositionType DEFAULT 0, 
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_OrdersId PRIMARY KEY CLUSTERED (OrderPosId ASC) ON [PRIMARY],
		CONSTRAINT FK_Orders_Order FOREIGN KEY(OrderId) REFERENCES dbo.Orders (OrderId),
		CONSTRAINT FK_Orders_Tax FOREIGN KEY(TaxId) REFERENCES dbo.Taxes (TaxId)
	) ON [PRIMARY]
END
GO
REVOKE SELECT ON dbo.OrderPos TO Public
REVOKE DELETE ON dbo.OrderPos TO Public
REVOKE UPDATE ON dbo.OrderPos TO Public
REVOKE INSERT ON dbo.OrderPos TO Public
GO

--TK 2014-03-26 Eindeutige Budget
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID('Budgets')  AND name = 'UQ_Budget_CostCenter_CostUnit_CostType_BudgetItem')
	DROP INDEX Budgets.UQ_Budget_CostCenter_CostUnit_CostType_BudgetItem

DECLARE @serverVersion INT
SELECT @serverVersion = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
	
IF @serverVersion > 9 AND NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Budgets]')  AND name = 'UQ_Budget_BudgetPeriod_CostCenter_CostUnit_CostType_BudgetItem')
	EXEC('CREATE UNIQUE NONCLUSTERED INDEX UQ_Budget_BudgetPeriod_CostCenter_CostUnit_CostType_BudgetItem ON Budgets (BudgetPeriodId, CostCenterId, CostUnitId, CostTypeId, BudgetItemId ) WHERE IsInactive = 0')

GO
	
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'WorkTyp' AND o.id = OBJECT_ID('dbo.Typ'))
BEGIN
	ALTER TABLE dbo.Typ ADD WorkTyp INT NOT NULL CONSTRAINT DF_Typ_WorkTyp DEFAULT 0
	EXEC ('UPDATE dbo.Typ SET WorkTyp = 3 WHERE Typ.TypID <> 0')
END	
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'DeadlineDate' AND o.id = OBJECT_ID('dbo.ContractTracking'))
BEGIN
	ALTER TABLE dbo.ContractTracking ADD DeadlineDate DATETIME NULL
	ALTER TABLE dbo.ContractTracking ALTER COLUMN TrackingDate DATETIME NULL
	ALTER TABLE dbo.Budgets ADD IsCostUnitBudget BIT NOT NULL CONSTRAINT DF_Budgets_IsCostUnitBudget DEFAULT 1
	EXEC ('UPDATE Budgets SET IsCostUnitBudget = 1 WHERE NOT CostUnitId  IS NULL')
END
GO

--2014-03-28 TH:
--Neue Spalte in Zeitkonten für die Einstellungen bezüglich der Übernahme beim Jahresabschluss und eine Spalte it weiteren Einstellungen (XML)
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON o.id = c.id
	WHERE c.name = 'TransferValueOnYearClose' AND o.id = OBJECT_ID('dbo.Zeitkonten'))
BEGIN
	ALTER TABLE Zeitkonten ADD TransferValueOnYearClose INT NOT NULL CONSTRAINT DF_Zeitkonten_TransferValueOnYearClose DEFAULT 2
	ALTER TABLE Zeitkonten ADD TransferValueOnYearCloseSettings VARCHAR(500) NULL
	EXEC ('UPDATE Zeitkonten SET TransferValueOnYearClose = 0 WHERE Zeitkonten.Formel = 1252')
	EXEC ('UPDATE Zeitkonten SET TransferValueOnYearClose = 1 WHERE Zeitkonten.Formel IN (3010, 3020, 3050, 1230)')
END
GO

--2014-03-26 TH:
--Neue Spalte in OrderValidationApprovalStatus, die angibt, ob eine Bestellung in diesem Status gedruck werden kann
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IsPrintable' AND o.id = OBJECT_ID('dbo.OrderValidationApprovalStatus'))
BEGIN
	ALTER TABLE OrderValidationApprovalStatus ADD IsPrintable BIT NOT NULL CONSTRAINT DF_OrderValidationApprovalStatus_IsPrintable DEFAULT 0
END
GO

--2014-03-26 sh
--neuer view zum abfrage nvon aktivitäten

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

CREATE VIEW [dbo].[AbActivities]
AS

	SELECT			act.*, p.Titel, p.ModuleGroupId, p.TypID
	FROM			AufführgTabelle act
		INNER JOIN	Spielzeittabelle AS s  ON act.Datum <= s.SpzEnde AND act.Datum >= s.SpzStart
		INNER JOIN	UserForAccess    AS us ON s.spznr   = us.spznr
		INNER JOIN	UserPW           AS u  ON us.UserId = u.UserID
		INNER JOIN  Stücke			 AS p ON act.snr = p.snr
		LEFT  JOIN  UserGruppe ug ON p.ModuleGroupId = ug.GruppeID AND U.UserID = ug.UserID AND ug.BerechtigungsbereichID = 2

	WHERE
		u.UserName  = CURRENT_USER
		AND (act.Gesperrt = 0 OR  ug.OptionsFlag IS NULL OR ug.OptionsFlag & 1 = 1)

GO
GRANT SELECT ON [dbo].[AbActivities] TO PUBLIC
GO

--berechtigungsflag für alle user setzen die spielplan alles lesen haben
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 142 OR (Minor = 142 AND Build < 4)))))
BEGIN
	--benutzer die schreiben haben, das optionsflag setzen
	UPDATE UserGruppe SET OptionsFlag = 1 WHERE BerechtigungsbereichID = 2 and Schreiben = 1

	--benutzer die lesen haben, und in der rolle "spielplan alles lesen" sind, optionsflag setzen und vererbung deaktivieren
	UPDATE UserGruppe SET OptionsFlag = 1, IsInherited = 0
	WHERE BerechtigungsbereichID = 2 AND Schreiben = 0
	AND UserID IN (
		SELECT up.UserID FROM UserPw up
		JOIN dbo.sysusers u ON u.name = up.UserName AND u.uid IN (
			SELECT memberuid FROM dbo.sysmembers WHERE groupuid IN (
				SELECT uid FROM dbo.sysusers WHERE name = 'Spielplan alles lesen' AND issqlrole = 1
			)
		)
		UNION ALL
		SELECT up.userid FROM UserPw up WHERE up.UserName = 'dbo'
	)
END
GO

--2014-03-08 sh
--publishinweb umstellen von bool auf enum
IF EXISTS(SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'PublishInWeb' AND o.id = OBJECT_ID(N'[dbo].PlanPermissionSettings') AND c.xtype = 104)
BEGIN
	ALTER TABLE dbo.PlanPermissionSettings ALTER COLUMN PublishInWeb int NOT NULL

	ALTER TABLE dbo.PlanPermissionSettings ADD CONSTRAINT DF_PlanPermissionSettings_PublishInWeb DEFAULT 0 FOR PublishInWeb
END
GO

GRANT DELETE ON FormulaConfigurations_Departments TO Public
GRANT UPDATE ON FormulaConfigurations_Departments TO Public
GRANT INSERT ON FormulaConfigurations_Departments TO Public
GO
IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Fahrplan]')  AND name = 'IX_AuffNr' ) 
		DROP INDEX Fahrplan.IX_AuffNr

IF  EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Fahrplan]')  AND name = 'IX_Gruppe' ) 
		DROP INDEX Fahrplan.IX_Gruppe

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_JourneyTimetable_Activity]') AND type = 'F')
BEGIN
	--TK Fahrplan Index erstellen	
	DELETE FROM Fahrplan WHERE AuffNr IS NULL
	DELETE FROM Fahrplan WHERE AuffNr NOT IN (SELECT Auffnr FROM AufführgTabelle)
	ALTER TABLE Fahrplan ALTER COLUMN AuffNr INT NOT NULL
	ALTER TABLE Fahrplan ALTER COLUMN RichtungHin BIT NOT NULL 
	UPDATE Fahrplan SET RichtungHin = 0 WHERE RichtungHin IS NULL

	UPDATE Fahrplan SET Diff = 0 WHERE Diff IS NULL
	ALTER TABLE Fahrplan ALTER COLUMN Diff FLOAT NOT NULL 

	ALTER TABLE [dbo].Fahrplan  WITH CHECK ADD  CONSTRAINT FK_JourneyTimetable_Activity FOREIGN KEY(AuffNr)
	REFERENCES [dbo].AufführgTabelle (AuffNr)  
	ALTER TABLE dbo.Fahrplan CHECK CONSTRAINT FK_JourneyTimetable_Activity
	
	DELETE FROM Fahrplan WHERE Gruppe IS NULL
	DELETE FROM Fahrplan WHERE Gruppe NOT IN (SELECT GruppeID FROM FahrplanGruppen)
	ALTER TABLE Fahrplan ALTER COLUMN Gruppe INT NOT NULL

	ALTER TABLE [dbo].Fahrplan  WITH CHECK ADD  CONSTRAINT FK_JourneyTimetable_JourneyGroup FOREIGN KEY(Gruppe)
	REFERENCES [dbo].FahrplanGruppen (GruppeID)  
	ALTER TABLE dbo.Fahrplan CHECK CONSTRAINT FK_JourneyTimetable_JourneyGroup

	--Kostenarten nach 
	CREATE INDEX IX_JourneyTimetable_ActivityId ON dbo.Fahrplan(Auffnr)
	ALTER TABLE CostTypes ADD IsCostUnitRequired BIT NULL
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'QuoteNo' AND o.id = OBJECT_ID('dbo.Orders'))
BEGIN
	ALTER TABLE Orders ADD 	OrderNo  VARCHAR(20) NULL
	ALTER TABLE Orders ADD 	QuoteNo  VARCHAR(20) NULL
	ALTER TABLE Orders ADD 	QuoteDate  DATETIME NULL
	ALTER TABLE OrderPos ADD DiscountPercent DECIMAL NOT NULL CONSTRAINT DF_OrderPos_DiscountPercent DEFAULT 0
	ALTER TABLE OrderPos ADD ReferenceNo  VARCHAR(20) NULL	
END
GO

--2014-04-03 sh
--neue spalte für standard status für neue verträge bei vertragsvalidierung
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ContractStatusIdForNewContracts' AND o.id = OBJECT_ID('dbo.PersContractValidationType'))
BEGIN
	ALTER TABLE PersContractValidationType ADD ContractStatusIdForNewContracts INT NULL

	ALTER TABLE [dbo].PersContractValidationType  WITH CHECK ADD CONSTRAINT FK_PersContractValidationType_VertragsStatus FOREIGN KEY(ContractStatusIdForNewContracts)
	REFERENCES [dbo].VertragsStatus (VertragsStatusNr)
END
GO

--2014-04-04 sh
--neue spalte für tagesnotizkategorien, ob diese mit gedruckt werden
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'IssueOnRosterPrint' AND o.id = OBJECT_ID('dbo.DayNoteCategories'))
BEGIN
	ALTER TABLE DayNoteCategories ADD IssueOnRosterPrint BIT NOT NULL CONSTRAINT DF_DayNoteCategories_IssueOnRosterPrint DEFAULT 1
END
GO

--2014-04-11 th
--neue Spalte für Xml-Einstellungen in OrderPos
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'XmlSettings' AND o.id = OBJECT_ID('OrderPos'))
BEGIN
	ALTER TABLE OrderPos ADD XmlSettings VARCHAR(MAX) NULL
END
GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.[CashFunds]') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.CashFunds (
		CashFundId INT IDENTITY(1, 1) NOT NULL,
		CashFundNumber VARCHAR(200) NOT NULL,
		CostCenterId INT NOT NULL,
		OwnerUserId INT NOT NULL,
		OpenedOn DATETIME NULL,
		ClosedOn DATETIME NULL,
		Closed BIT NOT NULL CONSTRAINT CashFund_Closed DEFAULT 0,
		[Description] VARCHAR(1000) NULL,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_CashFundId PRIMARY KEY CLUSTERED (CashFundId ASC) ON [PRIMARY],
		CONSTRAINT FK_CashFunds_Users FOREIGN KEY(OwnerUserId) REFERENCES dbo.UserPw (UserId),
		CONSTRAINT FK_CashFunds_CostCenters FOREIGN KEY(CostCenterId) REFERENCES dbo.CostCenter (CostCenterId),
	) ON [PRIMARY]

	ALTER TABLE Orders ADD CashFundId INT NULL
	ALTER TABLE [dbo].Orders  WITH CHECK ADD CONSTRAINT FK_Orders_CashFunds FOREIGN KEY(CashFundId)
	REFERENCES [dbo].CashFunds (CashFundId)
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.[CashFundPositions]') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.CashFundPositions (
		CashFundPositionId INT IDENTITY(1, 1) NOT NULL,
		CashFundId INT NOT NULL,
		CashFundPositionNumber VARCHAR(200) NOT NULL,
		CashFundPositionReference VARCHAR(200) NULL,
		CashFundStatusId INT NOT NULL, 
		PositionDate DATETIME NOT NULL,
		PositionValue REAL NOT NULL CONSTRAINT DF_CashFundPositions_PositionValue DEFAULT 0, 
		[Description] VARCHAR(1000) NULL,
		CurrencyId INT NOT NULL,
		CurrencyRate FLOAT NOT NULL CONSTRAINT CashFundPositions_CurrencyRate DEFAULT 1,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_CashFundPositionId PRIMARY KEY CLUSTERED (CashFundPositionId ASC) ON [PRIMARY],
		CONSTRAINT FK_CashFundPosition_CashFund FOREIGN KEY(CashFundId) REFERENCES dbo.CashFunds (CashFundId),
		CONSTRAINT FK_CashFundPosition_Currency FOREIGN KEY(CurrencyId) REFERENCES dbo.Currency (CurrencyId),
	) ON [PRIMARY]
END
GO

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbOrders]'))	DROP VIEW [dbo].[AbOrders]
GO
--ORDERS SELECT VIEW
CREATE VIEW [dbo].[AbOrders]
AS 
SELECT * FROM Orders  AS O WHERE O.CostCenterId IN(
SELECT CCG.CostCenterId FROM CostCenter_OwnerGroup AS CCG
INNER JOIN UserGruppe AS UG ON UG.GruppeID = CCG.OwnerGroupId
INNER JOIN UserPw AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.BerechtigungsbereichID = 12)
OR O.CashFundId IN (
SELECT CF.CashFundId FROM CashFunds AS CF INNER JOIN UserPw AS U ON U.Userid = CF.OwnerUserID
WHERE U.UserName = CURRENT_USER)
WITH CHECK OPTION

GO
GRANT SELECT ON dbo.[AbOrders] TO Public
GO 

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbOrders_Update]'))	DROP VIEW [dbo].[AbOrders_Update]
GO
CREATE VIEW [dbo].[AbOrders_Update]
AS 
--ORDERS UPDATE VIEW
SELECT * FROM Orders  AS O WHERE O.CostCenterId IN(
SELECT CCG.CostCenterId FROM CostCenter_OwnerGroup AS CCG
INNER JOIN UserGruppe AS UG ON UG.GruppeID = CCG.OwnerGroupId
INNER JOIN UserPw AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.BerechtigungsbereichID = 12 AND UG.Schreiben = 1)
OR O.CashFundId IN (
SELECT CF.CashFundId FROM CashFunds AS CF INNER JOIN UserPw AS U ON U.Userid = CF.OwnerUserID
WHERE U.UserName = CURRENT_USER)
WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, DELETE, INSERT ON dbo.[AbOrders_Update] TO Public
GO 

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbOrderPositions]'))	DROP VIEW [dbo].[AbOrderPositions]
GO
--ORDERPOSITIONS SELECT VIEW
CREATE VIEW [dbo].[AbOrderPositions]
AS 
SELECT * FROM OrderPos  AS OP WHERE OP.OrderId IN(
SELECT OrderId FROM Orders AS O
INNER JOIN CostCenter_OwnerGroup AS CCG ON O.CostCenterId = CCG.CostCenterId
INNER JOIN UserGruppe AS UG ON UG.GruppeID = CCG.OwnerGroupId
INNER JOIN UserPw AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.BerechtigungsbereichID = 12)
OR OP.OrderId IN (
SELECT O.OrderID FROM Orders AS O
INNER JOIN  CashFunds AS CF ON CF.CashFundId = O.CashFundId
INNER JOIN UserPw AS U ON U.Userid = CF.OwnerUserID
WHERE U.UserName = CURRENT_USER)
WITH CHECK OPTION
GO
GRANT SELECT ON dbo.[AbOrderPositions] TO Public
GO 

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbOrderPositions_Update]'))	DROP VIEW [dbo].[AbOrderPositions_Update]
GO
--ORDERPOSITIONS UPDATE VIEW
CREATE VIEW [dbo].[AbOrderPositions_Update]
AS 
SELECT * FROM OrderPos  AS OP WHERE OP.OrderId IN(
SELECT OrderId FROM Orders AS O
INNER JOIN CostCenter_OwnerGroup AS CCG ON O.CostCenterId = CCG.CostCenterId
INNER JOIN UserGruppe AS UG ON UG.GruppeID = CCG.OwnerGroupId
INNER JOIN UserPw AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.BerechtigungsbereichID = 12 AND UG.Schreiben = 1)
OR OP.OrderId IN (
SELECT O.OrderID FROM Orders AS O
INNER JOIN  CashFunds AS CF ON CF.CashFundId = O.CashFundId
INNER JOIN UserPw AS U ON U.Userid = CF.OwnerUserID
WHERE U.UserName = CURRENT_USER)
WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, DELETE, INSERT ON dbo.[AbOrderPositions_Update] TO Public
GO 

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCashFunds]'))	DROP VIEW [dbo].[AbCashFunds]
GO
CREATE VIEW [dbo].[AbCashFunds]
AS 
--CASHFUNDS SELECT VIEW 
SELECT * FROM CashFunds  AS CF WHERE CF.CostCenterId IN(
SELECT CCG.CostCenterId FROM CostCenter_OwnerGroup AS CCG
INNER JOIN UserGruppe AS UG ON UG.GruppeID = CCG.OwnerGroupId
INNER JOIN UserPw AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.BerechtigungsbereichID = 12)
OR CF.OwnerUserID IN (SELECT UserId FROM UserPw AS U
WHERE U.UserName = CURRENT_USER)
WITH CHECK OPTION
GO
GRANT SELECT ON dbo.[AbCashFunds] TO Public
GO 

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCashFunds_Update]'))	DROP VIEW [dbo].[AbCashFunds_Update]
GO
CREATE VIEW [dbo].[AbCashFunds_Update]
AS 
--CASHFUNDS UPDATE VIEW
SELECT * FROM CashFunds  AS CF WHERE CF.CostCenterId IN(
SELECT CCG.CostCenterId FROM CostCenter_OwnerGroup AS CCG
INNER JOIN UserGruppe AS UG ON UG.GruppeID = CCG.OwnerGroupId
INNER JOIN UserPw AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.BerechtigungsbereichID = 12 AND UG.Schreiben = 1)
WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, DELETE, INSERT ON dbo.[AbCashFunds_Update] TO Public
GO 

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCashFundPositions]'))	DROP VIEW [dbo].[AbCashFundPositions]
GO
CREATE VIEW [dbo].[AbCashFundPositions]
AS 
--CASHFUNDPOSITIONS SELECT VIEW
SELECT * FROM CashFundPositions WHERE CashFundId IN(
SELECT CashFundID FROM CashFunds AS CF
INNER JOIN CostCenter_OwnerGroup AS CCG ON CF.CostCenterId = CCG.CostcenterId
INNER JOIN UserGruppe AS UG ON UG.GruppeID = CCG.OwnerGroupId
INNER JOIN UserPw AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.BerechtigungsbereichID = 12
OR CF.OwnerUserID IN (SELECT UserId FROM UserPw AS U
WHERE U.UserName = CURRENT_USER))
WITH CHECK OPTION
GO
GRANT SELECT ON dbo.[AbCashFundPositions] TO Public
GO 

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbCashFundPositions_Update]'))	DROP VIEW [dbo].[AbCashFundPositions_Update]
GO
CREATE VIEW [dbo].[AbCashFundPositions_Update]
AS 
--CASHFUNDPOSITIONS UPDATE VIEW
SELECT * FROM CashFundPositions WHERE CashFundId IN(
SELECT CashFundID FROM CashFunds AS CF
INNER JOIN CostCenter_OwnerGroup AS CCG ON CF.CostCenterId = CCG.CostcenterId
INNER JOIN UserGruppe AS UG ON UG.GruppeID = CCG.OwnerGroupId
INNER JOIN UserPw AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.BerechtigungsbereichID = 12 AND Schreiben = 1)
WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, DELETE, INSERT ON dbo.[AbCashFundPositions_Update] TO Public
GO 

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbBudgets]'))	DROP VIEW [dbo].[AbBudgets]
GO
CREATE VIEW [dbo].[AbBudgets]
AS 
--BUDGET SELECT VIEW
SELECT * FROM Budgets WHERE Budgets.CostCenterId IN(
SELECT CostCenterId FROM CostCenter_OwnerGroup AS CCG
INNER JOIN UserGruppe AS UG ON UG.GruppeID = CCG.OwnerGroupId
INNER JOIN UserPw AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.BerechtigungsbereichID IN (12,1))
WITH CHECK OPTION
GO
GRANT SELECT ON dbo.[AbBudgets] TO Public
GO 



--2014-04-08 sh
--personenberechtigungen auf geheime kontaktdaten lesen setzen für den besitzer der person
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 142 OR (Minor = 142 AND Build < 101)))))
BEGIN
	UPDATE PersonModulGroupPermission SET HasAccessToSecretContactData = 1
	WHERE PersonModulGroupPermissionId IN (
		SELECT pmgp.PersonModulGroupPermissionId FROM PersH ph
		INNER JOIN PersonModulGroupPermission pmgp ON ph.PersNr = pmgp.PersonId AND ph.Besitzer = pmgp.ModulGroupId
	)
END
GO

--Besitzer in PersonModulGroupPermission eintragen (verschoben da neue spalte hinzu kam)
 INSERT INTO PersonModulGroupPermission (PersonId,ModulGroupId,PermissionType,HasWritePermission,LM,UM,LC,UC, HasAccessToSecretContactData)
 SELECT p.PersNr,p.Besitzer,0,1,GetDate(),0,GetDate(),0,1
 FROM PersonModulGroupPermission as pmg 
	RIGHT JOIN PersH as p on pmg.ModulGroupId = p.Besitzer AND pmg.PersonId = p.PersNr 
 WHERE  pmg.ModulGroupId IS NULL
 GO
--2014-04-11 sh
--neue spalte für abwesenheiten, datum der beantragung
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'DateOfRequest' AND o.id = OBJECT_ID('dbo.StatusZeitR'))
BEGIN
	ALTER TABLE dbo.[StatusZeitR] ADD DateOfRequest DATETIME NULL
END
GO

--2014-04-14 sh
--neue spalte für PersoParameter
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'UseRegularWorkingTimeByDateAsHolidayCreditValue' AND o.id = OBJECT_ID('dbo.PersoParameter'))
BEGIN
	ALTER TABLE dbo.[PersoParameter] ADD UseRegularWorkingTimeByDateAsHolidayCreditValue BIT NOT NULL CONSTRAINT DF_PersoParameter_UseRegularWorkingTimeByDateAsHolidayCreditValue DEFAULT 0
	EXEC('UPDATE PersoParameter SET UseRegularWorkingTimeByDateAsHolidayCreditValue = GutschriftTag')
END
GO

--2014-05-06 sh
--neue spalte für PlanExport
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ExportCastData' AND o.id = OBJECT_ID('dbo.PlanExport'))
BEGIN
	ALTER TABLE dbo.[PlanExport] ADD ExportCastData BIT NOT NULL CONSTRAINT DF_PlanExport_ExportCastData DEFAULT 1
END
GO

--2014-04-17 th
--neue Tabelle für die cash fund position validierung
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.[CashFundPositionValidationStatus]') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.CashFundPositionValidationStatus (
		CashFundPositionValidationStatusId INT IDENTITY(1, 1) NOT NULL,
		CashFundStatusId INT NOT NULL,
		CostCenterId INT NULL,
		UserGroupId INT NOT NULL,
		MailingListId INT NULL,
		CanChangeData BIT NOT NULL CONSTRAINT DF_CashFundPositionValidationStatus_CanChangeData DEFAULT 0,
		Sort INT NOT NULL CONSTRAINT DF_CashFundPositionValidationStatus_Sort DEFAULT 0,
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_CashFundPositionValidationStatusId PRIMARY KEY CLUSTERED (CashFundPositionValidationStatusId ASC) ON [PRIMARY],
		CONSTRAINT FK_CashFundPositionValidationStatus_User FOREIGN KEY (UserGroupId) REFERENCES dbo.UserPW (UserId),
		CONSTRAINT FK_CashFundPositionValidationStatus_MailingList FOREIGN KEY (MailingListId) REFERENCES dbo.Verteiler (VerteilerId),
		CONSTRAINT UQ_CashFundPositionValidationStatus_CashFundstatus_CostCenter UNIQUE (CashFundStatusId, CostCenterId)
	) ON [PRIMARY]
END
GO
GRANT SELECT ON dbo.CashFundPositionValidationStatus TO Public
GO

--2014-04-28 TH: Wenn nicht vorhanden wird ein StückeTeil für das SoliProben-Stück angelegt
IF NOT EXISTS(SELECT * FROM StückeTeil WHERE SNR = -2)
BEGIN
	INSERT INTO [dbo].[StückeTeil] ([Snr] ,[SnrTeil] ,[Sort]) VALUES (-2,-2,0)
END
GO

--2014-05-06 TH: Neuer View für die Stücke-Spielzeit zuordnung. Dieser Prüft nurnoch die Berechtigungsbereichberechtigung
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbProductionSeasons_Update'))
BEGIN
DROP VIEW [dbo].AbProductionSeasons_Update
END
GO
CREATE VIEW dbo.AbProductionSeasons_Update 
AS
SELECT * FROM StückeSpz WHERE Snr IN (
SELECT Snr 
FROM Stücke AS S 
INNER JOIN UserGruppe AS UG ON S.ModuleGroupId = UG.GruppeID
INNER JOIN UserPW AS U ON U.UserID = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.Schreiben = 1 AND UG.BerechtigungsbereichID = 3)

WITH CHECK OPTION
GO
GRANT SELECT ON AbProductionSeasons_Update To PUBLIC
GRANT UPDATE ON AbProductionSeasons_Update To PUBLIC
GRANT DELETE ON AbProductionSeasons_Update To PUBLIC
GRANT INSERT ON AbProductionSeasons_Update To PUBLIC
GO

--2014-05-08 TH: Umstellung der Countdownzeiten auf Minuten
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'OffsetMinutes' AND o.id = OBJECT_ID('dbo.Countdown'))
BEGIN
ALTER TABLE Countdown ADD OffsetMinutes INT NULL
ALTER TABLE Countdown ADD DurationMinutes INT NULL
EXEC ('UPDATE Countdown SET OffsetMinutes = ROUND(BeginnOff*60,0), DurationMinutes = ROUND(Dauer*60,0)')
ALTER TABLE Countdown DROP COLUMN BeginnOff
ALTER TABLE Countdown ADD BeginnOff AS OffsetMinutes /60.0
ALTER TABLE Countdown DROP COLUMN Dauer
ALTER TABLE Countdown ADD Dauer AS DurationMinutes /60.0
END
GO
--TK 2014-06-05 View für Personalbedarf
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbTechnicalPersonalRequirements]'))
	DROP VIEW [dbo].[AbTechnicalPersonalRequirements]
GO
CREATE VIEW [dbo].[AbTechnicalPersonalRequirements]
AS 

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

		FROM AuffTechAufgabe as aufgabe
		INNER JOIN AufführgTabelle AS auff ON auff.AuffNr = aufgabe.AuffNr
		LEFT JOIN Besetzungtabelle AS C ON c.AuffTechAufgabeID = aufgabe.AuffTechAufgabeID and c.AuffNr = auff.AuffNr

	WHERE auff.Status BETWEEN 0 AND 99
	GROUP BY auff.Auffnr, aufgabe.AuffTechAufgabeID,  auff.Datum, auff.UhrBeg, auff.UhrEnde, aufgabe.ArbeiterAnzahl, aufgabe.ABGruppeId, aufgabe.Pos
GO
GRANT SELECT ON [AbTechnicalPersonalRequirements] To PUBLIC

GO

ALTER VIEW [dbo].[AbActivities]
AS
	SELECT			act.*, p.Titel, p.ModuleGroupId, p.TypID
	FROM			AufführgTabelle act
		INNER JOIN	Spielzeittabelle AS s  ON act.Datum <= s.SpzEnde AND act.Datum >= s.SpzStart
		INNER JOIN	UserForAccess    AS us ON s.spznr   = us.spznr
		INNER JOIN	UserPW           AS u  ON us.UserId = u.UserID
		INNER JOIN  Stücke			 AS p ON act.snr = p.snr
		LEFT  JOIN  UserGruppe ug ON p.ModuleGroupId = ug.GruppeID AND U.UserID = ug.UserID AND ug.BerechtigungsbereichID = 2

	WHERE
		u.UserName  = CURRENT_USER
		AND (act.Gesperrt = 0 OR  ug.OptionsFlag IS NULL OR ug.OptionsFlag & 1 = 1)
GO
--TK-204-05-22 REFERENCES  Fahrplangruppen 
UPDATE BesetzungStd SET GruppeId = NULL WHERE  GruppeId NOT IN (SELECT GruppeId FROM FahrplanGruppen)
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_Roles_JourneyTimetableGroups]') AND type = 'F')
BEGIN
	ALTER TABLE [dbo].[BesetzungStd]  WITH CHECK ADD  CONSTRAINT [FK_Roles_JourneyTimetableGroups] FOREIGN KEY(GruppeId)
	REFERENCES [dbo].FahrplanGruppen (GruppeId)  
	ALTER TABLE dbo.[BesetzungStd] CHECK CONSTRAINT [FK_Roles_JourneyTimetableGroups]
END
GO
UPDATE RollenLtg SET GruppeId = NULL WHERE  GruppeId NOT IN (SELECT GruppeId FROM FahrplanGruppen)
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_RolesTemplate_JourneyTimetableGroups]') AND type = 'F')
BEGIN
	ALTER TABLE [dbo].RollenLtg  WITH CHECK ADD  CONSTRAINT FK_RolesTemplate_JourneyTimetableGroups FOREIGN KEY(GruppeId)
	REFERENCES [dbo].FahrplanGruppen (GruppeId)  
	ALTER TABLE dbo.RollenLtg CHECK CONSTRAINT FK_RolesTemplate_JourneyTimetableGroups
END
GO

--2014-05-21 TH: Neue Spalten in OrderValidationType für Kostenstelle und Status ab welchem die Nummer generiert werden soll
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'CostCenterId' AND o.id = OBJECT_ID('dbo.OrderValidationTypes'))
BEGIN
ALTER TABLE OrderValidationTypes ADD CostCenterId INT NULL
ALTER TABLE OrderValidationTypes ADD CONSTRAINT FK_OrderValidationTypes_CostCenter FOREIGN KEY (CostCenterId) REFERENCES dbo.CostCenter (CostcenterId)
ALTER TABLE OrderValidationApprovalStatus ADD CreateNumber BIT NOT NULL CONSTRAINT DF_OrderValidationApprovalStatus_CreateNumber DEFAULT 0
ALTER TABLE Orders ADD OrderNumber INT NULL
ALTER TABLE BudgetPeriods ADD Prefix VARCHAR(25) NULL
ALTER TABLE Orders ADD CallOfTender VARCHAR(25) NULL
END
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].GetMaxOrderNumber'))
BEGIN
	DROP PROCEDURE dbo.GetMaxOrderNumber 
END
go
CREATE PROCEDURE [dbo].[GetMaxOrderNumber]
	@budgetPeriodId int
AS
BEGIN
	SELECT ISNULL(MAX(OrderNumber),0) FROM Orders  AS O
		INNER JOIN Budgets AS B ON B.BudgetId = O.BudgetId
		WHERE OrderNumber IS NOT NULL AND B.BudgetPeriodId = @budgetPeriodId
END
GO
GRANT EXECUTE ON GetMaxOrderNumber TO PUBLIC
GO


IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'PublicNote' AND o.id = OBJECT_ID('dbo.Orders'))
BEGIN
ALTER TABLE Orders ADD PublicNote VARCHAR(255) NULL
END
GO
--TK 2014-06-03
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'ExactjourneyTimeMinutes' AND o.id = OBJECT_ID('dbo.Fahrplan'))
	ALTER TABLE Fahrplan ADD 	ExactjourneyTimeMinutes INT NULL




IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'PersonInChargeId' AND o.id = OBJECT_ID('dbo.CostCenter'))
BEGIN
ALTER TABLE CostCenter ADD PersonInChargeId INT NULL
END

--2014-05-26 TH:
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'PublicPermission' AND o.id = OBJECT_ID('dbo.PersonAttachments'))
BEGIN
ALTER TABLE PersonAttachments ADD PublicPermission INT NOT NULL CONSTRAINT DF_PersonAttachments_PublicPermission DEFAULT 0 
ALTER TABLE PersonAttachments ADD OwnerId INT NULL
EXEC ('UPDATE PersonAttachments SET OwnerID = (SELECT Max(Besitzer) FROM PersH WHERE PersH.PersNr = PersonAttachments.PersonId)')
ALTER TABLE PersonAttachments ALTER COLUMN OwnerId INT NOT NULL
INSERT INTO [dbo].[UserGruppe]
           ([GruppeID]
           ,[UserID]
           ,[Schreiben]
           ,[LM]
           ,[UM]
           ,[LC]
           ,[UC]
           ,[BerechtigungsbereichID]
           ,[OptionsFlag]
           ,[IsInherited]
           ,[Options])
     
           SELECT [GruppeID]
           ,[UserID]
           ,[Schreiben]
           ,[LM]
           ,[UM]
           ,[LC]
           ,[UC]
           ,13
           ,0
           ,[IsInherited]
           ,NULL FROM UserGruppe WHERE BerechtigungsbereichID = 0
END
GO


IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPersonAttachments]'))	DROP VIEW [dbo].[AbPersonAttachments]
GO
CREATE VIEW [dbo].[AbPersonAttachments]
AS 
--PersonAttachments SELECT VIEW
SELECT * FROM PersonAttachments WHERE PersonAttachments.PublicPermission = 0 OR PersonAttachments.PublicPermission = 2 OR
PersonAttachments.OwnerId IN(
SELECT GruppeId FROM UserGruppe AS UG 
INNER JOIN UserPw AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.BerechtigungsbereichID = 13)
WITH CHECK OPTION
GO
GRANT SELECT ON dbo.AbPersonAttachments TO Public
GO 

IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPersonAttachments_Update]'))	DROP VIEW [dbo].[AbPersonAttachments_Update]
GO
CREATE VIEW [dbo].[AbPersonAttachments_Update]
AS 
--PersonAttachments UPDATE VIEW
SELECT * FROM PersonAttachments WHERE PersonAttachments.OwnerId IN(
SELECT GruppeId FROM UserGruppe AS UG 
INNER JOIN UserPw AS U ON U.Userid = UG.UserID
WHERE U.UserName = CURRENT_USER AND UG.BerechtigungsbereichID = 13 AND UG.Schreiben = 1)
WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, INSERT, DELETE ON dbo.AbPersonAttachments_Update TO Public
GO 

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'CheckBudget' AND o.id = OBJECT_ID('dbo.OrderApprovalStatus'))
BEGIN
ALTER TABLE OrderApprovalStatus ADD CheckBudget BIT NOT NULL CONSTRAINT DF_OrderApprovalStatus_CheckBudget DEFAULT 0
GRANT SELECT ON Budgets TO BudgetWrite
END

--TK 2014-06-06
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Settings]')  AND name = 'IX_Setting_Form')
BEGIN 
	DELETE FROM Settings WHERE Settings.Form IS NULL
	-- da in lyon ein fehler kam beim umstellen der form spalte (daten in spalte größer 8060), räumen wir die tabelle erstmal auf
	DBCC CLEANTABLE (0,[dbo.Settings])
	ALTER TABLE Settings ALTER COLUMN Form VARCHAR(50) NOT NULL
	CREATE INDEX IX_Setting_Form ON dbo.Settings (Form) ON [PRIMARY]
	CREATE INDEX IX_Setting_UserCreate ON dbo.Settings (UC) ON [PRIMARY]
END
GO
--TK 2014-06-11
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'FieldChangeHistory' AND o.id = OBJECT_ID('dbo.AufführgDetails'))
BEGIN
	ALTER TABLE AufführgDetails ADD FieldChangeHistory VarChar(MAX)
	ALTER TABLE AufführgDetails ADD IncomeActualIsTemporary BIT NOT NULL CONSTRAINT DF_ActivityDetails_IncomeActualIsTemporary DEFAULT (0)
	ALTER TABLE AufführgDetails ADD BudgetNote VarChar(1000)
END
GO
--TK 2014-06-13
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.[SeasonSeatingPlanPriceCategories]') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.SeasonSeatingPlanPriceCategories (
		SeasonSeatingPlanPriceCategoryId INT IDENTITY(1, 1) NOT NULL,
		SeasonId INT NOT NULL,
		SeatingPlanId INT NULL,
		PriceCategoryId INT NOT NULL,
		IncomeMax FLOAT NULL,
		Note VARCHAR(500),	
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_SeasonSeatingPlansPriceCategoryId PRIMARY KEY CLUSTERED (SeasonSeatingPlanPriceCategoryId ASC) ON [PRIMARY],
		CONSTRAINT FK_SeasonSeatingPlanPriceCategories_Seasons FOREIGN KEY (SeasonId) REFERENCES dbo.SpielzeitTabelle (SpzNr),
		CONSTRAINT FK_SeasonSeatingPlanPriceCategories_SeatingPlans FOREIGN KEY (SeatingPlanId) REFERENCES dbo.SeatingPlans (SeatingPlanId),
		CONSTRAINT FK_SeasonSeatingPlanPriceCategories_PriceCategories FOREIGN KEY (PriceCategoryId) REFERENCES dbo.Preise (PreisNr),
		CONSTRAINT UQ_CashFundPositionValidationStatus_Seasons_SeatingPlans_PriceCategories UNIQUE (SeasonId, SeatingPlanId, PriceCategoryId)
	) ON [PRIMARY]
END
--TH 2014-06-18
--Spalte Orderstatus entfernen und DeliveryStatus/PaymentStatus anlegen
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'Orderstatus' AND o.id = OBJECT_ID('dbo.Orders'))
BEGIN
ALTER TABLE Orders DROP DF_Orders_OrderStatus
DROP INDEX IX_Orders_OrderStatus ON Orders 
ALTER TABLE Orders DROP COLUMN Orderstatus
ALTER TABLE Orders ADD DeliveryStatus INT NOT NULL CONSTRAINT DF_Orders_DeliveryStatus DEFAULT 0
ALTER TABLE Orders ADD PaymentStatus INT NOT NULL CONSTRAINT DF_Orders_PaymentStatus DEFAULT 0
END

IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'IsPermanent' AND o.id = OBJECT_ID('dbo.CashFunds'))
BEGIN
ALTER TABLE CashFunds ADD IsPermanent BIT NOT NULL CONSTRAINT DF_CashFunds_IsPermanent DEFAULT 0
		CREATE INDEX SeasonSeatingPlanPriceCategories_Season ON dbo.SeasonSeatingPlanPriceCategories (SeasonId)
		CREATE INDEX SeasonSeatingPlanPriceCategories_PriceCategory ON dbo.SeasonSeatingPlanPriceCategories (PriceCategoryId)
END
GO
GRANT SELECT ON dbo.SeasonSeatingPlanPriceCategories TO Public
GRANT INSERT, SELECT, UPDATE, DELETE ON dbo.SeasonSeatingPlanPriceCategories TO [Vorverkauf ändern]
GO

--TH 2014-06-23
-- Neue Spalte die angibt, ob beim setzten dieses Status der Ersteller der Bestellung benachrichtigt werden soll.
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'NotifyCreator' AND o.id = OBJECT_ID('dbo.OrderValidationApprovalStatus'))
BEGIN
ALTER TABLE OrderValidationApprovalStatus ADD NotifyCreator BIT NOT NULL CONSTRAINT DF_OrderValidationApprovalStatus_NotifyCreator DEFAULT 0
END

--TH 2014-06-23
-- Neue Tabelle für Reisende
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.[OrderTravelers]') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.OrderTravelers (
		OrderTravelerId INT IDENTITY(1, 1) NOT NULL,
		OrderId INT NOT NULL,
		TravelerId INT NULL,
		Note VARCHAR(500),	
		LM DATETIME NOT NULL,
		UM INT NOT NULL,
		LC DATETIME NOT NULL,
		UC INT NOT NULL,
		CONSTRAINT PK_OrderTravelerId PRIMARY KEY CLUSTERED (OrderTravelerId ASC) ON [PRIMARY],
		CONSTRAINT FK_OrderTravelers_Orders FOREIGN KEY (OrderId) REFERENCES dbo.Orders (OrderId),
		CONSTRAINT FK_OrderTravelers_Persons FOREIGN KEY (TravelerId) REFERENCES dbo.PersH (PersNr),
		CONSTRAINT UQ_OrderTravelers_Orders_Persons UNIQUE (OrderId, TravelerId)
	) ON [PRIMARY]
END

GRANT INSERT, SELECT, UPDATE, DELETE ON dbo.OrderTravelers TO public

--TH 2014-06-24
--Neue Spalte, die den Typ der Typ der CashFundPosition angibt
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'CashFundPositionType' AND o.id = OBJECT_ID('dbo.CashFundPositions'))
BEGIN
ALTER TABLE CashFundPositions ADD CashFundPositionType INT NOT NULL CONSTRAINT DF_CashFundPositionss_CashFundPositionType DEFAULT 0
END


--Neue Spalte für die Zuordnung eines Validierungsshcritts zu einem CashFundPositionType
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'CashFundPositionType' AND o.id = OBJECT_ID('dbo.CashFundPositionValidationStatus'))
BEGIN
ALTER TABLE CashFundPositionValidationStatus ADD CashFundPositionType INT NOT NULL CONSTRAINT DF_CashFundPositionValidationStatus_CashFundPositionType DEFAULT 0
ALTER TABLE CashFundPositionValidationStatus DROP CONSTRAINT UQ_CashFundPositionValidationStatus_CashFundstatus_CostCenter
ALTER TABLE CashFundPositionValidationStatus ADD CONSTRAINT UQ_CashFundPositionValidationStatus_CashFundstatus_CostCenter UNIQUE (CashFundStatusId, CostCenterId, CashFundPositionType)
END

IF NOT EXISTS (SELECT * FROM syscolumns c INNER JOIN sysObjects o ON c.id = o.id WHERE c.name = 'IsConsistent' AND o.id = OBJECT_ID('dbo.Orders'))
BEGIN
ALTER TABLE Orders ADD IsConsistent BIT NOT NULL CONSTRAINT DF_Orders_IsConsistent DEFAULT 0
END

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'CashFundNumber' AND o.id = OBJECT_ID('dbo.CashFunds'))
BEGIN
ALTER TABLE CashFunds DROP COLUMN CashFundNumber
END

--2014-06-23 sh
--sort spalte in tourneestatus
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('dbo.TourStatus'))
BEGIN
	ALTER TABLE TourStatus ADD Sort INT NOT NULL CONSTRAINT DF_TourStatus_Sort DEFAULT 0
END

--2014-06-26 sh
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'LayoutSettings' AND o.id = OBJECT_ID(N'[dbo].DienstplanArtenTabelle') AND c.xtype = 167 and c.[length]<>-1)
BEGIN
	ALTER TABLE DienstplanArtenTabelle ALTER COLUMN LayoutSettings varchar(MAX) NULL
END
GO
--TK 2014-06-11
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'SalesTaxType' AND o.id = OBJECT_ID('dbo.Vertrag'))
BEGIN
	ALTER TABLE Vertrag ADD SalesTaxType INT
END
GO
--TK 2014-06-25
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'BudgetValueFormula' AND o.id = OBJECT_ID('dbo.VertragsVorlagen'))
BEGIN
	ALTER TABLE VertragsVorlagen ADD BudgetValueFormula VARCHAR(MAX)
END
GO
--2014-07-04 SH
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'DataType' AND o.id = OBJECT_ID('dbo.ContractFieldTypes'))
BEGIN
	ALTER TABLE ContractFieldTypes ADD DataType int NOT NULL CONSTRAINT DF_ContractFieldTypes_DataType DEFAULT 0
	ALTER TABLE ContractFields ALTER COLUMN TextValue varchar(MAX) NULL
END
GO

--2014-07-08 TH
-- Neue Tabelle für OrderAttachments
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.OrderAttachments') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.OrderAttachments (
			OrderAttachmentId INT IDENTITY(1,1) NOT NULL,--ID
			OrderId INT NOT NULL, 
			AttachmentId INT NOT NULL, 
			Note VARCHAR (255) NULL,
			Sort INT NOT NULL CONSTRAINT DF_OrderAttachments_Sort DEFAULT(0),
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_OrderAttachments PRIMARY KEY CLUSTERED (OrderAttachmentId ASC) ON [PRIMARY]
			CONSTRAINT FK_OrderAttachments_Order FOREIGN KEY (OrderId) REFERENCES dbo.Orders (OrderId),
			CONSTRAINT FK_OrderAttachments_Attachment FOREIGN KEY (AttachmentId) REFERENCES dbo.[Attachments] (AttachmentId),
	) ON [PRIMARY]
	GRANT SELECT ON dbo.OrderAttachments TO [Public]
	GRANT DELETE ON dbo.OrderAttachments TO [Public]
	GRANT INSERT ON dbo.OrderAttachments TO [Public]
	GRANT UPDATE ON dbo.OrderAttachments TO [Public]
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'PermissionStatus' AND o.id = OBJECT_ID('dbo.DayNoteCategories'))
BEGIN
	ALTER TABLE DayNoteCategories ADD PermissionStatus INT NOT NULL CONSTRAINT DF_DayNoteCategories_PermissionStatus DEFAULT 0
END
GO

--2014-08-08 sh
-- spalte DayOffCredit in ZyklusWochen und Dienstplan
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'DayOffCredit' AND o.id = OBJECT_ID('dbo.ZyklusWochen'))
BEGIN
	ALTER TABLE ZyklusWochen ADD DayOffCredit INT NOT NULL CONSTRAINT DF_ZyklusWochen_DayOffCredit DEFAULT 0
	ALTER TABLE Dienstplan ADD DayOffCredit INT NOT NULL CONSTRAINT DF_Dienstplan_DayOffCredit DEFAULT 0
END
GO

--2014-07-29 SH
--neue tabellen für dienstplanfreigabe
--Tabelle für Dienstplanzeitraumstatus
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.DutyRosterPeriodStatus') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.DutyRosterPeriodStatus (
			DutyRosterPeriodStatusId INT IDENTITY(1,1) NOT NULL,--ID
			Name VARCHAR(30) NOT NULL, 
			IsClosedStatus BIT NOT NULL CONSTRAINT DF_DutyRosterPeriodStatus_IsClosedStatus DEFAULT 0,
			IsDraftStatus BIT NOT NULL CONSTRAINT DF_DutyRosterPeriodStatus_IsDraftStatus DEFAULT 0,
			IsReadOnlyStatus BIT NOT NULL CONSTRAINT DF_DutyRosterPeriodStatus_IsReadOnlyStatus DEFAULT 0,
			--PromptForChangeNotes BIT NOT NULL CONSTRAINT DF_DutyRosterPeriodStatus_PromptForChangeNotes DEFAULT 0,
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_DutyRosterPeriodStatus PRIMARY KEY CLUSTERED (DutyRosterPeriodStatusId ASC) ON [PRIMARY],
			CONSTRAINT IX_DutyRosterPeriodStatus_Name UNIQUE (Name)
	) ON [PRIMARY]
END
GO

	GRANT SELECT ON dbo.DutyRosterPeriodStatus TO [Public]
	GRANT DELETE ON dbo.DutyRosterPeriodStatus TO [PersoAdmin], PersoBasicDataWrite
	GRANT INSERT ON dbo.DutyRosterPeriodStatus TO [PersoAdmin], PersoBasicDataWrite
	GRANT UPDATE ON dbo.DutyRosterPeriodStatus TO [PersoAdmin], PersoBasicDataWrite
GO

--Tabelle für Dienstplanzeiträume
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.DutyRosterPeriods') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.DutyRosterPeriods (
			DutyRosterPeriodId INT IDENTITY(1,1) NOT NULL,--ID
			DepartmentId INT NOT NULL, 
			[Start] DateTime NOT NULL, 
			[End] DateTime NOT NULL,
			DutyRosterPeriodStatusId INT NOT NULL,
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_DutyRosterPeriods PRIMARY KEY CLUSTERED (DutyRosterPeriodId ASC) ON [PRIMARY]
			CONSTRAINT FK_DutyRosterPeriods_Departments FOREIGN KEY (DepartmentId) REFERENCES dbo.DienstplanArtenTabelle (DienstplanArtenID),
			CONSTRAINT FK_DutyRosterPeriods_DutyRosterPeriodStatus FOREIGN KEY (DutyRosterPeriodStatusId) REFERENCES dbo.DutyRosterPeriodStatus (DutyRosterPeriodStatusId),
			CONSTRAINT [UQ_DutyRosterPeriods_DepartmentId_Start_End_LC] UNIQUE (DepartmentId, Start, [End], LC)
	) ON [PRIMARY]
END
GO

--vorrübergehend alle berechtigungen für public, da datenklassen mit reines select + insert nicht umgehen können
GRANT SELECT ON dbo.DutyRosterPeriods TO [Public]
GRANT DELETE ON dbo.DutyRosterPeriods TO [Public], [PersoAdmin], PersoBasicDataWrite
GRANT INSERT ON dbo.DutyRosterPeriods TO [Public], [PersoAdmin], PersoBasicDataWrite
GRANT UPDATE ON dbo.DutyRosterPeriods TO [Public], [PersoAdmin], PersoBasicDataWrite
GO

--2014-09-16
--da ein view für die periods fehlt, erstmal insert auf public setzen
GRANT INSERT ON dbo.DutyRosterPeriods TO [Public]
GO

--Tabelle für Dienstplanfreigabemodellen
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.DutyRosterReleaseModels') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.DutyRosterReleaseModels (
			DutyRosterReleaseModelId INT IDENTITY(1,1) NOT NULL,--ID
			Name VARCHAR(25) NOT NULL,
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_DutyRosterReleaseModels PRIMARY KEY CLUSTERED (DutyRosterReleaseModelId ASC) ON [PRIMARY],
			CONSTRAINT IX_DutyRosterReleaseModels_Name UNIQUE (Name)
	) ON [PRIMARY]
END
GO

	GRANT SELECT ON dbo.DutyRosterReleaseModels TO [Public]
	GRANT DELETE ON dbo.DutyRosterReleaseModels TO [PersoAdmin], PersoBasicDataWrite
	GRANT INSERT ON dbo.DutyRosterReleaseModels TO [PersoAdmin], PersoBasicDataWrite
	GRANT UPDATE ON dbo.DutyRosterReleaseModels TO [PersoAdmin], PersoBasicDataWrite
GO

--Tabelle für Dienstplanfreigabeworkflows
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.DutyRosterReleaseWorkflows') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.DutyRosterReleaseWorkflows (
			DutyRosterReleaseWorkflowId INT IDENTITY(1,1) NOT NULL,--ID
			DutyRosterReleaseModelId INT NOT NULL,
			UserGroupId INT NOT NULL,
			FromStatusId INT NULL,
			ToStatusId INT NULL,
			CopyDutyRosterTargetId INT NULL,
			NotifyHeadOfDepartment BIT NOT NULL CONSTRAINT DF_DutyRosterReleaseWorkflows_NotifyHeadOfDepartment DEFAULT 0,
			MailingListId INT NULL,
			LC DATETIME NOT NULL,
			UC INT NOT NULL,
			LM DATETIME NOT NULL,
			UM INT NOT NULL
			CONSTRAINT PK_DutyRosterReleaseWorkflows PRIMARY KEY CLUSTERED (DutyRosterReleaseWorkflowId ASC) ON [PRIMARY],
			CONSTRAINT FK_DutyRosterReleaseWorkflows_DutyRosterReleaseModels FOREIGN KEY (DutyRosterReleaseModelId) REFERENCES dbo.DutyRosterReleaseModels (DutyRosterReleaseModelId),
			CONSTRAINT FK_DutyRosterReleaseWorkflows_UserPw FOREIGN KEY (UserGroupId) REFERENCES dbo.UserPw (UserID),
			CONSTRAINT FK_DutyRosterReleaseWorkflows_DutyRosterPeriodStatus_FromStatusId FOREIGN KEY (FromStatusId) REFERENCES dbo.DutyRosterPeriodStatus (DutyRosterPeriodStatusId),
			CONSTRAINT FK_DutyRosterReleaseWorkflows_DutyRosterPeriodStatus_ToStatusId FOREIGN KEY (ToStatusId) REFERENCES dbo.DutyRosterPeriodStatus (DutyRosterPeriodStatusId),
			CONSTRAINT FK_DutyRosterReleaseWorkflows_DienstplanEintragArt FOREIGN KEY (CopyDutyRosterTargetId) REFERENCES dbo.DienstplanEintragArt (DienstplanEintragArtId),
			CONSTRAINT FK_DutyRosterReleaseWorkflows_MailingList FOREIGN KEY (MailingListId) REFERENCES dbo.Verteiler (VerteilerID),
			CONSTRAINT UQ_DutyRosterReleaseWorkflows_DutyRosterReleaseModelId_UserGroupId_FromStatusId_ToStatusId UNIQUE (DutyRosterReleaseModelId, UserGroupId, FromStatusId, ToStatusId)
	) ON [PRIMARY]
END
GO

GRANT SELECT ON dbo.DutyRosterReleaseWorkflows TO [Public]
GRANT DELETE ON dbo.DutyRosterReleaseWorkflows TO [PersoAdmin], PersoBasicDataWrite
GRANT INSERT ON dbo.DutyRosterReleaseWorkflows TO [PersoAdmin], PersoBasicDataWrite
GRANT UPDATE ON dbo.DutyRosterReleaseWorkflows TO [PersoAdmin], PersoBasicDataWrite
GO

--verweis von abteilung auf dienstplanfreigabemodel
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'DutyRosterReleaseModelId' AND o.id = OBJECT_ID('dbo.DienstplanArtenTabelle'))
BEGIN
	ALTER TABLE DienstplanArtenTabelle ADD DutyRosterReleaseModelId INT NULL

	ALTER TABLE [dbo].DienstplanArtenTabelle  WITH CHECK ADD CONSTRAINT FK_DienstplanArtenTabelle_DutyRosterReleaseModels FOREIGN KEY(DutyRosterReleaseModelId)
	REFERENCES [dbo].DutyRosterReleaseModels (DutyRosterReleaseModelId)

	ALTER TABLE DienstplanArtenTabelle ADD HeadOfDepartmentId INT NULL

	ALTER TABLE [dbo].DienstplanArtenTabelle  WITH CHECK ADD CONSTRAINT FK_DienstplanArtenTabelle_Persons FOREIGN KEY(HeadOfDepartmentId)
	REFERENCES [dbo].PersH (PersNr)
END
GO

--standardwerte für die neuen dutyrostertabellen einfügen
IF NOT EXISTS (SELECT * FROM DutyRosterPeriodStatus WHERE IsClosedStatus = 1)
BEGIN

	DECLARE @country VARCHAR(20)
	SELECT @country = WertText FROM Settings WHERE Form = 'Adresse' AND Control = 'Country'
	
	INSERT INTO DutyRosterPeriodStatus (Name, IsClosedStatus, IsDraftStatus, IsReadOnlyStatus, LC, UC, LM, UM)
	VALUES (
	CASE @country
		WHEN 'FI' THEN 'Tilitetty'
		WHEN 'EN' THEN 'Closed'
		WHEN 'F'  THEN 'Clôturé'
		WHEN 'BE' THEN 'Clôturé'
		WHEN 'NL' THEN 'Gesloten'
		ELSE 'Abgeschlossen'
	END  , 1, DEFAULT, DEFAULT, GETDATE(), 0, GETDATE(), 0);
END
GO

IF NOT EXISTS (SELECT * FROM DutyRosterPeriodStatus WHERE IsDraftStatus = 1)
BEGIN
	DECLARE @country VARCHAR(20)
	SELECT @country = WertText FROM Settings WHERE Form = 'Adresse' AND Control = 'Country'
	
	INSERT INTO DutyRosterPeriodStatus (Name, IsClosedStatus, IsDraftStatus, IsReadOnlyStatus, LC, UC, LM, UM)
	VALUES (
	CASE @country
		WHEN 'FI' THEN 'Luonnos'
		WHEN 'EN' THEN 'Draft'
		WHEN 'F'  THEN 'Conception'
		WHEN 'BE' THEN 'Conception'
		WHEN 'NL' THEN 'Ontwerp'
		ELSE 'Entwurf'
	END  , DEFAULT, 1, DEFAULT, GETDATE(), 0, GETDATE(), 0);
END
GO

--sollplan umbenennen
IF EXISTS (SELECT * FROM DienstplanEintragArt dea WHERE dea.DienstplanEintragArtId = 1 AND dea.Bezeichnung = 'SOLL')
BEGIN
	DECLARE @country VARCHAR(20)
	SELECT @country = WertText FROM Settings WHERE Form = 'Adresse' AND Control = 'Country'
	
	UPDATE DienstplanEintragArt SET Bezeichnung = 
	CASE @country
		WHEN 'FI' THEN 'Veloitus (kopio)'
		WHEN 'EN' THEN 'Debit (Copy)'
		WHEN 'F'  THEN 'Théorique (copie)'
		WHEN 'BE' THEN 'Théorique (copie)'
		WHEN 'NL' THEN 'Gewenst (kopie)'
		ELSE 'Soll (Kopie)'
	END WHERE DienstplanEintragArtId = 1 AND Bezeichnung='SOLL'
END
GO

--istplan umbenennen
IF EXISTS (SELECT * FROM DienstplanEintragArt dea WHERE dea.DienstplanEintragArtId = 0 AND dea.Bezeichnung = 'PLAN')
BEGIN
	DECLARE @country VARCHAR(20)
	SELECT @country = WertText FROM Settings WHERE Form = 'Adresse' AND Control = 'Country'
	
	UPDATE DienstplanEintragArt SET Bezeichnung = 
	CASE @country
		WHEN 'FI' THEN 'Työvuorolista'
		WHEN 'EN' THEN 'Roster'
		WHEN 'F'  THEN 'Planning de travail'
		WHEN 'BE' THEN 'Planning de travail'
		WHEN 'NL' THEN 'Werkplan'
		ELSE 'Arbeitsplan'
	END WHERE DienstplanEintragArtId = 0 AND Bezeichnung='PLAN'
END
GO

--bisherigen wochenabschlüsse umschreiben
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 144 OR (Minor = 144 AND Build < 5)))))
BEGIN
	DECLARE @statusId INT;
	SELECT @statusId = DutyRosterPeriodStatusId from DutyRosterPeriodStatus where IsClosedStatus = 1 
	
	INSERT INTO 
		DutyRosterPeriods (DepartmentId, Start, [End], DutyRosterPeriodStatusId, LC, UC, LM, UM)
	SELECT 
		dat.DienstplanArtenID, '01.01.1900', dat.ArchivDatum, @statusId, GETDATE(), 0, GETDATE(), 0 
	FROM 
		DienstplanArtenTabelle dat
	WHERE 
		dat.ArchivDatum IS NOT NULL 
		AND dat.DutyRosterReleaseModelId IS NULL
		 AND NOT EXISTS (SELECT * FROM DutyRosterPeriods drp WHERE dat.DienstplanArtenID = drp.DepartmentId)
END
--2014-08-08 sh
-- spalte DayOffCredit in ZyklusWochen und Dienstplan
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'DayOffCredit' AND o.id = OBJECT_ID('dbo.ZyklusWochen'))
BEGIN
	ALTER TABLE ZyklusWochen ADD DayOffCredit INT NOT NULL CONSTRAINT DF_ZyklusWochen_DayOffCredit DEFAULT 0
	ALTER TABLE Dienstplan ADD DayOffCredit INT NOT NULL CONSTRAINT DF_Dienstplan_DayOffCredit DEFAULT 0
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'RoyaltyPercentage' and o.id = OBJECT_ID(N'dbo.WorkVersions'))
BEGIN
	ALTER TABLE dbo.WorkVersions ADD RoyaltyPercentage FLOAT NULL
END
GO

--2014-08-12 TH
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id WHERE c.name = 'IsRehearsalStage' AND o.id = OBJECT_ID('dbo.Zr'))
BEGIN
	ALTER TABLE Zr ADD IsRehearsalStage BIT NOT NULL CONSTRAINT DF_Zr_IsRehearsalStage DEFAULT 1
	EXEC ('UPDATE Zr SET IsRehearsalStage = 0 WHERE ZrPl > 0 OR GastSpiel <> 0')
END
GO

--2014-08-26 TH
-- Die Spalte CashFundPositionReference ist nun nullable
ALTER TABLE CashFundPositions ALTER COLUMN CashFundPositionReference VARCHAR(200) NULL

IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[Vertrag]')  AND name = 'IX_Contract_ContractIdOwnerGroup')
CREATE INDEX IX_Contract_ContractIdOwnerGroup ON dbo.Vertrag
	(VertragsNr, ModulGruppeID) ON [PRIMARY]
GO

-- 2014-09-08 TH
-- Neue Tabelle um Konten für die Budgetverwaltung pro Budgetperiode und Abteilung sperren zu können
-- Ein Eintrag in dieser Tabelle bedeutet, dass der Wert gesperrt ist
-- BEnötigt für die Tabellen Kosten und BudgetItem
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.BlockedCostTypes') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.BlockedCostTypes (
				BlockedCostTypeId INT IDENTITY(1,1) NOT NULL,--ID
				CostTypeId INT NOT NULL,
				CostCenterId INT NOT NULL,
				BudgetPeriodId INT NOT NULL,
				LC DATETIME NOT NULL,
				UC INT NOT NULL,
				LM DATETIME NOT NULL,
				UM INT NOT NULL
				CONSTRAINT PK_BlockedCostTypes PRIMARY KEY CLUSTERED (BlockedCostTypeId ASC) ON [PRIMARY],
				CONSTRAINT FK_BlockedCostTypes_CostTypes FOREIGN KEY (CostTypeId) REFERENCES dbo.CostTypes (CostTypeId) ON DELETE CASCADE,
				CONSTRAINT FK_BlockedCostTypes_CostCenter FOREIGN KEY (CostCenterId) REFERENCES dbo.CostCenter (CostCenterId) ON DELETE CASCADE,
				CONSTRAINT FK_BlockedCostTypes_BudgetPeriod FOREIGN KEY (BudgetPeriodId) REFERENCES dbo.BudgetPeriods (BudgetPeriodId) ON DELETE CASCADE,
				CONSTRAINT UQ_BlockedCostTypes_CostTypeId_CostCenterId_BudgetPeriodId UNIQUE (CostTypeId, CostCenterId, BudgetPeriodId)
		) ON [PRIMARY]
	GRANT SELECT ON dbo.BlockedCostTypes TO [Public]
	GRANT DELETE, INSERT, UPDATE ON dbo.BlockedCostTypes TO CostsWrite

	CREATE TABLE dbo.BlockedBudgetItems (
				BlockedBudgetItemId INT IDENTITY(1,1) NOT NULL,--ID
				BudgetItemId INT NOT NULL,
				CostCenterId INT NOT NULL,
				BudgetPeriodId INT NOT NULL,
				LC DATETIME NOT NULL,
				UC INT NOT NULL,
				LM DATETIME NOT NULL,
				UM INT NOT NULL
				CONSTRAINT PK_BlockedBudgetItems PRIMARY KEY CLUSTERED (BlockedBudgetItemId ASC) ON [PRIMARY],
				CONSTRAINT FK_BlockedBudgetItems_BudgetItem FOREIGN KEY (BudgetItemId) REFERENCES dbo.BudgetItem (BudgetItemId) ON DELETE CASCADE,
				CONSTRAINT FK_BlockedBudgetItems_CostCenter FOREIGN KEY (CostCenterId) REFERENCES dbo.CostCenter (CostCenterId) ON DELETE CASCADE,
				CONSTRAINT FK_BlockedBudgetItems_BudgetPeriod FOREIGN KEY (BudgetPeriodId) REFERENCES dbo.BudgetPeriods (BudgetPeriodId) ON DELETE CASCADE,
				CONSTRAINT UQ_BlockedBudgetItems_BudgetItemId_CostCenterId_BudgetPeriodId UNIQUE (BudgetItemId, CostCenterId, BudgetPeriodId)
		) ON [PRIMARY]
	GRANT SELECT ON dbo.BlockedBudgetItems TO [Public]
	GRANT DELETE, INSERT, UPDATE ON dbo.BlockedBudgetItems TO CostsWrite
END

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UQ_ContractTypeDepartment_DepartmentId_ContractTypeId]') )
BEGIN
		ALTER TABLE ContractType_Department ADD CONSTRAINT UQ_ContractTypeDepartment_DepartmentId_ContractTypeId UNIQUE (DepartmentId, ContractTypeId)
END
GO


-- ENDE
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'DebitServicesCountPerSeason' and o.id = OBJECT_ID(N'dbo.VertragsVorlagen'))
BEGIN
	ALTER TABLE dbo.VertragsVorlagen ADD DebitServicesCountPerSeason FLOAT NOT NULL CONSTRAINT [DF_ContractType_DebitServicesCountPerSeason] DEFAULT (0) 
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns c 
	WHERE c.name = 'TemplateId' and c.id = OBJECT_ID(N'OrderValidationTypes'))
BEGIN
	ALTER TABLE OrderValidationTypes ADD TemplateId INT NULL  
	ALTER TABLE OrderValidationTypes WITH CHECK ADD CONSTRAINT FK_OrderValidationTypes_Templates FOREIGN KEY(TemplateId)
	REFERENCES [dbo].Vorlagen (VorlagenID)
END
GO

-- 2014-09-18 TH:
--PeriodConverter aus PersStatusConverter entfernt
--Es werden nun die Felder Startdate und enddate verwendet
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 144 OR (Minor = 144 AND Build < 101)))))
BEGIN
	UPDATE PlanSort SET ContentPath = 'startdate' WHERE PlansortId IN(
	SELECT PC.plansortid FROM PlanSort AS PC
	INNER JOIN PlanSpalte PS ON PS.SpalteID = PC.SpalteID
	INNER JOIN [Plan] P ON P.PlanID = PS.PlanID
	WHERE Planart = 170 AND PC.ContentPath = 'period.start')
	UPDATE PlanSort SET ContentPath = 'enddate' WHERE PlansortId IN(
	SELECT PC.plansortid FROM PlanSort AS PC
	INNER JOIN PlanSpalte PS ON PS.SpalteID = PC.SpalteID
	INNER JOIN [Plan] P ON P.PlanID = PS.PlanID
	WHERE Planart = 170 AND PC.ContentPath = 'period.end')
END
GO

-- 2014-09-18 TH:
-- FEhlende Spalten im CashFund hinzugefügt
IF NOT EXISTS (SELECT * FROM sysColumns c 
	WHERE c.name = 'NotPaid' and c.id = OBJECT_ID(N'Orders'))
BEGIN
	ALTER TABLE dbo.Orders ADD NotPaid BIT NOT NULL CONSTRAINT [DF_Orders_NotPaid] DEFAULT (0) 
	ALTER TABLE dbo.CashFunds ADD Note VARCHAR(255) NULL
END
GO
--2014-09-29 TK
IF NOT EXISTS (SELECT * FROM sysColumns c 
	WHERE c.name = 'Module' and c.id = OBJECT_ID(N'CostCenter'))
BEGIN
	ALTER TABLE dbo.CostCenter ADD Module INT NOT NULL CONSTRAINT [DF_CostCenter_Module] DEFAULT (0) 
	EXEC ('UPDATE CostCenter SET Module = Module|1 WHERE UsedInProgramFunctions&1 = 1')
	EXEC ('UPDATE CostCenter SET Module = Module|4 WHERE UsedInProgramFunctions&2 = 2')
	EXEC ('UPDATE CostCenter SET Module = Module|16 WHERE UsedInProgramFunctions&4 = 4')
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns AS c WHERE c.name = 'AccountancyPrintCount' and c.id = OBJECT_ID(N'Orders'))
BEGIN
	ALTER TABLE dbo.Orders ADD AccountancyPrintCount INT NOT NULL CONSTRAINT [DF_OrdersAccountancyPrintCount] DEFAULT (0)
END
GO

IF NOT EXISTS (SELECT * FROM sysColumns AS c WHERE c.name = 'InvoiceFollows' and c.id = OBJECT_ID(N'Orders'))
BEGIN
	ALTER TABLE dbo.Orders ADD InvoiceFollows BIT NOT NULL CONSTRAINT [DF_OrdersInvoiceFollows] DEFAULT (0)
END
GO


--2014-09-30 TH:
--Neue Tabelle für OrderHistory
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.OrderHistory') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.OrderHistory (
				OrderHistoryId INT IDENTITY(1,1) NOT NULL,--ID
				OrderId INT NULL,
				OrderPositionId INT NULL,
				WhatWasChanged VARCHAR(1000) NULL,
				ChangeType INT NOT NULL CONSTRAINT [DF_OrderHistory_ChangeType] DEFAULT (0),
				LC DATETIME NOT NULL,
				UC INT NOT NULL,
				LM DATETIME NOT NULL,
				UM INT NOT NULL
				CONSTRAINT PK_OrderHistory PRIMARY KEY CLUSTERED (OrderHistoryId ASC) ON [PRIMARY],
				--Keine FKs, Da es sich auch um Verknüpfungen zu gelöschten Daten handeln kann
				--CONSTRAINT FK_OrderHistory_BudgetItem FOREIGN KEY (OrderId) REFERENCES dbo.Orders (OrderId)
				--CONSTRAINT FK_OrderHistory_CostCenter FOREIGN KEY (OrderPositionId) REFERENCES dbo.OrderPositions (OrderPositionId)
		) ON [PRIMARY]
	GRANT SELECT ON dbo.OrderHistory TO [Public] --ggf Leserechte beschränken
	GRANT DELETE, INSERT, UPDATE ON dbo.OrderHistory TO PUBLIC
END

IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 145 OR (Minor = 145 AND Build < 6)))))
BEGIN
ALTER TABLE OrderHistory ALTER COLUMN WhatWasChanged VARCHAR(MAX) NULL
END
-- 2014-11-09 DH:
-- Neue Tabelle für CostUnitProduction
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('dbo.CostUnitProduction') AND OBJECTPROPERTY(id,'IsUserTable') = 1)
BEGIN
	CREATE TABLE dbo.CostUnitProduction (
				CostUnitProductionId INT IDENTITY(1,1) NOT NULL,--ID
				ProductionId INT NOT NULL,
				CostUnitId INT NOT NULL,				
				LC DATETIME NOT NULL,
				UC INT NOT NULL,
				LM DATETIME NOT NULL,
				UM INT NOT NULL
				CONSTRAINT PK_CostUnitProductionId PRIMARY KEY CLUSTERED (CostUnitProductionId ASC) ON [PRIMARY],				
				CONSTRAINT FK_CostUnitProduction_Production FOREIGN KEY (ProductionId) REFERENCES dbo.Stücke (SNr) on delete Cascade,
				CONSTRAINT FK_CostUnitProduction_CostUnit FOREIGN KEY (CostUnitId) REFERENCES dbo.CostUnit (CostUnitId) on delete Cascade
		) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IX_CostUnitProduction_ProductionId] ON [dbo].[CostUnitProduction] ([ProductionId])
	CREATE NONCLUSTERED INDEX [IX_CostUnitProduction_CostUnitId] ON [dbo].[CostUnitProduction] ([CostUnitId])
	CREATE UNIQUE NONCLUSTERED INDEX [IX_CostUnitProduction_ProductionIdCostUnitID] on [dbo].[CostUnitProduction] ([ProductionId],[CostUnitId])
	GRANT SELECT ON dbo.CostUnitProduction TO [Public] 
	GRANT DELETE, INSERT, UPDATE ON dbo.CostUnitProduction TO [Stammdaten ändern]
	GRANT DELETE, INSERT, UPDATE ON dbo.CostUnitProduction TO [CostsWrite]
exec ('
	Insert Into dbo.CostUnitProduction
	(ProductionId,CostUnitId,uc,um,lc,lm)
	select ProductionID,CostUnitId,uc,um,lc,lm from dbo.CostUnit where productionid is not null' )
END 

--2014-10-17 SH
--neue spalte bemerkung für resources
IF NOT EXISTS (SELECT * FROM sysColumns AS c WHERE c.name = 'Note' and c.id = OBJECT_ID(N'Resources'))
BEGIN
	ALTER TABLE dbo.Resources ADD Note VARCHAR(50)
END
GO
--2014-11-03 TK
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[ContractType_Department]')  AND name = 'IX_ContractType_Department_ContractTypeId_DepartmentId')
BEGIN
	DELETE FROM  ContractType_Department WHERE ContractType_Departmentid IN ( SELECT MIN (ContractType_Departmentid)   FROM [dbo].[ContractType_Department] GROUP BY [ContractTypeId], [DepartmentId] HAVING COUNT(*) > 1)
	DELETE FROM  ContractType_Department WHERE ContractType_Departmentid IN ( SELECT MIN (ContractType_Departmentid)   FROM [dbo].[ContractType_Department] GROUP BY [ContractTypeId], [DepartmentId] HAVING COUNT(*) > 1)
	DELETE FROM  ContractType_Department WHERE ContractType_Departmentid IN ( SELECT MIN (ContractType_Departmentid)   FROM [dbo].[ContractType_Department] GROUP BY [ContractTypeId], [DepartmentId] HAVING COUNT(*) > 1)
	CREATE UNIQUE NONCLUSTERED INDEX [IX_ContractType_Department_ContractTypeId_DepartmentId] ON [dbo].[ContractType_Department] (ContractTypeId ASC, DepartmentId  ASC) ON [PRIMARY]
END
GO

--2014-11-21 DH 
 UPDATE dbo.BesetzungStd
  SET ABGruppeID= null
  WHERE ABGruppeID NOT IN (SELECT ABGruppeID FROM dbo.ABGruppe)
 UPDATE dbo.AuffTechAufgabe
  SET ABGruppeID= null
  WHERE ABGruppeID NOT IN (SELECT ABGruppeID FROM dbo.ABGruppe)

 IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_BesetzungStd_ABGruppe') AND type = 'F')
		exec('ALTER TABLE dbo.besetzungstd WITH CHECK ADD CONSTRAINT FK_BesetzungStd_ABGruppe 
		FOREIGN KEY (abGruppeId) REFERENCES abgruppe(abgruppeid)')
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.FK_BesetzungStd_ABGruppe') AND type = 'F')
		exec('ALTER TABLE dbo.AuffTechAufgabe WITH CHECK ADD CONSTRAINT FK_AuffTechAufgabe 
		FOREIGN KEY (AbGruppeId) REFERENCES AbGruppe(AbGruppeId)')
go

--2014-12-04 sh
--umscheiben von usedinprogramfunctions in modulflag nochmal,
--da das original erhebliche fehler beinhaltet hat
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 145 OR (Minor = 145 AND Build < 101)))))
BEGIN
	EXEC ('UPDATE CostCenter SET Module = Module|1 WHERE UsedInProgramFunctions&1 = 1')
	EXEC ('UPDATE CostCenter SET Module = Module|4 WHERE UsedInProgramFunctions&2 = 2')
	EXEC ('UPDATE CostCenter SET Module = Module|16 WHERE UsedInProgramFunctions&4 = 4')
END
GO

--tk 2014-10-20 
IF EXISTS (SELECT * FROM Stücke WHERE typId = 0 AND Snr > 0) 
BEGIN
	DECLARE @typId INT
	SELECT @typId = typId FROM typ WHERE TypBez Like '%Sonst%' OR TypBez LIKE '%Sonderveranstaltung%' OR TypBez LIKE '%Allgemein%' OR TypBez LIKE '%Event%' OR TypBez LIKE  '%Special%' OR TypBez LIKE  '%Others%' OR TypBez LIKE '%misc%'
	IF (@typId = 0 OR @typId IS NULL)
	BEGIN
		SELECT TOP 1 @typId = typId FROM typ WHERE typId <> 0
	END
	UPDATE Stücke SET typId = @typId WHERE  typId = 0 AND Snr > 0
END
GO

GO
--tk 2014-12-04
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = '[Format]' AND o.id = OBJECT_ID(N'[dbo].DayNotes') AND c.prec < 1024)
BEGIN
	ALTER TABLE DayNotes ALTER COLUMN [Format] VARCHAR(1024)
END
GO
--2014-11-21 TK
IF NOT EXISTS (SELECT * FROM sysColumns c 
	WHERE c.name = 'Module' and c.id = OBJECT_ID(N'BudgetItem'))
BEGIN
	ALTER TABLE dbo.BudgetItem ADD Module INT NOT NULL CONSTRAINT [DF_BudgetItem_Module] DEFAULT (0) 
	EXEC ('UPDATE BudgetItem SET Module = 1 WHERE UsedInProgramFunctions = 1')
	EXEC ('UPDATE BudgetItem SET Module = 4 WHERE UsedInProgramFunctions = 2')
	EXEC ('UPDATE BudgetItem SET Module = 16 WHERE UsedInProgramFunctions = 4')
END
GO

--2014-12-01 sh
--währeungsspalte in lohnarten für kassenanordnungen/loga
IF NOT EXISTS (SELECT * FROM sysColumns c WHERE c.name = 'UnitId' and c.id = OBJECT_ID(N'WageType'))
BEGIN
	ALTER TABLE dbo.WageType ADD UnitId INT NULL CONSTRAINT [FK_WageType_Currency] FOREIGN KEY (UnitId) REFERENCES dbo.Currency(CurrencyId)
END
GO
IF NOT EXISTS (SELECT * FROM sysColumns c 
	WHERE c.name = 'IsMale' and c.id = OBJECT_ID(N'ProductionBonus'))
BEGIN
	ALTER TABLE dbo.ProductionBonus ADD IsMale BIT NULL 
END
GO


GO
 /**2014-12-18,DH
  Berechtigung umgestellt für Pläne **/
 -- 2015-01-26 sh   Anpassung sodass freigabe der pläne auch ausgewertet wird

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPlanConfiguration]'))
	BEGIN
drop VIEW [dbo].[AbPlanConfiguration]
END
go
CREATE VIEW [dbo].[AbPlanConfiguration]
AS 
SELECT  p.* FROM [Plan] AS p
WHERE p.OwnerId IN (
		SELECT UserGruppe.GruppeID 
		FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 11
	)
	OR p.PlanID IN (
		SELECT pps.PlanId FROM PlanPermissionSettings AS pps
		INNER JOIN UserPw AS g ON pps.UserId = g.UserID
		INNER JOIN UsersInGroups AS uig ON g.UserId = uig.GroupId  
		INNER JOIN UserPw AS u ON uig.UserId = u.UserID AND u.UserName = CURRENT_USER
	)
WITH CHECK OPTION
go
GRANT SELECT ON [dbo].[AbPlanConfiguration] to [public]
go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPlanConfiguration_Update]'))
		BEGIN
drop VIEW [dbo].[AbPlanConfiguration_Update]
		END
go

CREATE VIEW [dbo].[AbPlanConfiguration_Update]
AS 
SELECT  p.*  FROM  [Plan]  AS p WHERE p.OwnerId IN
	   (SELECT UserGruppe.GruppeID 
		FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 11
			AND UserGruppe.Schreiben = 1)
WITH CHECK OPTION
go
GRANT SELECT ON [dbo].[AbPlanConfiguration_Update] TO Public
GRANT DELETE ON [dbo].[AbPlanConfiguration_Update] TO Public
GRANT INSERT ON [dbo].[AbPlanConfiguration_Update] TO Public
GRANT UPDATE ON [dbo].[AbPlanConfiguration_Update] TO Public
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPlanColumn]'))
BEGIN
drop VIEW [dbo].[AbPlanColumn]
		END
go
CREATE VIEW [dbo].[AbPlanColumn]
AS 
SELECT  ps.*  FROM [PlanSpalte] ps inner join [Plan]  AS p on ps.PlanID=p.PlanID WHERE p.OwnerId IN
	   (SELECT UserGruppe.GruppeID 
		FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 11
			)
WITH CHECK OPTION
go
grant select on [dbo].[AbPlanColumn] to [public]
go

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPlanColumn_update]'))
BEGIN
drop VIEW [dbo].[AbPlanColumn_update]
		END
go
CREATE VIEW [dbo].[AbPlanColumn_update]
AS 
SELECT  ps.*  FROM [PlanSpalte] ps inner join [Plan]  AS p on ps.PlanID=p.PlanID WHERE p.OwnerId IN
	   (SELECT UserGruppe.GruppeID 
		FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 11
		and UserGruppe.Schreiben=1	)
WITH CHECK OPTION
go
GRANT SELECT ON [dbo].[AbPlanColumn_update] TO Public
GRANT DELETE ON [dbo].[AbPlanColumn_update] TO Public
GRANT INSERT ON [dbo].[AbPlanColumn_update] TO Public
GRANT UPDATE ON [dbo].[AbPlanColumn_update] TO Public
go

IF NOT EXISTS (SELECT * FROM sysColumns c 
	WHERE c.name = 'FilterSettings' and c.id = OBJECT_ID(N'RapportSpalte'))
BEGIN
	ALTER TABLE RapportSpalte ADD FilterSettings VARCHAR(MAX) NULL;
END

GO
--TK2014-12-17
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'UseWorkTimeEveryWeekday' and o.id = OBJECT_ID(N'dbo.AzTypen'))
BEGIN
	ALTER TABLE dbo.AzTypen ADD UseWorkTimeEveryWeekday BIT NOT NULL CONSTRAINT [DF_AzTypen_UseWorkTimeEveryWeekday] DEFAULT (0)
END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPlanSort]'))
BEGIN
	drop VIEW [dbo].[AbPlanSort]
END
GO
CREATE VIEW [dbo].[AbPlanSort]
AS 
SELECT  pso.*  FROM [PlanSort] pso inner join PlanSpalte ps on pso.SpalteID=ps.SpalteID inner join [Plan]  AS p on ps.PlanID=p.PlanID WHERE p.OwnerId IN
	   (SELECT UserGruppe.GruppeID 
		FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 11
			)
WITH CHECK OPTION
go
grant select on [dbo].[AbPlanSort] to [public]
go

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPlanSort_update]'))
		BEGIN
drop VIEW [dbo].[AbPlanSort_update]
		END
go
CREATE VIEW [dbo].[AbPlanSort_update]
AS 
SELECT  pso.*  FROM [PlanSort] pso inner join PlanSpalte ps on pso.SpalteID=ps.SpalteID inner join [Plan]  AS p on ps.PlanID=p.PlanID WHERE p.OwnerId IN
	   (SELECT UserGruppe.GruppeID 
		FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 11
		and UserGruppe.Schreiben=1	)
WITH CHECK OPTION
go
GRANT SELECT ON [dbo].[AbPlanSort_update] TO Public
GRANT DELETE ON [dbo].[AbPlanSort_update] TO Public
GRANT INSERT ON [dbo].[AbPlanSort_update] TO Public
GRANT UPDATE ON [dbo].[AbPlanSort_update] TO Public
go

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPlanStages]'))
BEGIN
drop VIEW [dbo].[AbPlanStages]
	END
go
CREATE VIEW [dbo].[AbPlanStages]
AS 
SELECT  pzr.*  FROM [PlanZR] pzr inner join PlanSpalte ps on pzr.SpalteID=ps.SpalteID inner join [Plan]  AS p on ps.PlanID=p.PlanID WHERE p.OwnerId IN
	   (SELECT UserGruppe.GruppeID 
		FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 11
			)
WITH CHECK OPTION
go
grant select on [dbo].[AbPlanStages] to [public]
go

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPlanStages_update]'))
BEGIN
drop VIEW [dbo].[AbPlanStages_update]
END
go
CREATE VIEW [dbo].[AbPlanStages_update]
AS 
SELECT  pzr.*  FROM [PlanZR] pzr inner join PlanSpalte ps on pzr.SpalteID=ps.SpalteID inner join [Plan]  AS p on ps.PlanID=p.PlanID WHERE p.OwnerId IN
	   (SELECT UserGruppe.GruppeID 
		FROM UserGruppe INNER JOIN UserPW ON UserGruppe.Userid = UserPW.Userid 
		WHERE UserPW.Username = CURRENT_USER AND BerechtigungsbereichID = 11
		and UserGruppe.Schreiben=1	)
WITH CHECK OPTION
go
GRANT SELECT ON [dbo].[AbPlanStages_update] TO Public
GRANT DELETE ON [dbo].[AbPlanStages_update] TO Public
GRANT INSERT ON [dbo].[AbPlanStages_update] TO Public
GRANT UPDATE ON [dbo].[AbPlanStages_update] TO Public
GO

 /**2014-12-11,DH
  Neue Spalte für Gruppierung nach frei einstellbaren Werten, vorbelegt mit lokalisierten Namen für Spielplan, Person und Kalender  **/
 IF NOT  EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Groupby' and o.id = OBJECT_ID(N'[dbo].[Plan]'))
 ALTER TABLE [Plan] ADD Groupby VARCHAR(30) NULL;
 PRINT 'Groupby angelegt';
GO
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'Groupby' and o.id = OBJECT_ID(N'[dbo].[Plan]'))
	BEGIN
		DECLARE @country VARCHAR(20)
		SELECT @country = WertText FROM Settings WHERE Form = 'Adresse' AND Control = 'Country'
		IF @country = 'FI'
		BEGIN--Finnisch
			UPDATE  [Plan] SET Groupby='Ohjelma' WHERE PlanArt in (30,99,120) AND Groupby is null;
			UPDATE  [Plan] SET Groupby='Henkilö' WHERE PlanArt in (170) AND Groupby IS NULL;
			UPDATE  [Plan] SET Groupby='Kalenteri' WHERE PlanArt in (160) AND Groupby IS NULL;
			PRINT 'FI eingetragen Groupby';
		END
		IF @country = 'EN'
		BEGIN--Englisch
			UPDATE  [Plan] SET Groupby='Program' WHERE PlanArt in (30,99,120) AND Groupby is null;
			UPDATE  [Plan] SET Groupby='Person' WHERE PlanArt in (170) AND Groupby IS NULL;
			UPDATE  [Plan] SET Groupby='Calendar' WHERE PlanArt in (160) AND Groupby IS NULL;
			PRINT 'EN eingetragen Groupby';
		END
		IF @country = 'F' OR @country = 'BE'
		BEGIN--Französisch
			UPDATE  [Plan] SET Groupby='Programme' WHERE PlanArt in (30,99,120) AND Groupby is null;
			UPDATE  [Plan] SET Groupby='Personne' WHERE PlanArt in (170) AND Groupby IS NULL;
			UPDATE  [Plan] SET Groupby='Calendrier' WHERE PlanArt in (160) AND Groupby IS NULL;
			PRINT 'BE eingetragen Groupby';
		END
		IF @country = 'NL'
		BEGIN--Niederländisch
			UPDATE  [Plan] SET Groupby='Repertoire' WHERE PlanArt in (30,99,120)
			UPDATE  [Plan] SET Groupby='Persoon' WHERE PlanArt in (170) AND Groupby IS NULL;
			UPDATE  [Plan] SET Groupby='Kalender' WHERE PlanArt in (160) AND Groupby IS NULL;
			PRINT 'NL eingetragen Groupby';
		END
		IF @country = 'CZ'
		BEGIN--Tschechisch
			UPDATE  [Plan] SET Groupby='Hrací plán' WHERE PlanArt in (30,99,120);
			UPDATE  [Plan] SET Groupby='Osoba' WHERE PlanArt in (170) AND Groupby IS NULL;
			UPDATE  [Plan] SET Groupby='Kalendář' WHERE PlanArt in (160) AND Groupby IS NULL;
			PRINT 'CZ eingetragen Groupby';
		END
		ELSE
		BEGIN
			UPDATE  [Plan] SET Groupby='Spielplan' WHERE PlanArt in (30,99,120) AND Groupby IS NULL;
			UPDATE  [Plan] SET Groupby='Person' WHERE PlanArt in (170) AND Groupby IS NULL;
			UPDATE  [Plan] SET Groupby='Kalender' WHERE PlanArt in (160) AND Groupby IS NULL;
			PRINT 'DE eingetragen Groupby';
		END
	END

GO

--BorisMünch 2014-012-19 
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o ON c.id = o.id
	WHERE c.name = 'ForeColor' AND o.id = OBJECT_ID('dbo.AuffTypen'))
BEGIN
	ALTER TABLE AuffTypen ADD ForeColor INT NULL
END
--DH20150105 Kommentarfelder für Honorare
GO
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
       WHERE c.name = 'FeeComment' and o.id = OBJECT_ID(N'dbo.vertragRolle'))
BEGIN
ALTER TABLE dbo.vertragRolle ADD FeeComment TEXT NULL;
END
go
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
WHERE c.name = 'RehearsalFeeComment' and o.id = OBJECT_ID(N'dbo.vertragRolle'))
BEGIN
ALTER TABLE dbo.vertragRolle ADD RehearsalFeeComment TEXT NULL;
END
go
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbVertragRolle'))
BEGIN
DROP VIEW [dbo].[AbVertragRolle]
END
GO
CREATE VIEW [dbo].[AbVertragRolle]
AS 
SELECT
	vr.VertragsNr,
	vr.RolleId,
	vr.VRID,
	vr.ProbUnbez,
	vr.AbrechnungProben,
	vr.ProbBezahltAnz,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.ProbBezahltWert ELSE -1 END AS ProbBezahltWert,
	vr.ProbVorstAnteilAnz,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.Honorar ELSE -1 END AS Honorar,
	vr.VorstAnz,
	vr.AbrechnungVs,
	vr.VorstAnzMin,
	--CASE WHEN UG.HasFeesPermission = 1 THEN vr.Ausstattungskosten ELSE -1 END AS Ausstattungskosten,
	vr.VertragRolleTS,
	vr.VorstAnzVortrag,
	--CASE WHEN UG.HasFeesPermission = 1 THEN vr.HonorarIst ELSE -1 END AS HonorarIst,
	vr.LM,
	vr.UM,
	vr.LC,
	vr.UC,
	vr.vrVon,
	vr.vrBis,
	--CASE WHEN UG.HasFeesPermission = 1 THEN vr.BonusFee ELSE -1 END AS BonusFee,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.ExtraFee ELSE -1 END AS ExtraFee,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.SalaryLevelId ELSE -1 END AS SalaryLevelId,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.CoverFee ELSE -1 END AS CoverFee,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.FeeComment ELSE NULL END AS FeeComment,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.RehearsalFeeComment ELSE NULL END AS RehearsalFeeComment,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.DayFee ELSE -1 END AS DayFee,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.TravelExpensesFlat ELSE -1 END AS TravelExpensesFlat,
	vr.ProductionId,
	CASE WHEN UG.HasFeesPermission = 1 THEN vr.OvernightExpensesFlat ELSE -1 END AS OvernightExpensesFlat,
	vr.RehearsalsCompensatedByPerformance
FROM  
	VertragRolle AS vr 
	INNER JOIN Vertrag AS v ON VR.VertragsNr = v.VertragsNr  
	INNER JOIN	(SELECT GruppeID, Schreiben, (CASE WHEN OptionsFlag & 1 <> 1 THEN 0 ELSE 1 END) AS HasFeesPermission
						FROM			UserGruppe 
						INNER JOIN		UserPW		ON UserGruppe.Userid = UserPW.Userid 
						WHERE Username = CURRENT_USER AND BerechtigungsbereichID = 1) AS UG
				ON v.ModulGruppeID = UG.GruppeID
GO

-- berechtigungen alle auf public
GRANT SELECT ON AbVertragRolle TO public
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbVertragRolle_Update'))
BEGIN
DROP VIEW [dbo].[AbVertragRolle_Update]
END
go
CREATE VIEW [dbo].[AbVertragRolle_Update]
AS 
SELECT  vr.*  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

GRANT SELECT ON AbVertragRolle_Update TO public
GRANT DELETE ON AbVertragRolle_Update TO public
GRANT INSERT ON AbVertragRolle_Update TO public
GRANT UPDATE ON AbVertragRolle_Update TO public

GO

--BM20150106 Formelzuweisungen müssen eindeutig sein
DELETE FROM [dbo].[FormulaConfigurations_Departments]
  WHERE EXISTS (
	SELECT FormulaConfiguration_DepartmentId FROM [dbo].[FormulaConfigurations_Departments] secondTbl
	WHERE [dbo].[FormulaConfigurations_Departments].[FormulaConfigurationId] = secondTbl.[FormulaConfigurationId]
	AND [dbo].[FormulaConfigurations_Departments].[DepartmentId] = secondTbl.[DepartmentId]
	AND [dbo].[FormulaConfigurations_Departments].[FormulaConfiguration_DepartmentId] > secondTbl.[FormulaConfiguration_DepartmentId]
	)
		
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UQ_ID_FormulaConfigurationId_DepartmentId]') )
BEGIN
  ALTER TABLE [dbo].[FormulaConfigurations_Departments]
  ADD CONSTRAINT [UQ_ID_FormulaConfigurationId_DepartmentId] UNIQUE NONCLUSTERED
(
    [FormulaConfigurationId], [DepartmentId]
)

END
GO
--DH20150112 Zuordnen von Leseberechtigungen für jeden existierenden User
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 146 OR (Minor = 146 AND Build < 7)))))
BEGIN
INSERT INTO dbo.UserGruppe (Userid,GruppeID,BerechtigungsbereichID,schreiben)
	SELECT p.Userid,1,11,0 FROM [dbo].[UserPW] AS p 
	WHERE p.userid NOT IN(SELECT userid FROM Usergruppe WHERE BerechtigungsbereichID=11)
END
GO

--BM20150112 Farbe schwarz einmalig null setzen. WI#5791
IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 146 OR (Minor = 146 AND Build < 7)))))
	UPDATE [dbo].[AuffTypen] SET BackColor = null WHERE BackColor = 0
GO
--TK2015-01-16
-- Nicht mehr benötigte Felder löschen
DropColumn 'PersonalDetails','Str'
GO
DropColumn 'PersonalDetails','PLZ'
GO
DropColumn 'PersonalDetails','Ort'
GO
DropColumn 'PersonalDetails','Tel'
GO
DropColumn 'PersonalDetails','Fax'
GO
DropColumn 'PersonalDetails','Land'
GO
DropColumn 'PersonalDetails','KuenstlerVN'
GO
DropColumn 'PersonalDetails','KuenstlerNN'
GO
DropColumn 'PersonalDetails','Titel'
GO
DropColumn 'PersonalDetails','Co'
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_PersonalDetails_Agentur3]') AND type = 'F')
	ALTER TABLE [dbo].[PersonalDetails] DROP CONSTRAINT [FK_PersonalDetails_Agentur3]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_PersonalDetails_Agentur1]') AND type = 'F')
	ALTER TABLE [dbo].[PersonalDetails] DROP CONSTRAINT [FK_PersonalDetails_Agentur1]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_PersonalDetails_Agentur]') AND type = 'F')
	ALTER TABLE [dbo].[PersonalDetails] DROP CONSTRAINT [FK_PersonalDetails_Agentur]
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK_PersonalDetails_Agentur2]') AND type = 'F')
	ALTER TABLE [dbo].[PersonalDetails] DROP CONSTRAINT [FK_PersonalDetails_Agentur2]
GO
DropColumn 'PersonalDetails','Theater'
GO
DropColumn 'PersonalDetails','Hotel'
GO
DropColumn 'PersonalDetails','EMail'
GO
DropColumn 'PersonalDetails','Handy'
GO
DropColumn 'PersonalDetails','HausRuf'
GO
DropColumn 'PersonalDetails','NVDat'
GO
DropColumn 'PersonalDetails','AgenturNr2'
GO
DropColumn 'PersonalDetails','Bild'
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[BallettDienste]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE BallettDienste
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[BallettDispo]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE BallettDispo
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ChorDienste]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE ChorDienste
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[ChorDispo]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE ChorDispo
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KollBallett]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE KollBallett
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KollChor]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE KollChor
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KollOrchester]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE KollOrchester
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Agentur]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE Agentur
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[AgFilter]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE AgFilter
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[AusrüstungsArten]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE AusrüstungsArten
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Ausrüstung]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE Ausrüstung
Go

--2015-01-16 sh
--im view CastActiveties prüfung auf berechtigungen hinzugefügt
ALTER VIEW [dbo].[CastActiveties]
AS
SELECT      ac.AuffNr, ac.Datum, ac.UhrBeg, ac.UhrEnde, ac.SNr, ac.ZRNr, ac.Art, ac.Bem,
			ca.PersNr, ca.DiffVon, ca.DiffBis, ca.CastStatusID, ca.Gesperrt, ca.ID, ca.IsCanceled, ca.RolleID,
			at.KatNr, ca.IsCover, ac.status, ca.Creditable
FROM		   AufführgTabelle 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 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.BerechtigungsbereichID = 4 AND ugc.UserID = ua.UserID
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)) OR ca.RolleId IS NULL)
GO
GRANT SELECT ON  dbo.CastActiveties TO public;
GO
--2015-02-10 dh
--Benutzergruppen auf aktiv setzen, da Inaktiv keine Auswirkung hat.
update dbo.userpw set isinactive=0 where isgroup=1 and isinactive=1;
GO

--BM20150219
IF EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].Settings'))
BEGIN
	IF EXISTS (SELECT * FROM NvData WHERE ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 146 OR (Minor = 146 AND Build < 103)))))
	BEGIN
		DELETE FROM Settings  WHERE Form = N'Benutzereinstellungen' AND Control = N'ActivityContextMenuUserSettings' AND Pref IS NULL
		DELETE FROM Settings  WHERE Form = N'System' AND Control = N'ActivityContextMenuGlobalSettings' AND Pref IS NULL
		DELETE FROM Settings  WHERE Form = N'SettingsView' AND Control = N'ActivityContextMenuSettingsControl' AND Pref IS NULL
		IF EXISTS (SELECT * FROM Fahrplan)
		BEGIN
			INSERT INTO [Settings] (
				Form,
				[control],
				WertText,
				IsGlobalSetting
			) VALUES (
				'SettingsView',
				'ActivityContextMenuSettingsControl',
				'<ActivityContextMenuSettings><SelectedMenuItems><string>TimetableActivityControl</string><string>ActivityCast</string><string>ActivityHistory</string></SelectedMenuItems></ActivityContextMenuSettings>',
				1
			)
		END
		ELSE
			INSERT INTO [Settings] (
				Form,
				[control],
				WertText,
				IsGlobalSetting
			) VALUES (
				'SettingsView',
				'ActivityContextMenuSettingsControl',
				'<ActivityContextMenuSettings><SelectedMenuItems><string>ActivityCast</string><string>ActivityHistory</string></SelectedMenuItems></ActivityContextMenuSettings>',
				1
			)
	END
END
GO

--BM 20150224
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_SubscriptionActivityCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].sp_SubscriptionActivityCount
GO
CREATE 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 [Status] BETWEEN 0 AND 99
GO

GRANT EXECUTE ON sp_SubscriptionActivityCount TO Public
GO

--2015-02-24 sh
--bugfix im View ActivitiesUpdate, der letzte JOIN auf UserPW mit einem LEFT JOIN statt INNER JOIN, da der Benutzer vlt. schon nicht mehr existiert
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'dbo.[ActivitiesUpdate]'))
BEGIN
	DROP VIEW dbo.[ActivitiesUpdate]
END
GO
CREATE VIEW [dbo].[ActivitiesUpdate]
AS
SELECT * 
FROM AufführgTabelle AS Auff 
WHERE Auff.Datum <= dbo.AccessDatum() 
AND AuffNr IN(
			SELECT DISTINCT A.AuffNr FROM AufführgTabelle AS A
			INNER JOIN AuffTypen AS AT ON AT.AuffTNr = A.Art
			LEFT JOIN ActivityTypeGroups AS ATG ON AT.AuffTNr = ATG.ActivityTypeId
			LEFT JOIN Stücke AS S ON S.Snr = A.SNr
			LEFT JOIN UserGruppe AS UGBB2 ON UGBB2.BerechtigungsbereichID = 2 AND UGBB2.schreiben <> 0 AND UGBB2.GruppeID = S.ModuleGroupId
			LEFT JOIN UserPW AS UPBB2 ON UGBB2.Userid  = UPBB2.Userid AND UPBB2.Username = CURRENT_USER
			LEFT JOIN UserGruppe AS UGBB9 ON UGBB9.BerechtigungsbereichID = 9 AND UGBB9.schreiben <> 0 AND UGBB9.GruppeID = ATG.GroupId
			LEFT JOIN UserPW AS UPBB9 ON UGBB9.Userid  = UPBB9.Userid AND UPBB9.Username = CURRENT_USER
			LEFT JOIN UserPW AS UPC ON UPC.UserId = A.UC
			WHERE (ATG.ActivityTypeId IS NULL OR UPBB9.UserID IS NOT NULL) AND UPBB2.UserID IS NOT NULL OR 
			(1 = IS_MEMBER('db_owner') OR (UPC.UserName = CURRENT_USER))
		)
WITH CHECK OPTION
GO

GRANT SELECT ON [ActivitiesUpdate] TO Public
GRANT INSERT ON [ActivitiesUpdate] TO Public
GRANT DELETE ON [ActivitiesUpdate] TO Public
GRANT UPDATE ON [ActivitiesUpdate] TO Public
GO

--2015-03-06 sh
-- converterfeld umbenannt, da name irreführend und nicht passend zum rest
UPDATE PlanSort SET ContentPath = 'workingTimeHoursSum' WHERE ContentPath = 'setupTimeHoursSum'
GO

--Jemand
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
WHERE c.name = 'AttachmentDocumentType' and o.id = OBJECT_ID(N'dbo.PersContractValidationStatus'))
BEGIN
ALTER TABLE dbo.PersContractValidationStatus ADD AttachmentDocumentType INT NULL;
END


--BM 2015-01-20 Berechtigung, um besondere Pressetexte zu lesen und zu bearbeiten
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbPressetext'))
	BEGIN
DROP VIEW [dbo].[AbPressetext]
END
GO
CREATE VIEW [dbo].[AbPressetext]
AS
	SELECT p.* FROM PresseText AS p
		INNER JOIN AufführgTabelle AS act ON p.AuffNr = act.AuffNr
		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 UserPW.Username = CURRENT_USER

GO

-- berechtigungen alle auf public
GRANT SELECT ON AbPressetext TO public
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].AbPressetext_Update'))
		BEGIN
DROP VIEW [dbo].[AbPressetext_Update]
END
GO
CREATE VIEW [dbo].[AbPressetext_Update]
AS
	SELECT p.* FROM PresseText AS p
	WHERE p.AuffNr IS NULL OR p.AuffNr 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

-- berechtigungen alle auf public
GRANT SELECT ON AbPressetext_Update TO public
GRANT DELETE ON AbPressetext_Update TO public
GRANT INSERT ON AbPressetext_Update TO public
GRANT UPDATE ON AbPressetext_Update TO public
GO

--DH20150122 Neue Spalte Buchhaltungsdruckdatum für Bestellungen
IF NOT EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'AccountancyPrintDate' and o.id = OBJECT_ID(N'[dbo].[Orders]'))
BEGIN
	ALTER TABLE dbo.Orders ADD AccountancyPrintDate datetime NULL
END
go
IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = 'CallOfTender' AND o.id = OBJECT_ID(N'[dbo].Orders') AND c.prec < 50)
BEGIN
		ALTER TABLE Orders ALTER COLUMN CallOfTender VARCHAR(50)
	--Rolle 0 bereinigen
	UPDATE BesetzungStd SET Anzahl = 1 , Pos = 100000 WHERE ID = 0
	DELETE FROM BesetzungStdSoliTabelle WHERE RolleID = 0
		END

--BM 2015-01-26 Bankdaten und Personendetails als getrennte Berechtigungen
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPersonalDetails]'))
	BEGIN
	DROP VIEW [dbo].[AbPersonalDetails]
	END
GO
CREATE VIEW [dbo].[AbPersonalDetails]
AS
	SELECT  PersonalDetails.*  FROM  PersonalDetails WHERE Pnr 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.BerechtigungsbereichID = 0 AND (ug.OptionsFlag & 4 = 4 OR ug.OptionsFlag & 8 = 8) AND Username = CURRENT_USER GROUP BY pp.PersonId)
GO

GRANT SELECT ON AbPersonalDetails TO public
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbPersonalDetails_Update]'))
	BEGIN
	DROP VIEW [dbo].[AbPersonalDetails_Update]
END
GO
CREATE VIEW [dbo].[AbPersonalDetails_Update]
AS
	SELECT  PersonalDetails.*  FROM  PersonalDetails WHERE Pnr 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 pp.HasWritePermission=1 AND UG.Schreiben=1 AND  ug.BerechtigungsbereichID = 0 AND ug.OptionsFlag & 8 = 8 AND Username = CURRENT_USER GROUP BY pp.PersonId)

	WITH CHECK OPTION
GO

GRANT SELECT ON AbPersonalDetails_Update TO public
GRANT DELETE ON AbPersonalDetails_Update TO public
GRANT INSERT ON AbPersonalDetails_Update TO public
GRANT UPDATE ON AbPersonalDetails_Update TO public
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbBankAccount]'))
	BEGIN
	DROP VIEW [dbo].[AbBankAccount]
	END
GO
CREATE VIEW [dbo].[AbBankAccount]
AS
	SELECT  BankAccount.*  FROM  BankAccount WHERE PersID 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.BerechtigungsbereichID = 0 AND (ug.OptionsFlag & 16 = 16 OR ug.OptionsFlag & 32 = 32) AND Username = CURRENT_USER GROUP BY pp.PersonId)
GO

GRANT SELECT ON AbBankAccount TO public
GO

IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].[AbBankAccount_Update]'))
BEGIN
	DROP VIEW [dbo].[AbBankAccount_Update]
END
GO
CREATE VIEW [dbo].[AbBankAccount_Update]
AS
	SELECT  BankAccount.*  FROM  BankAccount WHERE PersID 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.BerechtigungsbereichID = 0 AND ug.Schreiben = 1 AND pp.HasWritePermission = 1 AND ug.OptionsFlag & 32 = 32 AND Username = CURRENT_USER GROUP BY pp.PersonId)

WITH CHECK OPTION
GO

GRANT SELECT ON AbBankAccount_Update TO public
GRANT DELETE ON AbBankAccount_Update TO public
GRANT INSERT ON AbBankAccount_Update TO public
GRANT UPDATE ON AbBankAccount_Update TO public
GO

UPDATE UserGruppe SET OptionsFlag = OptionsFlag | 40 WHERE IsInherited = 0 AND BerechtigungsbereichID = 0 AND Schreiben = 1 AND UserID IN (
		(SELECT p.UserID FROM [dbo].[sysusers] AS u
			INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
			INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
			INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
		WHERE (g.name = 'Soli-Daten ändern' OR g.name = 'db_owner') AND g.issqlrole = 1))

exec InheritPermissions

UPDATE UserGruppe SET OptionsFlag = OptionsFlag | 40, IsInherited = 0 WHERE IsInherited = 1 AND OptionsFlag & 40 <> 40 AND BerechtigungsbereichID = 0 AND Schreiben = 1 AND UserID IN (
		(SELECT p.UserID FROM [dbo].[sysusers] AS u
			INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
			INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
			INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
		WHERE (g.name = 'Soli-Daten ändern' OR g.name = 'db_owner') AND g.issqlrole = 1))
GO

UPDATE UserGruppe SET OptionsFlag = OptionsFlag | 20 WHERE IsInherited = 0 AND BerechtigungsbereichID = 0 AND UserID IN (
		(SELECT p.UserID FROM [dbo].[sysusers] AS u
			INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
			INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
			INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
		WHERE (g.name = 'Soli-Daten lesen' OR g.name = 'Soli-Daten ändern' OR g.name = 'db_owner') AND g.issqlrole = 1))

exec InheritPermissions

UPDATE UserGruppe SET OptionsFlag = OptionsFlag | 20, IsInherited = 0 WHERE IsInherited = 1 AND OptionsFlag & 20 <> 20 AND BerechtigungsbereichID = 0 AND UserID IN (
		(SELECT p.UserID FROM [dbo].[sysusers] AS u
			INNER JOIN [dbo].[sysmembers]   AS m ON  u.uid=m.memberuid
			INNER JOIN [dbo].[sysusers]     AS g ON  m.groupuid=g.uid
			INNER JOIN [dbo].[UserPW]		AS p ON  u.name=p.Username
		WHERE (g.name = 'Soli-Daten lesen' OR g.name = 'Soli-Daten ändern' OR g.name = 'db_owner') AND g.issqlrole = 1))
GO

GRANT DELETE, INSERT, UPDATE ON WageType TO PersoAdmin

GO
-------------------------------------------------------------------------------------------------------------------
--
------------------------SCRIPT GESCHLOSSEN! Keine Änderungen mehr vornehmen! Änderungen jetzt in CreateDB_2015.sql!
go
--2015-02-10 dh
--Benutzergruppen auf aktiv setzen, da Inaktiv keine Auswirkung hat.
update dbo.userpw set isinactive=0 where isgroup=1 and isinactive=1;
GO

--2015-03-26 sh
--alte sichten entfernen (aus 2015 übernommen da der fehler auch im 2014er script auftritt)
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].Sicht1'))
BEGIN
	DROP VIEW [dbo].Sicht1
END
GO
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].Sicht2'))
BEGIN
	DROP VIEW [dbo].Sicht2
END
GO
--ENDE
-------------------------------------------------------------------------------------------------------------------
--Aufräumen...
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DropIndexByTable'))				DROP PROCEDURE dbo.DropIndexByTable
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DropColumn'))					DROP PROCEDURE dbo.DropColumn 
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DeleteConstraint'))				DROP PROCEDURE dbo.DeleteConstraint 
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DropDefault'))					DROP PROCEDURE dbo.DropDefault 
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].DropRoleWithDropRoleMember'))	DROP PROCEDURE dbo.DropRoleWithDropRoleMember 
IF  EXISTS (SELECT * FROM  sysobjects o WHERE  o.id = OBJECT_ID(N'[dbo].SumToFormula'))					DROP PROCEDURE dbo.SumToFormula 
GO

------------------- Views aktuallisiern -----------------
DECLARE @SchemaView VARCHAR(100)
DECLARE view_cursor CURSOR FOR
SELECT Name
	FROM 	sysobjects
	WHERE	xtype = 'V'

OPEN view_cursor
FETCH NEXT FROM view_cursor INTO @SchemaView
WHILE @@FETCH_STATUS = 0
	BEGIN
		PRINT @SchemaView
		EXEC sp_refreshview @SchemaView;
		FETCH NEXT FROM view_cursor INTO @SchemaView
	END
CLOSE view_cursor
DEALLOCATE view_cursor
--------------------------------------------------------
GO

DECLARE @major INT
DECLARE @minor INT
DECLARE @build INT
DECLARE @Datum INT
/*----------------VERSION-ts_DataClass---*/
SET @major = 4
SET @minor = 146
SET @build = 105
SET @Datum = 20150306
/*----------------VERSION-----------------*/

IF NOT EXISTS (SELECT *
				FROM  NvData
				WHERE ByModulScript = 1)
BEGIN
	INSERT INTO NvData (lfdVerNr, ByModulScript)
	VALUES				(1, 1)
END
UPDATE NvData
SET
	Major = @major, Minor = @minor, Build = @build, lfdVerNr = @Datum, LastDatabaseUpdateDate = GetDate()
WHERE
	ByModulScript = 1
GO
--#region ----------- NOEXEC OFF ------------------------------
SET NOEXEC OFF
--#endregion