Created
June 15, 2018 04:05
-
-
Save Faz95210/72d3b9aca1e05134096ab21422052333 to your computer and use it in GitHub Desktop.
[Copy an SQLServer table to another in PHP] Copy the content from an SQLserver table to another #PHP #SQLserver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private function copyTableToTable($dbSrc, $dbDest, $tableSrc, $tableDest = null) { | |
if ($tableDest == null) { // If null then assume tables have same name | |
$tableDest = $tableSrc; | |
} | |
$dbDest->query("TRUNCATE TABLE $tableDest"); //Empty Dest table in case it's not already done. | |
$columns = $this->db->query("SELECT c.name FROM" | |
. " sys.columns c" | |
. " INNER JOIN " | |
. " sys.types t ON c.user_type_id = t.user_type_id" | |
. " LEFT OUTER JOIN " | |
. " sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id" | |
. " LEFT OUTER JOIN " | |
. " sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id" | |
. " WHERE" | |
. " c.object_id = OBJECT_ID('$tableSrc')")->rows; //Get array with column names | |
$column_list = "(" . $columns[0]['name']; | |
for ($index = 1; $index < count($columns); $index++) { | |
$column_list .= ","; | |
$column_list .= "[" . $columns[$index]['name'] . "]"; | |
} | |
$column_list .= ")"; // Fill columns part of the INSERT INTO query | |
$rows = $dbSrc->query("SELECT * FROM $tableSrc")->rows; //Get content from src table | |
foreach ($rows as $row) { //Loop through every row to insert | |
$values = array_values($row); // Get the values in an array | |
$sql = "INSERT INTO $tableDest "; | |
$sql .= $column_list; | |
$sql .= " VALUES ('" . $values[0] . "'"; // Fill the values parenthesis of the query | |
for ($index = 1; $index < count($values); $index++) { | |
$sql .= ",'" . $values[$index] . "'"; | |
} | |
$sql .= ")"; | |
try { | |
$dbDest->query($sql); // Insert it. | |
} catch (Exception $e) { // on id insert error catch exception and retry with identity_insert set to ON. | |
$identity = "SET IDENTITY_INSERT $tableDest ON;"; //SQLSERVER prevent inserting IDs if nidentity_insert isn't set to ON and the columns list isn't ther | |
$dbDest->query($identity . $sql); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment