I Strongly Feel that by using the relations between the tables,
with out using any loops u can write that query by using case
Conditions and joins
... as i don't know the relations so am using cursor and loop...
Any way u can use this Proc...
USE[Test2OMS]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE sp_TruckAlert
AS
BEGIN
Declare @Rpath varchar(80),@Ipath varchar(80),@Path Varchar(80),@TruckId int
Declare @status int,@Flag int
Declare @TruckId_Cursor Cursor
Create Table #Output
(
TruckNo Int,
RoadTaxExpiryDate varchar(40),
RoadPath Varchar(80),
InsuranceExpiryDate Varchar(40),
InsuPath Varchar(80)
)
Set @TruckId_Cursor = CURSOR FAST_FORWARD
For
Select Distinct TruckID From tbl_TruckDetails
Open @TruckId_Cursor
Fetch Next From @TruckId_Cursor into @TruckId
While @@FETCH_STATUS=0
Begin
select @status= DATEDIFF(day, RoadTaxExpiryDate, GETDATE()) from tbl_TruckDetails
where TruckID = @TruckId
Set @Flag=0
While @Flag<2
Begin
if(@status < -5)
Select @Path=ImagePath from tbl_AlertImages where ID =4
else if(@status > -3 and @status < -5)
Select @Path=ImagePath from tbl_AlertImages where ID =2
else if(@status > -1 and @status < -3)
Select @Path=ImagePath from tbl_AlertImages where ID =3
else if(@status = 1 or @status > 1)
Select @Path=ImagePath from tbl_AlertImages where ID =1
If @Flag=1
Set @Rpath=@Path
Else
Set @Ipath=@Path
select @status= DATEDIFF(day, InsuranceExpiryDate, GETDATE()) from tbl_TruckDetails
where TruckID = @TruckId
set @Flag=@Flag+1
End
Insert into #Output
Select t.TruckNo,
CAST(t.RoadTaxExpiryDate as varchar) as RoadTaxExpiryDate,
a.ImagePath as RoadPath,
CAST(t.InsuranceExpiryDate as varchar) as InsuranceExpiryDate,
b.ImagePath as InsuPath
--CAST(t.InspectionDate as varchar) as InspectionDate,
--CAST(t.NextServiceDate as varchar) as NextServiceDate,
--(t.NextServiceKM - f.OdometerEnd) as NextserviceKM,
--CAST(NextServiceKM as varchar) as NextServiceKM
from tbl_TruckDetails t
Inner Join tbl_FleetFuelMaintenance f on f.TruckID = t.TruckID
Cross Join tbl_AlertImages a
Cross Join tbl_AlertImages b
where t.IsDeleted !=1 and a.ImagePath = @Rpath and t.TruckID = @TruckId
and b.ImagePath = @Ipath and t.TruckID = @TruckId
Fetch Next From @TruckId_Cursor into @TruckId
End
Close @TruckId_Cursor
Deallocate @TruckId_Cursor
Select * From #Output
END