我在SQL Server 2012中有这个查询,但是我已经将顺序(Id,Slug,CategoryName)更改为(Id,CategoryName,Slug)以匹配返回的数据和列名称,现在我得到了这个错误:
Msg 240,Level 16,State 1,Line 1
锚和递归查询“categoryPath”列“CategoryName”中的递归部分之间的类型不匹配
这是查询:
WITH categoryPath(Id, CategoryName, Slug)
AS
(
SELECT
Id, CategoryName, Slug
FROM Categories
WHERE ParentCategoryId IS NULL
UNION ALL
SELECT
Categories.Id,
CAST(categoryPath.CategoryName + ' / ' + categories.CategoryName AS NVARCHAR(150)),
categories.Slug
FROM Categories
JOIN categoryPath ON Categories.ParentCategoryId = categoryPath.Id
)
SELECT *
FROM [ItemCategories]
JOIN categoryPath ON [ItemCategories].CategoryId = categoryPath.Id
WHERE [ItemCategories].StockId = '5'
答案 0 :(得分:2)
当我收到这个错误时,我只是施展得很好而且很快就会有效:
WITH categoryPath(Id, CategoryName, Slug) AS (
SELECT Id, cast(CategoryName as nvarchar(150)), cast(Slug as nvarchar(150))
FROM Categories
WHERE ParentCategoryId IS NULL
UNION ALL
SELECT Categories.Id,
CAST(categoryPath.CategoryName + ' / ' + categories.CategoryName AS NVARCHAR(150)),
CAST(categories.Slug as nvarchar(150))
FROM Categories JOIN
categoryPath
ON Categories.ParentCategoryId=categoryPath.Id
)
. . .