SQL查询-IF EXISTS和WITH

时间:2018-04-06 00:57:52

标签: sql common-table-expression exists

您有一个带有WITH关键字的存储过程,它返回结果集,如下所示

WITH p as(...),
mp as (select *, x.name from p left join x on ...)

现在我想说

IF EXISTS (select * from mp where pid is not null and id != pid)
THEN 
  BEGIN
    SELECT * FROM cp left join mp on ...

  END 
ELSE
BEGIN  SELECT * FROM mp where...
END

这里我面临一些语法错误,这个选择应该从存储过程返回

更新

我把它如下

SELECT DISTINCT *
FROM (

    --get all parent records that matches RIDE ID
    SELECT * FROM mp WHERE pid is null or pid = id
    UNION --get parent of a child that matches RIDE ID
        SELECT pl.* [i have specified exact same columns in this select]
        FROM pl 
            left join mp on pl.plc_id = mp.PrimaryPlacementId  
            left join reg on reg.usr_id = mp.plc_usr and isnull(reg.usr_isdeleted, 0) = 0 --and reg.usr_active = 1
            left join ut on ut.cut_id = mp.plc_unit
            left join f on f.fac_id = mp.plc_facility and isnull(f.fac_isdeleted, 0) = 0
            left join s on s.sem_id = mp.plc_semester and isnull(s.sem_isdeleted, 0) = 0
        WHERE mp.pid != id AND mp.pid is not null

) x

这个似乎工作正常 - 基本上pid包含父ID

我的mp = pl表具有以下结构

id |名字| PID

1 |山姆| 1

2 | sid | 1

所以基本上第一个是父记录,第二个是子记录。

所以我想要的是 - 如果我搜索“sam'然后返回记录1 如果我搜索' sid'再次记录一个

即如果您按父ID或子ID搜索,则应返回父记录或其pid为空的记录

0 个答案:

没有答案