Get Array Difference

PeterP1550 80 Reputation points
2023-07-25T03:50:03.3633333+00:00

How do you return the difference?

CREATE TABLE Table1
(
    fname VARCHAR(25) NOT NULL,
    val VARCHAR(500) NOT NULL
)
INSERT INTO Table1 VALUES
('Bob','apple, orange, grape')

CREATE TABLE Table2
(
    fname VARCHAR(25) NOT NULL,
    val VARCHAR(500) NOT NULL
)
INSERT INTO Table2 VALUES
('Jane','pear, lemon, orange')

If returning the difference results from Table1 it should look like this result.

select 'Bob' as fname,'apple, grape' as val

If returning the difference results from Table2 it should look like this result.

select 'Jane' as fname,'pear, lemon' as val

SQL Server | Other
0 comments No comments
{count} votes

Answer accepted by question author
  1. Anonymous
    2023-07-25T07:37:18.2566667+00:00

    Hi @PeterP1550

    You can try this.

    ;with T1 as(
      select value from table1 cross apply string_split(val,',')
      except
      select value from table2 cross apply string_split(val,',')
    ),T2 as(
      select STRING_AGG(value,',') as val from T1)
    select fname,T2.val from table1,T2;
    

    Output:

    User's image


    ;with T1 as(
      select value from table2 cross apply string_split(val,',')
      except
      select value from table1 cross apply string_split(val,',')
    ),T2 as(
      select STRING_AGG(value,',') as val from T1)
    select fname,T2.val from table2,T2;
    

    Output:

    User's image

    Best regards,

    Percy Tang


1 additional answer

Sort by: Most helpful
  1. Olaf Helper 47,591 Reputation points
    2023-07-25T05:15:36.55+00:00

    The result set format don't make sense, because it could return 0-n records.

    To get the data differents between 2 tables, see Set Operators - EXCEPT and INTERSECT (Transact-SQL)

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.