DB2 replace into实现
最近进入到另一个项目, 数据库用的是DB2, 要实现MySQL中类似replace into的功能, 网上搜了下, 实现了一个类似功能的基础方法(PHP实现)
public function replace($table, $arr, $pks){ $values = ''; $keys = ''; $mergeValues = ''; $upStatement = ''; $first = true; foreach($arr as $key => $val){ if (!$first){ $values .= ','; $keys .= ','; $mergeValues .= ','; $upStatement .= ','; } else{ $first = false; } $values .= "'{$val}'"; $keys .= $key; $mergeValues .= "merge.{$key}"; $upStatement .= "tab.{$key} = merge.{$key}"; } $first = true; $pkstr = ''; foreach($pks as $pk){ if (!$first){ $pkstr .= ' AND '; } else{ $first = false; } $pkstr .= "tab.{$pk} = merge.{$pk}"; } $sql = "MERGE INTO {$table} AS tab USING (VALUES ({$values}) ) AS merge ({$keys}) ON {$pkstr} WHEN MATCHED THEN UPDATE SET {$upStatement} WHEN NOT MATCHED THEN INSERT ({$keys}) VALUES ({$mergeValues})"; $this->db->query($sql); }
参考链接:
http://www.withdata.com/blog/db2/replace-update-or-insert-a-row-into-db2-table-merge-into.html
本篇文章首发自魔芋红茶的博客https://www.cnblogs.com/Moon-Face/
请尊重其他人的劳动成功,转载请注明。