SQL Server 查询 CTE 父子,在 2012 本地工作,但在 2012 现场不工作,类型不匹配
Posted
技术标签:
【中文标题】SQL Server 查询 CTE 父子,在 2012 本地工作,但在 2012 现场不工作,类型不匹配【英文标题】:SQL Server query CTE parent child, works in 2012 local but not in 2012 live, types don't match 【发布时间】:2017-10-27 15:57:53 【问题描述】:此查询在一个服务器版本中有效,但在另一个版本中无效。
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[EventDetails]
@EventID AS VARCHAR(20)
AS
BEGIN
WITH CTE(CategoryID, FullCategName, OrderString) AS
(
SELECT
CategoryID,
CAST(CategoryName AS VARCHAR(MAX)),
CAST(CAST(CategoryID AS CHAR(5)) AS VARCHAR(MAX)) OrderString
FROM
CategoryTbl
WHERE
ParentCategoryIDf is NULL
UNION ALL
SELECT
p.CategoryID,
CAST(c.FullCategName + ' >> ' + p.CategoryName AS VARCHAR(MAX)),
CAST(c.OrderString + CAST(p.CategoryID AS CHAR(5)) AS VARCHAR(MAX)) OrderString
FROM
CategoryTbl p
JOIN
CTE c ON c.CategoryID = p.ParentCategoryIDf
)
SELECT
(SELECT TOP 1 i.ImageUrl
FROM ImageTbl i
WHERE i.ProductIDf = p.EventID) AS ImageURL, *
FROM
EventTbl p
LEFT JOIN
CTE c on c.CategoryID = p.CategoryIDf
WHERE
p.EventID = @EventID
END
【问题讨论】:
所以...我不得不问...monsters_db
中有什么内容? ......这是怪物,不是吗?
请注意,根据那里的版本号,您的本地 express 实例是 SQL Server 2014。
【参考方案1】:
这可能是排序规则问题,试试这个:
WITH CTE(CategoryID, FullCategName, OrderString) AS (
SELECT
CategoryID
, cast(CategoryName as varchar(max)) Collate SQL_Latin1_General_CP1_CI_AS as FullCategName
, cast(cast(CategoryID as char(5)) as varchar(max)) Collate SQL_Latin1_General_CP1_CI_AS as OrderString
FROM CategoryTbl
WHERE ParentCategoryIDf is NULL
UNION ALL
SELECT
p.CategoryID
, cast(c.FullCategName + ' >> ' + p.CategoryName as varchar(max)) Collate SQL_Latin1_General_CP1_CI_AS
, cast(c.OrderString + cast(p.CategoryID as char(5)) as varchar(max)) Collate SQL_Latin1_General_CP1_CI_AS --OrderString
FROM CategoryTbl p
JOIN CTE c
ON c.CategoryID = p.ParentCategoryIDf
)
select
(select top 1 i.ImageUrl
from ImageTbl i
where i.ProductIDf=p.EventID) as ImageURL
, *
from EventTbl p
left join CTE c on c.CategoryID=p.CategoryIDf
where p.EventID=@EventID
end
参考:
T-SQL CTE Error: Types don't match between the anchor and the recursive part【讨论】:
感谢支持以上是关于SQL Server 查询 CTE 父子,在 2012 本地工作,但在 2012 现场不工作,类型不匹配的主要内容,如果未能解决你的问题,请参考以下文章
sql server使用cte递归查询获取树形的父节点/子节点