Search code examples
sqlsap-ase

Delete From One Table Based on Two Columns in Another


I need to delete values in a temp table based on both values in another. In other words, I do not want any item_desc left in B for an id that has a style_cd listed in A.

#tempA
style_cd char(3),
id_cd varchar(15)

Some sample values are like:

A, 123456
A, 654321
B, 321456
A, 654123
C, 424242

.

#tempB
item_desc varchar(50),
item_num char(4),
style_cd char(3),
id_cd varchar(15)

Sample values for this table:

item 1,  7, A, 123456
item 2, 14, B, 123456 
item 2, 14, A, 123456
item 3, 23, A, 123456
....snip....
item 2, 14, B, 654321
item 2, 14, A, 654321
item 6, 44, A, 654321

For example - for id 123456 I want to remove both entries for item 2 from B. Each item can have several styles associated with it. An id will usually only have one style associated with it but could conceivably have several.

I must be running into a block because this doesn't seem that complicated. I have been working on this for two days and can't get anything but all rows deleted. I have been trying something along the lines of:

DELETE #tempB
WHERE style_cd IN 
    (SELECT style_cd
     FROM #tempB b JOIN tempA a
     ON b.id_cd = a.id_cd
     AND b.style_cd = a.style_cd)

Of course this deletes all the rows and I can't for the life of me figure out how to just get rid of only rows associated with the style_cd values listed for an id in Table A. I hope this makes sense and someone can put me out of my misery!!!!

I am using Sybase ASE 15.0.2

ADD... I used @john's suggestion as a starting point. When I test the select it picks out the rows I need for it to.

    SELECT a.style_cd
    FROM #tempB b
      JOIN #tempA a
      ON a.id_cd = b.id_cd
      AND a.style_cd = b.style_cd 

When I add in any Delete clause it wipes out everything

DELETE FROM #tempB
WHERE style_cd IN 
(SELECT style_cd
 FROM #tempB b JOIN tempA a
 ON b.id_cd = a.id_cd
 AND b.style_cd = a.style_cd)

Somehow I am not getting just the rows from the list in the select removed from tempB


Solution

  • It's just a simple confusion between DELETE #tempDB and DELETE *FROM* #tempDB

    Try your same query modified like so:

    DELETE FROM #tempB
    WHERE style_cd IN 
        (SELECT style_cd
         FROM #tempB b JOIN tempA a
         ON b.id_cd = a.id_cd
         AND b.style_cd = a.style_cd)