In a SQL script which is due to end up feeding a SSRS RDL document, I’m trying to leverage CTEs to recursively fetch my data.
The actual SQL code is way too big to copypaste here but I made up this short repro:
declare @temp table
(
id uniqueidentifier not null default(newid()),
name varchar(100) not null default('new'),
value varchar(100) not null default('newValue'),
parentid uniqueidentifier null
)
insert into @temp (id, name, value, parentid) values ('12312312-1234-1234-1234-123412341234', 'o1', 'val1', null)
insert into @temp (id, name, value, parentid) values ('12312312-1234-1234-1234-123412341235', 'o2', 'val2', '12312312-1234-1234-1234-123412341234')
insert into @temp (id, name, value, parentid) values ('12312312-1234-1234-1234-123412341236', 'o3', 'val3', '12312312-1234-1234-1234-123412341234')
;with
cte(id,name, value, pid, pname, pvalue) as (
select id, name, value, null, null, null from @temp where parentid is null
union all
select r.id, r.name, r.value, a.id, a.name, a.value
from @temp r inner join cte a
on a.id = r.parentid
)
select * from cte
The CTE errors out like this (tested in SSMS 2012):
Msg 240, Level 16, State 1, Line 13
Types don't match between the anchor and the recursive part in column "pid" of recursive query "cte".
Msg 240, Level 16, State 1, Line 13
Types don't match between the anchor and the recursive part in column "pname" of recursive query "cte".
Msg 240, Level 16, State 1, Line 13
Types don't match between the anchor and the recursive part in column "pvalue" of recursive query "cte".
I’m pretty sure this is due to the NULL values being selected in the anchor part as opposed to the NOT NULL fields fetched in the recursive part… Can this issue be worked around ?
(I’m open to alternative ways of accomplishing this task.)
Cast the literal
nullvalues to match.Otherwise SQL will assume the default type
intfor eachnullwhich won’t match the second part of the union.