![](/img/trans.png)
[英]Iterate through derived value from temp table so it value can be used it a where condition using for loop
[英]Loop through sql server table using values derived from temp table
我需要使用從臨時表派生的值並將其用作 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
我得到這個結果:
但是,如果我將此值用作 where 語句的標准,則在 begin 語句中,我不會得到預期的結果。
您需要更改您的查詢,如下所示。
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.