3

在最终将提供 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 字段......这个问题可以解决吗?

(我对完成这项任务的替代方法持开放态度。)

4

1 回答 1

3

转换文字null值以匹配。

;with
cte(id,name, value, pid, pname, pvalue) as (
    select id, name, value, cast(null as uniqueidentifier),
        cast(null as varchar(100)), cast(null as varchar(100))
    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
)

否则 SQL 将假定int每个null与联合的第二部分不匹配的默认类型。

于 2013-01-17T11:02:44.263 回答