简体   繁体   中英

SQL Server date range generate to multiple rows

TableName

Sample data

Number Date_From   Date_To   
1      2020-09-29  2020-09-30

I need to return something like this:

Number Date_generated
1      2020-09-29
1      2020-09-30

You can unpivot with a lateral join:

select t.number, x.date_generated
from mytable t
cross apply (values (t.date_from), (t.date_to)) as x(date_generated)

On the other hand, if you want to generate one row per day within the range, one option uses a recursive query:

with cte as (
    select number, date_from date_generated, date_to from mytable
    union all
    select number, dateadd(day, 1, date_generated), date_to from cte where date_generated < date_to
)
select * from cte

If you have ranges that span over more than 100 days, then you need to add option (maxrecursion 0) at the very end of the query.

Based on question already asked here :
You can use this function to split your string with the desired delimiter. in your case it's '|'

CREATE FUNCTION dbo.SplitStrings
(
    @List       NVARCHAR(MAX),
    @Delimiter  NVARCHAR(255)
)
RETURNS TABLE
AS
    RETURN (SELECT Number = ROW_NUMBER() OVER (ORDER BY Number),
        Item FROM (SELECT Number, Item = LTRIM(RTRIM(SUBSTRING(@List, Number, 
        CHARINDEX(@Delimiter, @List + @Delimiter, Number) - Number)))
    FROM (SELECT ROW_NUMBER() OVER (ORDER BY s1.[object_id])
        FROM sys.all_objects AS s1 CROSS APPLY sys.all_objects) AS n(Number)
    WHERE Number <= CONVERT(INT, LEN(@List))
        AND SUBSTRING(@Delimiter + @List, Number, 1) = @Delimiter
    ) AS y);

Use it like it :

SELECT s.[message-id], f.Item
  FROM dbo.SourceData AS s
  CROSS APPLY dbo.SplitStrings(s.[recipient-address], '|') as f;

you can use

select number,date_from Date_generated from tbl
union all
select number,date_to Date_generated from tbl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM