在最终将提供 SSRS RDL 文档的 SQL 脚本中,我试图利用 CTE 递归地获取我的数据。
实际的 SQL 代码太大,无法在此处复制粘贴,但我做了这个简短的复制:
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
像这样的 CTE 错误(在 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".
我很确定这是由于在锚部分中选择了 NULL 值,而不是在递归部分中获取的 NOT NULL 字段......这个问题可以解决吗?
(我对完成这项任务的替代方法持开放态度。)