Search code examples
sqlsql-serverjoinselectsql-server-2012

How to join 2 tables (Table 2 data if present in Table 1, that specific record must not be selected) in SQL Server


I have 2 tables, Table1 and Table2. Both tables have only 1 column value.

  • Table1 - er3, 5ty, 5y6, 72j, 98e, sf1, 3mn, 9w2
  • Table2 - r5k, ad8, 5ty, sf1, 34x

How can we query, so that we can get the below result.

Result: er3, 5ty, 5y6, 72j, 98e, sf1, 3mn, 9w2, r5k, ad8, 34x

I tried this code:

SELECT value 
FROM Table1 T1
JOIN Table2 T2 ON T2.value = T1.value
WHERE T2.value IS NOT NULL

This query is not returning the expected result.

Expected result: er3, 5ty, 5y6, 72j, 98e, sf1, 3mn, 9w2, r5k, ad8, 34x

Table2 is the input param values, need to check with Table1 values and if exist, must not include that value while joining as we already have that value in Table 1.

Thanks in advance

Edit - I have adopted Tim Biegeleisen's solution and it works fine. When union statement was assigned to a variable as below

SELECT @UpdatedValues = SELECT value FROM Table1 
UNION 
SELECT value FROM Table2

got the below error message.

Error Message - Variable assignment is not allowed in a statement containing a top level UNION, INTERSECT or EXCEPT operator.

I have to assign the result set to a variable. How can this be achieved. Thanks in advance.

Edit (2)

I have achieved the desired result taking MartinSmith's comments.

Final SQL Query for my solution

SELECT @UpdatedValues = STRING_AGG(d.value, ',')  
WITHIN GROUP(ORDER BY value) 
FROM (SELECT value FROM Table1 UNION SELECT value FROM Table2) d

Solution

  • Try this one I think there is no need to join them

    ;WITH test AS(
      SELECT value FROM Table1 UNION ALL
      SELECT value FROM Table2
    )
    
    SELECT DISTINCT value FROM test