CTE查询有2个条件不起作用?

发布于 2024-12-11 22:05:28 字数 1029 浏览 0 评论 0原文

我出生于 1978 年 12 月 22 日,

我想要一个查询(在 CTE 中!)来显示我所有的生日(datepart day = 22)

declare @t0 datetime  = '1978/12/22';
declare @t1 datetime  = getdate();


 with CTEE (val,day1)
AS
(
    SELECT @t0,DATEPART(day,@t0)
    UNION   all
    SELECT DATEADD(day,1,val) , DATEPART(day,day1) from  ctee where( DATEADD(day,1,val) <=@t1)   and DATEPART(day,day1)=22
)
select val,day1 from CTEE OPTION (MAXRECURSION 20000) 

这似乎返回了我 1 行(为什么?? ?)

如果我删除 和 DATEPART(day,day1)=22 这样它就会给我我活着的所有日子。

我找到的解决方案是这样的:

  declare @t0 datetime  = '1978/12/22';
    declare @t1 datetime  = getdate();


     with CTEE (val,day1)
    AS
    (
        SELECT @t0,DATEPART(day,@t0)
        UNION   all
        SELECT DATEADD(day,1,val) , DATEPART(day,day1) from  ctee where( DATEADD(day,1,val) <=@t1)  

    )
    select val,day1 from CTEE where day1=22  OPTION (MAXRECURSION 20000) 

但我的问题是为什么在第一个查询中它不起作用?

I was born in 1978/12/22

I wanted a query (in CTE!) to display me all my birthdays (datepart day = 22)

declare @t0 datetime  = '1978/12/22';
declare @t1 datetime  = getdate();


 with CTEE (val,day1)
AS
(
    SELECT @t0,DATEPART(day,@t0)
    UNION   all
    SELECT DATEADD(day,1,val) , DATEPART(day,day1) from  ctee where( DATEADD(day,1,val) <=@t1)   and DATEPART(day,day1)=22
)
select val,day1 from CTEE OPTION (MAXRECURSION 20000) 

How ever this seems to return me 1 row ( why???)

If I remove and DATEPART(day,day1)=22 so it gives me all the days im alive.

The solution I found is this:

  declare @t0 datetime  = '1978/12/22';
    declare @t1 datetime  = getdate();


     with CTEE (val,day1)
    AS
    (
        SELECT @t0,DATEPART(day,@t0)
        UNION   all
        SELECT DATEADD(day,1,val) , DATEPART(day,day1) from  ctee where( DATEADD(day,1,val) <=@t1)  

    )
    select val,day1 from CTEE where day1=22  OPTION (MAXRECURSION 20000) 

But my question is why in the first query it didn't work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゃ人海孤独症 2024-12-18 22:05:28

因为第二条记录是1978-12-23

这不满足 DATEPART(day,day1)=22 条件,因此递归步骤不会返回结果,这会终止递归,如 SQL Server 联机丛书

终止检查是隐式的;当没有行时递归停止
从上次调用返回。

Because the second record is 1978-12-23.

That doesn't meet the DATEPART(day,day1)=22 condition, so that recursive step returns no results, this terminates the recursion as documented in SQL Server Books Online

The termination check is implicit; recursion stops when no rows are
returned from the previous invocation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文