I am trying to adapt a stored procedure into a view and I’ve run into what appears to be a table scoping issue in SQL Server 2008 R2.
In the sproc, there was a parameter that specified the companyId. Now we want to retrieve the same data but not limit it to a specific companyId but rather to group by that companyId.
However, my attempt broadening it has failed.
Select Distinct [T].[TruckID], [T].[VIN], [T].[Make], [T].[Model],
[T].[ModelYear], [T].[RFIDNo], [SQCT].[VendorCode], [SQCT].[UserLabel],
[T].[IsActive], [T].[IsFleetTruck], [SQDA].[DriverAssociations],
dbo.GetCurrentPlate([T].[TruckID]) [Plate],
[TCT].[CompanyId] -- // <- Now we're including it
From [dbo].[Truck] as [T]
Inner Join [dbo].[TruckerCompanyTruck] as [TCT]
On [T].[TruckID] = [TCT].[TruckId]
Left Outer Join (
Select [CT].[CompanyTruckId], [CT].[CompanyId],
[CT].[TruckId], [CT].[VendorCode], [CT].[UserLabel],
[CT].[CreateDate], [CT].[CreateBy], [CT].[UpdateDate],
[CT].[UpdateBy], [CT].[Version]
From [dbo].[CompanyTruck] as [CT]
) as [SQCT]
On [TCT].[CompanyId] = [SQCT].[CompanyId]
and [TCT].[TruckId] = [SQCT].[TruckId]
Left Join (
Select Distinct [TCTC].[TruckId], Count(*) [DriverAssociations]
From [TruckerCompanyTruck] [TCTC]
Inner Join [Trucker] [D]
On [TCTC].[TruckerId] = [D].[TruckerId]
Inner Join [TruckerContract] [TC]
On [TCTC].[TruckerId] = [TC].[TruckerId]
Where [TCTC].[CompanyId] = [TCT].[CompanyId] -- // Error!
and [TC].[CompanyId] = [TCT].[CompanyId] -- // Error!
Group By [TCTC].[TruckId]
) as [SQDA]
On [SQDA].[TruckId] = [T].[TruckId]
The “Error!” lines throw “The multi-part identifier “TCT.CompanyId” could not be bound.”
The ultimate goal is that running this query will produce multiple rows for a truck that has multiple company associations and return the correct driver count.
In the end, this query of the view…
Select *
From [FlattenedTruck]
Where [CompanyId] = 28
Order By [VIN]
…should produce the same output as this.
Exec [GetTrucksForGridWithAssociationCounts] @companyId = 28
But the differ. The sproc returns 1 driver association for companyId 28 and the view returns 1246 driver associations which is all of the associations for that truck regardless of the company. (It’s also different because the sproc does not return the companyId because it’s passed in as a parameter.)
TruckID -> VIN -> Make -> Model -> ModelYear -> RFIDNo -> VendorCode -> UserLabel -> IsActive -> IsFleetTruck -> DriverAssociations -> Plate -> CompanyId
26 -> NULL -> NULL -> NULL -> NULL -> NULL -> NULL -> NULL -> 1 -> 0 -> 1246 -> US-WA-9D68812 28
26 -> NULL -> NULL -> NULL -> NULL -> NULL -> NULL -> NULL -> 1 -> 0 -> 1 -> US-WA-9D68812
Can you try OUTER APPLY instead of the LEFT JOIN to the SQDA subquery? You’ll want to add the condition of [TCTC].[TruckId] = [T].[TruckId] to the WHERE clause within the subquery, as the APPLY doesn’t take an ON condition.