1

I have a scenario where I have to search value of column 1 in first table to see whether it matches some value in another table.

This should continue in a loop until the last row on first table has been compared.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
RAHUL
  • 21
  • 3
  • 2
    Your question is not clear. Please post your current data and expected results. Also, what have you tried before asking here? What, exactly, are you stuck on? – Rich Benner Jan 18 '17 at 13:23
  • I am having two tables..Table A and Table B.Column ABC having value as 1 has to be checked if exits in Table B in column ABC.This has to be in loop till end of rows. – RAHUL Jan 18 '17 at 13:28
  • 1
    Writing the same thing again isn't really helping. You need to add examples of what you want, containing examples what are in the tables, and what the result should be. Please edit your question to contain that. – James Z Jan 19 '17 at 18:41

1 Answers1

2

No loops needed. You can do this easily as a set based operation using exists()

select * 
  from FirstTable
  where exists (
  select 1 
    from SecondTable 
    where FirstTable.Column1 = SecondTable.Column1
    );

To find the opposite, where the row in the first table does not have a match based on Column1, you can use not exists()

select * 
  from FirstTable
  where not exists (
  select 1 
    from SecondTable 
    where FirstTable.Column1 = SecondTable.Column1
    );

If you want to identify which rows have a match and don't you can use:

select FirstTable.*
    , MatchFound = case when x.Column1 is null then 'No' else 'Yes' end
    , x.Column1
  from FirstTable 
  outer apply (
    select top 1 
        *
    from SecondTable 
    where FirstTable.Column1 = SecondTable.Column1
      ) as x
SqlZim
  • 37,248
  • 6
  • 41
  • 59
  • there are 30 rows in table which has to be compared row of first table with rows from second table – RAHUL Jan 18 '17 at 13:31
  • This compares all rows from the first table and checks all rows in the second table. What output are you looking for? – SqlZim Jan 18 '17 at 13:35
  • @SqlZim can you help here https://stackoverflow.com/questions/54959790/how-to-call-levenshtien-function-using-the-values-from-two-different-tables-in-t/54959816#54959816 – Shahid Manzoor Bhat Mar 02 '19 at 15:28