0

I have a table as follows: table 1

temp_id    node_name  variable_1 variable_2 variable_3
1          ab         a          b           y
2          sdd        a          a           a
3          u          a          s           s

and another table as follows: table 2

temp_id    node_name  variable_1 variable_2 variable_3
1          ab         as        sb           y
2          sdd        a          a           a
3          u          a          s           s

I want to fetch all the records from table 1 where variable_1, variable_2 and variable_3 of table 1 doesnot match with table 2.

How can I do that in TSQL?

4
  • I'm assuming temp_id and node_name have to match? Commented Sep 22, 2011 at 23:53
  • Create a new table, or fetch records? Commented Sep 22, 2011 at 23:55
  • yes ... the join will be on temp_id and node_id. Commented Sep 22, 2011 at 23:56
  • i want to create a new table. Commented Sep 22, 2011 at 23:56

2 Answers 2

3

Try this:

INSERT INTO new_table
SELECT t1.* FROM table1 AS t1
LEFT JOIN table2 AS t2
ON t1.temp_id = t2.temp_id AND 
   t1.node_name = t2.node_name
WHERE t1.variable_1 <> t2.variable_1 AND
      t1.variable_2 <> t2.variable_2 AND
      t1.variable_3 <> t2.variable_3
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT * FROM [table 1] t1
WHERE NOT EXISTS (
    SELECT * FROM [table 2] t2
    WHERE
        t1.variable_1 = t2.variable_1
        AND t1.variable_2 = t2.variable_2
        AND t1.variable_3 = t2.variable_3
)

---EDIT---

The above will "fetch all the records from table 1 where variable_1, variable_2 and variable_3 of table 1 doesnot match with table 2", as you asked.

However, it seems that you want to match the specific rows from table 2 not just any rows (BTW, you should have specified that in your question). If that is the case, Marco's answer looks good.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.