Reputation: 5058
I need to use values derived from a temporary table and use it as where criteria. Please see my code:
declare @laneNum int
declare @startDate date = '2019-02-07'
declare @class int = 1
declare @id int
if OBJECT_ID('tempdb..#tempLaneNumber') IS NOT NULL
drop table [#tempLaneNumber]
create table #tempLaneNumber
(
LANE_NUMBER INT NULL
)
INSERT INTO #tempLaneNumber (LANE_NUMBER)
SELECT DISTINCT EXIT_LANE
FROM [dbo].[TOLL]
ORDER BY EXIT_LANE ASC
select * from #tempLaneNumber
set @laneNum = (select * from #tempLaneNumber)
begin
select COUNT(*)
from [dbo].[TOLL]
where convert(date, TRXN_DTIME) = @startDate and EXIT_LANE = @laneNum
end
If I run up to select * from #tempLaneNumber
I get this result:
But if I use this values as a criteria on a where statement, on the begin statement, I don't get my expected result.
Upvotes: 1
Views: 43
Reputation: 17943
You need to change your query like following.
select l.LANE_NUMBER, COUNT(*)
from [dbo].[TOLL] t
inner join #tempLaneNumber l on t.EXIT_LANE = l.LANE_NUMBER
where convert(date, TRXN_DTIME) = @startDate
GROUP BY l.LANE_NUMBER
There are multiple issues in your query, i have commented those and modified where ever required.
--declare @laneNum int [NOT REQUIRED]
declare @startDate date = '2019-02-07'
declare @class int = 1
declare @id int
if OBJECT_ID('tempdb..#tempLaneNumber') IS NOT NULL
drop table [#tempLaneNumber]
create table #tempLaneNumber
(
LANE_NUMBER INT NULL
)
INSERT INTO #tempLaneNumber (LANE_NUMBER)
SELECT DISTINCT EXIT_LANE
FROM [dbo].[TOLL]
--ORDER BY EXIT_LANE ASC [NOT REQUIRED FOR INSERT]
select * from #tempLaneNumber
--set @laneNum = (select * from #tempLaneNumber) [YOU CAN'T ASSING A TABLE OUTPUT TO A INT VARIABLE]
--begin [NOT REQUIRED]
/*
select COUNT(*)
from [dbo].[TOLL]
where convert(date, TRXN_DTIME) = @startDate and EXIT_LANE = @laneNum
*/
--CHANGED
select l.LANE_NUMBER, COUNT(*)
from [dbo].[TOLL] t
inner join #tempLaneNumber l on t.EXIT_LANE = l.LANE_NUMBER
where convert(date, TRXN_DTIME) = @startDate
GROUP BY l.LANE_NUMBER
--end [NOT REQUIRED]
Upvotes: 1