对于在SQL Server中使用if else语句的循环

时间:2021-09-06 02:05:19

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.

我想在SQL Server中创建一个循环和一个IF Else语句来检查表的每一行中的一组条件,并在满足所有条件时执行某些操作。

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

我想在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

爱德华多

1 个解决方案

#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;

#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;