CREATE OR ALTER VIEW LD0VAAYScannedDocuments AS 
select T60.*,
CASE WHEN Q01I.KLARTEXT IS NOT NULL THEN Q01I.KLARTEXT
WHEN Q01A.KLARTEXT IS NOT NULL THEN Q01A.KLARTEXT 
WHEN Q01E.KLARTEXT IS NOT NULL THEN Q01E.KLARTEXT
WHEN Q01S.KLARTEXT IS NOT NULL THEN Q01S.KLARTEXT
END AS AGARTYP_T,
CASE WHEN Q01A.XNUM40 IS NOT NULL THEN Q01A.XNUM40 
WHEN Q01I.XNUM40 IS NOT NULL THEN Q01I.XNUM40
WHEN Q01S.XNUM40 IS NOT NULL THEN Q01S.XNUM40
ELSE 0 END AS WORKFLOW_T
from LD0VYT60 T60
LEFT JOIN LD0P0H A   
ON T60.AGARNR = A.AKTUALNR  AND A.AKTUALNR > 0
LEFT JOIN LD0P0Q01 Q01A     
ON Q01A.KODTYP ='AKTUAL' AND Q01A.KOD = A.AKTUAL 
LEFT JOIN LD0P0C I
ON T60.AGARNR = I.AEVERKNR  AND I.AEVERKNR > 0 AND I.TMARK = 0  
LEFT JOIN LD0P0Q01 AS Q01I 
ON Q01I.KODTYP = 'UTREDTYP' AND Q01I.KOD = I.AEVERKTYP  
LEFT JOIN LD0P0C E   
ON T60.AGARNR = E.AEVERKNR  AND E.AEVERKNR > 0
LEFT JOIN LD0P0Q01 AS Q01E 
ON Q01E.KODTYP = 'JOURNALTYP' AND Q01E.KOD = E.AEVERKTYP  
LEFT JOIN LD0P0C20 S   
ON T60.AGARNR = S.INSNR  AND S.INSNR > 0
LEFT JOIN LD0P0Q01 AS Q01S 
ON Q01S.KODTYP = 'INSATS' AND Q01S.KOD = S.INSTYP 
GO
GRANT ALL ON LD0VAAYScannedDocuments TO LD0ROANV
GO