How to delete all but 1?

  • I have a table RoleModule (roleModule_ID, role_ID, Module_ID)

    I want to delete all rows from RoleModule table where role_ID=10 for example but I want to leave one RoleModule row where role_ID=10

    How to do that??

  • This assumes that the combination of ID values is unique -- specifically, that the roleModule_ID field is a unique identifier of some sort for the table.

    DELETE
    FROM RoleModule
    Where Role_ID = 10
      AND roleModule_ID Not In 
       (Select Min(roleModule_ID) FROM RoleModule Where Role_ID = 10)

    Note that this can be modified in multiple ways:

    • Change the subselect to not have the Role_ID specified, and GROUP BY Role_ID instead.  Now you can use this subselect to keep only one from each Role_ID
    • Group the Subselect by both Role_ID And Module_ID (in case of duplicates in the table)
    • Yadda, yadda, yadda...

     

  • select count(*) where yada, yada

    then set rowcount = count(*) - 1

    delete where yada, yada

     

  • and then:

    set rowcount 0

  • Hi!

    Probably this code will help you.....

    delete RoleModule

    where roleModule_ID not in (select max(roleModule_ID) from RoleModule

        group by Role_ID

        having count(*) > 1 )

    and Role_ID in (select Role_ID from RoleModule b

        group by Role_ID

        having count(*) > 1)

    This is generic for deleting the values that are occuring more than once in your table leaving one occurance.

     

    Indu


    Best Regards,

    Indu Jakhar

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply