当前位置: 代码迷 >> Sql Server >> 如何插入两个日期之间的所有日期
  详细解决方案

如何插入两个日期之间的所有日期

热度:6   发布时间:2016-04-27 14:57:06.0
怎么插入两个日期之间的所有日期?
Table1
Store StartDate EndDate 
A店 20111230 20120101

Table2
Store Date
A店 20111230
A店 20111231
A店 20120101
由Table1 生成Table2 怎么写

------解决方案--------------------
SQL code
if not object_id('ta') is null    drop table taGoCreate table ta([Store] nvarchar(2),[StartDate] Datetime,[EndDate] Datetime)Insert taselect N'A店','20111230','20120101'UNION ALLselect N'B店','20111130','20111205'GoSELECT a.[Store],       DATEADD(DAY,b.number,a.[StartDate])[Date]FROM master..spt_values b,ta aWHERE b.type='P'AND   b.number BETWEEN 0 AND DATEDIFF(day,a.[StartDate],a.[EndDate]) /*Store Date----- -----------------------A店    2011-12-30 00:00:00.000A店    2011-12-31 00:00:00.000A店    2012-01-01 00:00:00.000B店    2011-11-30 00:00:00.000B店    2011-12-01 00:00:00.000B店    2011-12-02 00:00:00.000B店    2011-12-03 00:00:00.000B店    2011-12-04 00:00:00.000B店    2011-12-05 00:00:00.000*/
------解决方案--------------------
SQL code
create table t1(    store varchar(10),    startdate datetime,    enddate datetime)insert into t1 select 'A店', '20111230', '20120101'select * from t1select store,DATEADD(DAY,number,a.startdate) as riqifrom t1 as a with(nolock) cross join master..spt_values as b with(nolock)where b.type='P' and DATEADD(DAY,number,a.startdate)<=a.enddate-------------------------------store    riqiA店    2011-12-30 00:00:00.000A店    2011-12-31 00:00:00.000A店    2012-01-01 00:00:00.000
  相关解决方案