同时使用cte和变量来更新SQL中的日期

时间:2018-06-26 11:12:39

标签: tsql variables common-table-expression row-number

我目前正在尝试实现一些代码,这些代码将获取给定的160ish行列表的日期,并将它们更新为同一表中另一个日期之后的一分钟。

因此,例如,这些将来自:

> 1058841   2018-06-20 14:15:04.000 Copy of NtO produced
> 1058841   2018-06-14 19:58:03.000 NTO service date set to 24/05/2018

> 969565    2018-06-20 14:15:01.000 17530   Copy of NtO produced
> 969565    2018-06-14 19:58:03.000 148 NTO service date set to 24/05/2018

对此:

> 1058841   2018-06-14 19:59:03.000 Copy of NtO produced
> 1058841   2018-06-14 19:58:03.000 NTO service date set to 24/05/2018

> 969565    2018-06-14 19:59:03.000 17530   Copy of NtO produced
> 969565    2018-06-14 19:58:03.000 148 NTO service date set to 24/05/2018

我到目前为止的代码:

declare @thisdate datetime

set @thisdate = (
select * from (
select row_number() over (partition by te_system_ref order by (select 0)) as rownumber, te_date, te_system_ref, te_event from ticket_events where te_system_ref in 
(select sl_system_ref from statutory_letter where sl_letter_batch = 9429)and te_event = 'Copy of NtO produced'
) t
where rownumber = 1
);

with rn as 
( select * from (
select row_number() over (partition by te_system_ref order by (select 0)) as rownumber1, te_date, te_system_ref, te_event from ticket_events where te_system_ref in 
(
select sl_system_ref from statutory_letter where sl_letter_batch = 9429 
)
and te_event = 'Copy of NtO produced'
) t where rownumber1 = 1)

select * from rn where te_date between dateadd(hour,1,@thisdate) and dateadd(hour,-1,@thisdate)

这当前给我错误:

  

消息116,级别16,状态1,行9   未在子查询中引入子查询时在选择列表中指定   存在。

如果有人可以解释我哪里出了问题,或者指出正确的方向,将不胜感激

1 个答案:

答案 0 :(得分:0)

ke_search

这里您尝试为标量变量分配多个值。

我想您实际上是想要set @thisdate = ( select * from ( select row_number() over (partition by te_system_ref order by (select 0)) as rownumber, te_date, te_system_ref, te_event from ticket_events where te_system_ref in (select sl_system_ref from statutory_letter where sl_letter_batch = 9429)and te_event = 'Copy of NtO produced' ) t where rownumber = 1 );

te_date