Delete Parent record if child is not present

后端 未结 3 1294
猫巷女王i
猫巷女王i 2021-01-18 15:54

I am creating menu and submenus in a table variable. ( Typical parent child records in the same table) ParentID coll is null for all Top menus. And for their child ParentID

3条回答
  •  Happy的楠姐
    2021-01-18 16:29

    Without seeing your table structure it's difficult to tell you the exact query you would need but, if I understand your question correctly, you just need to do something like this:

    DELETE T 
    FROM MyTable T 
    WHERE NOT EXISTS(SELECT * FROM MyTable WHERE ParentID = T.MenuID)
        AND T.ParentID IS NULL
    

    This query does a correlated subquery to find all the menu records that don't have child records. It uses SQL's EXISTS clause

提交回复
热议问题