IF EXISTS (SELECT 1 FROM SYS.TABLES WHERE NAME='LD0P0U301')
BEGIN
	DROP TABLE LD0P0U301
END
;

IF EXISTS (SELECT 1 FROM SYS.VIEWS WHERE NAME='LD0V0U301')
BEGIN
	DROP VIEW LD0V0U301
END
;

IF EXISTS (SELECT 1 FROM SYS.VIEWS WHERE NAME='LD0VAA0LMRESPONSIBLEHISTORY')
BEGIN
	DROP VIEW LD0VAA0LMRESPONSIBLEHISTORY
END
;

CREATE TABLE LD0P0U301
(
       PLANNR               DECIMAL(9) NOT NULL,
       ANSVARIGNR           DECIMAL(9) DEFAULT 0 NOT NULL,
       ANSVARIGFROM         VARCHAR(8) NOT NULL,
       ANSVARIGTOM          VARCHAR(8) NOT NULL,
       ANSVARIGFOR          DECIMAL(9) DEFAULT 0 NOT NULL,
       ORGID                DECIMAL(9) NOT NULL,
       ANSVARIGORG          VARCHAR(10) DEFAULT ' ' NOT NULL,
       ANSVARIGHANDL        VARCHAR(10) DEFAULT ' ' NOT NULL
PRIMARY KEY CLUSTERED 
(
	PLANNR, ANSVARIGNR, ANSVARIGFROM, ANSVARIGTOM
)
)
;

CREATE VIEW LD0V0U301 AS SELECT * FROM LD0P0U301
;

CREATE VIEW LD0VAA0LMRESPONSIBLEHISTORY
AS SELECT U301.*
,Q1.KLARTEXT AS ANSVARIGFOR_T
,I.NAMN  AS ANSVARIGHANDL_T
,J01.NAMN  AS  ORGENH_T

FROM LD0P0U301 AS U301

LEFT OUTER JOIN LD0V0Q01 AS Q1 ON Q1.KODTYP = 'LNANSVFOR' AND U301.ANSVARIGFOR = Q1.KOD
LEFT OUTER JOIN LD0V0I AS I ON I.HAND = U301.ANSVARIGHANDL
LEFT OUTER JOIN LD0V0J01 AS J01 ON J01.ORGID = U301.ORGID AND J01.ORGENHNR = U301.ANSVARIGORG
;

