Mysql 8如何在存储过程中使用if并使用cte

时间:2019-11-10 23:10:29

标签: mysql

我在存储过程中使用CTE,它可以正常工作,但是问题是当我尝试添加条件时,出现以下消息:

  

您的SQL错误。.
  在'IF附近使用的语法。

CREATE PROCEDURE referrals(LEVEL INT, max_level INT, code VARCHAR(25)) 

WITH RECURSIVE referrals_path (id, NAME, CODE, lvl) AS
 (
SELECT c.id, c.name, c.code, 0 AS lvl
FROM users c
WHERE c.code = code UNION ALL
SELECT c.id, c.name, c.code, cp.lvl + 1
FROM category_path AS cp
JOIN users AS c ON cp.code = c.referred
) 

IF LEVEL > 1 THEN
SELECT * FROM referrals_path; 
ELSE
SELECT * FROM referrals_path WHERE lvl = LEVEL; 

END IF

1 个答案:

答案 0 :(得分:1)

您不能在查询中使用IF语句。它旨在根据条件执行SQL代码块,而不是在查询中使用。

但是,我认为您可以重新编写查询,如下所示:

WITH RECURSIVE referrals_path (id, NAME, CODE, lvl) AS (
    SELECT c.id, c.name, c.code, 0 AS lvl
    FROM users c
    WHERE c.code = code UNION ALL
    SELECT c.id, c.name, c.code, cp.lvl + 1
    FROM category_path AS cp
    JOIN users AS c ON cp.code = c.referred
) 
SELECT * 
FROM referrals_path
WHERE LEVEL > 1 OR lvl = LEVEL