I need to convert an existing MsSql stored procedure into mysql. Below mentioned query is a example stored procedure which I'm going to convert.
CREATE PROCEDURE [mydb].[mysp]
@input_userId nvarchar(255)
AS
BEGIN
WITH tree(userId, managerUserId, name, Level) AS
(
SELECT t1.userId, t1.managerUserId, t1.name, 0
FROM UserData t1
WHERE managerUserId = @input_userId OR userId=@input_userId
UNION ALL
SELECT t2.userId, t2.managerUserId, t2.name, t3.Level+1
FROM UserData t2
INNER JOIN tree t3 ON t2.managerUserId=t3.userId
)
SELECT DISTINCT(res.name), res.userId, res.Level, t1.empNo
FROM tree AS res
INNER JOIN
UserData AS t1 ON res.userId = t1.userId
ORDER BY res.name asc
END
I'm confuse how to convert WITH tree part in to MySql. I tried to replace that with another select, but since that tree is using in other 2 select queries it didn't success. I'd be SO THANKFUL if you could support me to resolve this.
EDITED:
I tried below query in mysql 5.6.
CREATE PROCEDURE mydb.mysp(
IN input_userId VARCHAR(255))
BEGIN
SELECT res.name, res.userId, res.Level, t1.empNo
FROM
(
SELECT userId, managerUserId, name, Level
FROM
(
SELECT t1.userId, t1.managerUserId, t1.name, 0
FROM UserData t1
WHERE managerUserId = @input_userId OR userId=@input_userId
UNION ALL
SELECT t2.userId, t2.managerUserId, t2.name, t3.Level+1
FROM UserData t2
INNER JOIN tree t3 ON t2.managerUserId=t3.userId
) AS tree
)
FROM tree AS res
INNER JOIN
UserData AS t1 ON res.userId = t1.userId
ORDER BY res.name ASC
END
This is giving an error like,
SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tree AS res INNER JOIN UserData AS t1 ON res.userId = t1.userId ORDER BY' at line 20