将CTE存储过程转换为Mysql兼容的数据库查询

时间:2019-05-18 11:06:14

标签: mysql sql sql-server tsql sql-server-2008

我的类别表是

  TABLE [Category](
        [Id] [int] IDENTITY(1,1) NOT NULL,
        [Title] [nvarchar](512) NULL,
        [Slug] [nvarchar](512) NULL,
        [Details] [text] NULL,
        [CategoryType] [int] NOT NULL,
        [ParentId] [int] NULL,
        [SortOrder] [int] NOT NULL
   )

我的CTE存储过程为

CREATE PROCEDURE [dbo].[sp_AllCategoryPath]
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET NOCOUNT ON;

 ;WITH CTE AS
 (
     SELECT Id, Title, Title as Path, ParentId, cast(Id as nvarchar(125)) as LinkPath,Slug
     FROM Category 
     WHERE ParentId IS NULL
     UNION ALL
     SELECT t.[Id], t.[Title], 
     cast(cte.[Path] +'/'+ t.Title as nvarchar(512)), 
     t.ParentId,
     cast(cte.[LinkPath]  +'/'+  CONVERT(varchar(512), t.Id) as nvarchar(125)),
     t.Slug
     FROM Category t
     INNER JOIN CTE ON t.ParentId = CTE.Id
 )

 SELECT cte.Id, cte.Title, cte.Path, cte.ParentId , c.Title as ParentName, LinkPath,cte.Slug
 FROM CTE cte LEFT JOIN Category c ON cte.ParentId = c.Id
 ORDER BY cte.Path

END

如何将cte sp查询转换为mysql sp兼容版本? 我想将sp更改为查询,因为我将asp.net核心应用程序数据库提供程序MSSQL更改为MySql服务器。 但是我无法将cte sp更改为普通的sp查询。 MyMySQL服务器版本5.1.73 This is query output

1 个答案:

答案 0 :(得分:0)

您可以使用WHILELOOPREPEAT..UNTIL之类的MySQL流控制语句来模拟RCTE行为,但所有这些语句仅在存储的例程,函数,触发器和事件中允许。您不能在SELECT之类的普通查询中使用它们。

如果您可以在MySQL中使用CALL AllCatPath(...)之类的存储例程,则可以自己实现递归。如果不允许使用存储的例程,则必须迁移到MySQL中树的另一种实现,例如“嵌套集”。