使用从临时表派生的值循环遍历sql server表

时间:2019-02-18 10:07:34

标签: sql sql-server

我需要使用派生自临时表的值并将其用作where条件。请查看我的代码:

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

如果我运行到select * from #tempLaneNumber,我将得到以下结果:

enter image description here

但是,如果我将此值用作where语句的条件,则在begin语句中,不会得到预期的结果。

1 个答案:

答案 0 :(得分:1)

您需要像下面那样更改查询。

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

您的查询中有多个问题,我已对它们进行了注释,并在需要时进行了修改。

--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]