SQL 遍历 table A 并在 table B 中插入/更新

SQL Loop through table A & Insert/ Update in table B

在存储过程中遍历 table "A" 的所有行的最佳方法是什么?如果 table "B" 中存在记录,则按 Id 检查& 根据结果(是否在 table B 中找到)执行 "Insert" 或 "Update" 到 table "B".

例如:

//LOOP START
    //if ID Exists in Table B.
        //Take current row table a values and update table "B"
    Else
        //Take current row table a values and insert into table "B"
//LOOP END

谢谢

在 SQL 2008

上使用 MERGE INTO 命令
MERGE INTO table_B as Target
USING (
    Select
        Id, Field1, Field2
    FROM table_A ) as Source
ON Source.Id = Target.Id
WHEN NOT MATCHED THEN
    INSERT( Id, Field1, Field2 )
    VALUES( Source.Id, Source.Field1, Source.Field2 )
WHEN MATCHED THEN
    UPDATE
    SET
        target.Id = Source.Id
        ,target.Field1 = Source.Field1
        ,target.Field2 = Source.Field2
;