Mohammadreza
Mohammadreza

Reputation: 3229

SQL Server : compare two tables and return similar rows

I want to compare two tables, source and target, and get similar rows.

Compare source and target on Id one by one and:

I think need a recursive expression to check source and target one by one

Source

x------x---------x
|  Id  |   Name  |
x------x---------x
|   1  |   a     |
|   2  |   b     |
|   2  |   c     |
|   3  |   d     |
|   3  |   e     |
|   4  |   x     |
x------x---------x

Target

x------x---------x
|  Id  |   Name  |
x------x---------x
|   1  |   f     |
|   1  |   g     |
|   2  |   h     |
|   3  |   i     |
|   3  |   j     |
|   5  |   y     |
x------x---------x

Result

x------x---------x
|  Id  |   Name  |
x------x---------x
|   1  |   f     |
|   1  |   g     |
|   2  |   h     |
|   3  |   i     |
|   3  |   j     |
x------x---------x

Test data

declare @s table(Id int, name varchar(20))
DECLARE @t table( Id int, name varchar(20))

INSERT @s values(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (3, 'e')

INSERT @t values(1, 'f'), (1, 'g'), (2, 'h'), (3, 'i'), (3, 'j')

Upvotes: 2

Views: 79

Answers (2)

rajesh yadav
rajesh yadav

Reputation: 1

SELECT DISTINCT 
    t.Id,
    t.name
FROM SOURCE s
INNER JOIN target t ON s.id=t.Id
WHERE s.Id IN (SELECT Id FROM target)

Upvotes: -1

Pரதீப்
Pரதீப்

Reputation: 93754

I think you just need Exists operator to do this.

select * from @t t
where exists (select 1 from @s s where t.id=s.id)

SQLFIDDLE DEMO

Upvotes: 2

Related Questions