Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

CTE non stop recursiveness

Status
Not open for further replies.

SQLScholar

Programmer
Aug 21, 2002
2,127
0
0
GB
Hey all,

I am still dont 100% understand CTEs. We have a little issue with a CTE that doesnt stop running. Basically i need to create a list of every date, cross joined to a table with about 10 rows.

Without the cross join element it works perfectly. With it - it starts off working ok. Then it gets todays date - and then repeats it for infinity.

heres my code:

Code:
with ReportDates as
  (
  select cast('2011-01-07' as date) calendar_date, ORGANISATION_CODE
  from
  dbo.ORGANISATION_UNITS
  where LEN(ORGANISATION_UNITS.ORGANISATION_CODE) = 1
  union all
  select DATEADD(DAY,1,calendar_date), ORGANISATION_UNITS.ORGANISATION_CODE
  from ReportDates
  cross join 
  dbo.ORGANISATION_UNITS
  where DATEADD(DAY,1,calendar_date) < GETDATE()
  and LEN(ORGANISATION_UNITS.ORGANISATION_CODE) = 1
  )

select * from reportdates

OPTION (MAXRECURSION 0)

Any help gratefully recieved.

Dan

----------------------------------------

Be who you are and say what you feel, because those who mind don't matter and those who matter don't mind - Dr. Seuss

Computer Science is no more about computers than astronomy is about telescopes - EW Dijkstra
----------------------------------------
 
DOH. I should do it in two - not one

Code:
with ReportDates as
  (
  select cast('2011-01-07' as date) calendar_date
  union all
  select DATEADD(DAY,1,calendar_date)
  from ReportDates
  where DATEADD(DAY,1,calendar_date) < GETDATE()
  ),
ReportDatesWithOrg as 
	( select calendar_date, ORGANISATION_CODE from ReportDates
	cross join
	ORGANISATION_UNITS
	where len(ORGANISATION_CODE) = 1 )


select * from ReportDatesWithOrg


OPTION (MAXRECURSION 0)

Sorry for troubling you..... :)

----------------------------------------

Be who you are and say what you feel, because those who mind don't matter and those who matter don't mind - Dr. Seuss

Computer Science is no more about computers than astronomy is about telescopes - EW Dijkstra
----------------------------------------
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top