我试图在子查询中使用行号来从我的存储过程的另一个表部分带来值如下所示。子查询出错:
;with cte as
(
select
@sDate StartDate,
DATEADD(wk,DATEDIFF(wk, 0, @sDate),7) EndDate
union all
select
dateadd(d, 1, EndDate),
dateadd(ww, 1, dateadd(ww, 1, StartDate))
from
cte
where
dateadd(wk, 1, StartDate) <= @eDate
), cte2 as
(
select
*,
(ROW_NUMBER() OVER(ORDER by iD)) as rn
from
[KFC].[dbo].[tblCOMPANYTAXPERIOD]
where
[COMPANYTAXYEARID] = 4
)
select
REPLICATE('0', 3 - LEN(RTRIM(ROW_NUMBER() OVER(ORDER by EndDate)))) + RTRIM(ROW_NUMBER() OVER(ORDER by EndDate)) AS [PAYROLLRUNNUMBER],
(CONVERT(VARCHAR(11), StartDate, 106)) as PERIODSTARTDATE,
(CONVERT(VARCHAR(11), EndDate, 106)) as PERIODENDDATE,
(select iD
from cte2
where [COMPANYTAXYEARID] = 4
and [TAXPERIODNO] = rn) AS [COMPANYTAXPERIODID]
from
cte c
错误:
子查询返回的值超过1。当子查询遵循=,!=,&lt;,&lt; =,&gt;,&gt; =或子查询用作表达式时,不允许这样做。
答案 0 :(得分:0)
你可以使用cte,尝试这样的事情:where子句
中不允许使用窗口函数;with cte as
(
select @sDate StartDate, DATEADD(wk,DATEDIFF(wk, 0, @sDate),7) EndDate --, ROW_NUMBER() OVER(ORDER by @sDate) as number
union all
select dateadd(d, 1, EndDate),
dateadd(ww, 1, dateadd(ww, 1, StartDate))--,ROW_NUMBER() OVER(ORDER by EndDate) as number
from cte
where dateadd(wk, 1, StartDate)<= @eDate
), cte2 as
( select iD, [TAXPERIODNO], (ROW_NUMBER() OVER(ORDER by EndDate)) as rn from [KFC].[dbo].[tblCOMPANYTAXPERIOD] where [COMPANYTAXYEARID] = 4 )
--Insert Into #Temp select * from cte
select REPLICATE('0',3-LEN(RTRIM( ROW_NUMBER() OVER(ORDER by EndDate)))) + RTRIM(ROW_NUMBER() OVER(ORDER by EndDate)) as [PAYROLLRUNNUMBER]
, (CONVERT(VARCHAR(11),StartDate,106)) as PERIODSTARTDATE, (CONVERT(VARCHAR(11),EndDate,106)) as PERIODENDDATE
, (select iD from cte2 where [TAXPERIODNO] =rn )as [COMPANYTAXPERIODID] from cte c