This query returns all days between date range defined with variables and result set is 31 distinct values. But, recursive CTE works in such a way that first query executed only once, and second query works on result set created before. So, it seems that there will be duplicates, but it returned distinct result set. Whether CTE apply DISTINCT clause internally or is it something else? How I get DISTINCT values?
DECLARE
@DateFrom DATE = '20130101' ,
@DateTo DATE = '20130131'
WITH Days
AS ( SELECT CAST(@DateFrom AS DATETIME) AS dt
UNION ALL
SELECT DATEADD(dd, 1, dt)
FROM Days s
WHERE DATEADD(dd, 1, dt) <= CAST(@DateTo AS DATETIME)
)
SELECT dt
FROM Days
Each time a CTE recurses, it uses the rows produced by the previous recursion (or the initial set of rows if this is the first time it recurses).
So, for your query, the first run produces a single row –
'20130101'converted to a datetime.For the first recursive step, we take all the rows produced by the last recursion or initial set (
'20130101') and use it to produce one new row, which contains'20130102'.For the next recursive step, we take all rows produced by the last recursion (
'20130102') and use it to produce one new row ('20130103')For the next recursive step, we take all rows produced by the last recursion (
'20130103') and use it to produce one new row ('20130104')I don’t see anywhere where duplicates are going to arise.
Read more here: