Search code examples
sqlsql-servert-sqlsql-deletecorrelated-subquery

Deleting from table based upon the result set of other query


I am trying to delete data from a table by looking up on the result set which is returned by correlated sub-query. My queries are as below.

select DISTINCT M24no,M0no
from V_SRC_I_FIN_ENGMNT_STG E

The above query will return a table result-set as below.

M24no M0no
2546  2570

Now I need to delete all the records from I_IPV_LOB_PROG_PROV_MO_MTRC_TRNS table which has MO_IDS between M24no and M0no.

I am trying to do something like this as below but it seems to be incorrect. Can somebody suggest me an amicable solution?

DELETE
FROM I_IPV_LOB_PROG_PROV_MO_MTRC_TRNS
WHERE LST_UPD_USERID='FINANCE'
AND MO_ID IN 
(select DISTINCT M24no,M0no
from V_SRC_I_FIN_ENGMNT_STG E)

Solution

  • This can be accomplished using an INNER JOIN to the V_SRC_I_FIN_ENGMNT_STG table and the BETWEEN clause:

    DELETE  A
      FROM  I_IPV_LOB_PROG_PROV_MO_MTRC_TRNS A
        INNER JOIN V_SRC_I_FIN_ENGMNT_STG B ON A.MO_ID BETWEEN B.M24no AND B.M0no
      WHERE LST_UPD_USERID = 'FINANCE'
    

    So effectively you delete everything from table A (I_IPV_LOB_PROG_PROV_MO_MTRC_TRNS) that is joined to B (V_SRC_I_FIN_ENGMNT_STG) where MO_ID is between M24no and M0no.