IF EXISTS (
SELECT 1 
FROM sys.indexes 
WHERE name='LD0C0I01' AND object_id = OBJECT_ID('LD0P0I01'))
BEGIN
	DROP INDEX LD0C0I01 ON LD0P0I01
END
GO
IF NOT EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_NAME(parent_object_id)='LD0P0I01' AND TYPE='PK')
BEGIN
ALTER TABLE LD0P0I01
ADD CONSTRAINT PK_LD0P0I01 PRIMARY KEY CLUSTERED (HAND, ORGID, ORGENHNR)
END
GO
IF NOT EXISTS(SELECT * FROM sys.columns WHERE  object_id = OBJECT_ID(N'LD0P0I01') AND name = 'StartTime')
BEGIN
ALTER TABLE LD0P0I01
ADD STARTTIME DATETIME2 GENERATED ALWAYS AS ROW START HIDDEN
   NOT NULL CONSTRAINT LD0P0I01_StartTime DEFAULT SYSUTCDATETIME()
   ,ENDTIME   DATETIME2 GENERATED ALWAYS AS ROW END HIDDEN
   NOT NULL CONSTRAINT LD0P0I01_EndTime DEFAULT CONVERT(DATETIME2, '9999-12-31 23:59:59.9999999'),
PERIOD FOR SYSTEM_TIME (STARTTIME, ENDTIME)
END
GO
BEGIN
DECLARE @SQL VARCHAR(2000)
DECLARE @SCHEMA VARCHAR(100)=(SELECT SCH.NAME
									FROM SYS.TABLES TAB
									JOIN SYS.SCHEMAS SCH
									ON SCH.schema_id=TAB.schema_id
									WHERE TAB.NAME='LD0P0I01')
SET @SQL='ALTER TABLE LD0P0I01
SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE='+@SCHEMA+'.LD0L0I01))'
EXEC (@SQL)
END
GO
IF EXISTS (SELECT 1 FROM SYS.VIEWS WHERE NAME='LD0V0LogOrganization')
BEGIN
DROP VIEW LD0V0LogOrganization 
END
GO
CREATE VIEW LD0V0LogOrganization AS
SELECT DISTINCT
LOGG.*,
CASE WHEN CAST(DATUM+' '+KLOCKSLAG AS DATETIME) BETWEEN StartTime AND ENDTIME THEN I01.ORGID ELSE 0 END I01_ORGID,
CASE WHEN CAST(DATUM+' '+KLOCKSLAG AS DATETIME) BETWEEN StartTime AND ENDTIME THEN I01.ORGENHNR ELSE ' ' END I01_ORGENHNR, 
I01.STARTTIME, 
I01.ENDTIME 
FROM LD0P0LOG LOGG
JOIN LD0P0I01 I01
ON LOGG.ANVHAND=I01.HAND
GO
GRANT ALL ON LD0V0LogOrganization TO LD0ROANV
GO