Skip to content
Advertisement

How to Exclude Record Based on Multiple Fields where Records May Share Values

I have two tables of addresses. They are formatted very similarly, to [main] table also has the customer name

CREATE TABLE [shipTo] 
(
    [id] int IDENTITY(1,1),
    [custID] int,
    [address1] varchar(255),
    [address2] varchar(255),
    [city] varchar(255),
    [state] varchar(255),
    [zip] varchar(255)
)

The shipto table has many addresses for each main customer, and many times the main addresses is also listed as a shipto. I do not want to include that main address in my results but I can’t get it to work correctly since in many cases the other addresses may share a city or state, or even a blank address2.

Here is what I have…

SELECT 
    @tmpCustID = [id], 
    @chkAddress1 = [Address 1], 
    @chkAddress2 = [Address 2], 
    @chkCity = [City], 
    @chkState = [State],  
    @chkZip = [Zip] 
FROM 
    [main] 
WHERE 
    [id] = @cnt

SELECT * 
FROM [shipTo]  
WHERE [custID] = @tmpCustID
  AND [Address 1] <> @chkAddress1
  AND [Address 2] <> @chkAddress2
  AND [City] <> @chkCity
  AND [State] <> @chkState
  AND [Zip] <> @chkZip

Here is the data:

MAIN

|id| address1     | address2      | city     | state | zip   |
|2 | 123 baker st |               | columbus | oh    | 43081 |

SHIPTO

|id| custid| address1       | address2       | city         | state | zip   |
|1 | 2     | 123 baker st   |                | columbus     | oh    | 43081 |
|2 | 2     | 626 oak point  |                | cleveland    | oh    | 43092 |
|3 | 2     | 17 purple blvd |                | columbus     | ga    | 81265 |
|4 | 2     | 851 brawny     |                | grand rapids | mi    | 49417 |
|5 | 2     | 101 olive rd   | suite #3       | grand rapids | mi    | 49417 |

I am expecting it to return id 2-5, but it’s only returning #5 because it’s matching some element of the main address to the shipto, but I need it to see the record as a whole.

I also tried adding an AND and parenthesis thinking that it would work, but that didn’t either.

SELECT * 
FROM [shipTo]  
WHERE [custID] = @tmpCustID
  AND ([Address 1] <> @chkAddress1
  AND [Address 2] <> @chkAddress2
  AND [City] <> @chkCity
  AND [State] <> @chkState
  AND [Zip] <> @chkZip)

Advertisement

Answer

Maybe try this query

SELECT * FROM [shipTo]  
WHERE [custID] = @tmpCustID
AND NOT
([Address 1] = @chkAddress1
 AND [Address 2] = @chkAddress2
 AND [City] = @chkCity
 AND [State] = @chkState
 AND [Zip] = @chkZip)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement