LoginSignup
27
17

More than 5 years have passed since last update.

SQLでWith句を2つ以上書くには?

Posted at

メモ書き
SQLでWith句を2つ以上書く場合は下記のように書く
ポイントは、2つ目以降のWith句は,でつなぎ、先頭にWithをつけないこと

with句を2つ以上書くサンプル

declare @FromDate varchar(7) = '2017/03';
declare @ToDate varchar(7) = '2017/04';
declare @FromDate2 varchar(7) = '2017/03';
declare @ToDate2 varchar(7) = '2017/04';

with NendoMonth as

(

select cast( @FromDate + '/01' as datetime ) as monthDate
union all
select dateadd( MONTH, 1, monthDate )
from NendoMonth
where NendoMonth.monthDate < @ToDate + '/01'
)

, NendoMonth2 as --,でつなぎ先頭にはwithをつけない
(

select cast( @FromDate2 + '/01' as datetime ) as monthDate
union all
select dateadd( MONTH, 1, monthDate )
from NendoMonth2
where NendoMonth2.monthDate < @ToDate2 + '/01'
)

27
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
17