2

I'd like to create a loop and an IF Else statement in SQL Server to check a set of condition in each row of a table and do something if all conditions are met.

I'd like to do something like the example below in SQL Server:

For each row in table1:
   If (table1.dob is null
       and table1.name = table2.name
       and table1.surname=table2.surname){
       update table1
       set dob = table2.dob}
   Else {
      Do nothing
   End If
End loop

Can anyone help me please?

Thanks,

Eduardo

3
  • 1
    SQL is designed to tell database what to do, but not HOW to do it. SQL query engine will decide how to execute the query, so you don't need to write explicit imperative logic for your database. Commented Feb 6, 2018 at 1:12
  • Hi Daniel, in this example let's suppose I have only 2 tables: table 1 (name, surname, dob) and table 2 (name, surname, dob). Suppose I have many null values on table1.dob and no null values on table 2. Thanks Commented Feb 6, 2018 at 1:14
  • you can take the query from Tim's reply and change INNER JOIN to LEFT or RIGHT JOIN or OUTER JOIN to deal with nulls in the way you need Commented Feb 6, 2018 at 1:19

1 Answer 1

5

You don't need loops for this, a standard update join should suffice:

UPDATE t1
SET dob = t2.dob
FROM table1 t1
INNER JOIN table2 t2
    ON t1.name = t2.name AND
       t1.surname = t2.surname
WHERE
    t1.dob IS NULL;
Sign up to request clarification or add additional context in comments.

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.