
CREATE VIEW [dbo].[ApiDevicesView] as
select d.*, 
ISNULL(Inspections.ReservationTo, DATEADD(month, d.InspectionFrequency, d.InspectionDate)) NextInspectionDate,
 ISNULL(Inspections.Id,0) NextInspectionTaskId
from dbo.ApiDevices  d LEFT OUTER JOIN 
(select l.DeviceId, t.Id, l.ReservationTo, d.Active from dbo.ApiDeviceLines  l JOIN dbo.ApiCrmTasks t ON t.Id = l.TaskId 
JOIN dbo.ApiDictionaries d on l.StateId = d.Id and d.Active<>0
where t.DefId = 1 and t.CategoryId = 16)  Inspections ON Inspections.DeviceId = d.Id