遍历临时表的派生值,以便可以在其中使用for循环的where条件中使用它的值

时间:2019-02-18 10:26:04

标签: sql sql-server tsql

我可以从派生表中获得每个项目的总计,如下所示:

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 DESC

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

但是,我现在需要遍历每个派生值,以便在可以将每个结果放在变量中的语句中使用它。这就是我在当前代码中得到的...

enter image description here

我需要将LANE_NUMBER 4放入x4变量,将LANE_NUMBER 6放入x6变量,依此类推。我怎么去呢?

编辑

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 DESC


;WITH CTE AS
(
    select l.LANE_NUMBER, COUNT(*) CT
    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
)
SELECT * FROM CTE where LANE_NUMBER = 4

这是正确的,但是问题是我需要对值“ 4”或“ 6”或“ 7”进行硬编码。该示例有4个结果,所以还可以。但是如果我有10个或更多,该怎么办?

1 个答案:

答案 0 :(得分:1)

如果以后要使用结果,可以使用如下的临时表。

create table #Results
(
    LANE_NUMBER INT NULL,
    [Count_LN] INT
)    

INSERT INTO #Results
select l.LANE_NUMBER, COUNT(*) CT
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

如果您想在下一条语句中立即使用输出,则可以像下面这样去寻求CTE。

;WITH CTE AS
(

select l.LANE_NUMBER, COUNT(*) CT
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
)
SELECT * FROM CTE --USER YOUR CTE HERE

编辑:

我无法完全理解您的要求,无论出于何种原因,如果您要迭代表并将每行的列值存储到变量中,都可以尝试执行以下操作。

create table #Results
(
    LANE_NUMBER INT NULL,
    [Count_LN] INT
)    

INSERT INTO #Results
select l.LANE_NUMBER, COUNT(*) CT
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 @ln int
declare @ct int
While (Select Count(*) From #Results) > 0
Begin
    select top 1 @ln = LANE_NUMBER, @ct = [Count_LN] from #Results
    -- Use the variable @ln and @ct. For example, if you want to call a sp
    -- exec call_someothersp @ln,@ct
    Delete From #Results Where LANE_NUMBER = @ln and [Count_LN]=@ct
End