CTE错误:“锚点和recursion部分之间的types不匹配”

我正在执行以下声明:

;WITH cte AS ( SELECT 1 as rn, 'name1' as nm UNION ALL SELECT rn + 1, nm = 'name' + CAST((rn + 1) as varchar(255)) FROM cte a WHERE rn < 10) SELECT * FROM cte 

…完成错误…

 Msg 240, Level 16, State 1, Line 2 Types don't match between the anchor and the recursive part in column "nm" of recursive query "cte". 

我在哪里犯错误?

究竟是什么说:

'name1'具有与'name' + CAST((rn+1) as varchar(255))不同的数据types

试试这个(未经testing)

 ;with cte as ( select 1 as rn, CAST('name1' as varchar(259)) as nm union all select rn+1,nm = 'name' + CAST((rn+1) as varchar(255)) from cte a where rn<10) select * from cte 

基本上,你必须确保长度匹配。 对于recursion位,如果再次失败,则可能必须使用CAST('name' AS varchar(4))

你需要投射两个纳米的领域

 ;with cte as ( select 1 as rn, CAST('name1' AS VARCHAR(255)) as nm union all select rn+1, nm = CAST('name' + CAST((rn+1) as varchar(255)) AS VARCHAR(255)) from cte a where rn<10) select * from cte 
 ;with cte as ( select 1 as rn, 'name' + CAST(1 as varchar(255)) as nm union all select rn+1,nm = 'name' + CAST((rn+1) as varchar(255)) from cte a where rn<10) select * from cte 
 ;with tmp1(NewsId,DataItem ,HeaderText) as ( select NewsId, LEFT(HeaderText, CHARINDEX(',',HeaderText+',')-1), STUFF(HeaderText, 1, CHARINDEX(',',HeaderText+','), '') from Currentnews union all select NewsId, LEFT(HeaderText, CHARINDEX(',',HeaderText+',')-1), STUFF(HeaderText, 1, CHARINDEX(',',HeaderText+','), '') from tmp1 where HeaderText > '' ) select NewsId, DataItem from tmp1 order by NewsId