話不多說,直接上代碼。
#!/usr/bin/perluse DBI;use Switch;#申請串連資源,因為Perl串連SQL Server只能用ODBC,如果還沒部署好環境的,請參見小弟另一篇博文 【PERL連MSSQL】 http://www.cnblogs.com/davyfamer/archive/2012/05/31/2528818.html$dbh=DBI->connect('dbi:ODBC:##隱去的ODBC資料庫連接##','##隱去的MSSQL使用者名稱##','##隱去的MSSQL資料庫密碼##'); #擷取所有需要匯入到MySQL的表my $sth=$dbh->prepare("select name,object_id from sys.all_objects where type='U' and is_ms_shipped=0 and name <>'sysdiagrams'");$sth->execute();while (@data=$sth->fetchrow_array()){#@data=$sth->fetchrow_array();#測試時禁用迴圈,只看一張表#擷取列get_columns($data[0],$data[1]);}#$dbh ->disconnect; #添加了斷開語句後,會報錯,難道ODBC不需要斷開?有點頭暈。##擷取所有的列sub get_columns{$dbh2=DBI->connect('dbi:ODBC:##隱去的ODBC資料庫連接##','##隱去的MSSQL的使用者名稱##','##隱去的MSSQL資料庫的密碼##');my $sql="select col.name,tp.name,col.max_length,col.[precision],col.[scale],col.[is_nullable],col.[is_identity] from sys.all_columns colinner join sys.types tp on col.system_type_id=tp.system_type_id and col.user_type_id=tp.user_type_idwhere object_id=$_[1]";my $cols=$dbh2 -> prepare($sql);$cols->execute();my $cols_str = "";while(@col= $cols->fetchrow_array()){($col_name,$type_name,$max_length,$precision,$scale,$is_nullable,$is_identity)=@col;#做類型轉換。。。switch ( $type_name) { case "nchar" { $type_name="char"; } case "bit" { $type_name="boolean"; } case "ntext" { $type_name="text"; } case "nvarchar" { $type_name="varchar"; } else { $type_name=$type_name;}}if($cols_str ne ""){$cols_str = "$cols_str, \n";}#對hierarchyid 做特殊處理if($type_name eq "hierarchyid"){if($cols_str eq ""){#$cols_str = "$cols_str `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,`parent_id` INT";$cols_str = "$cols_str `$col_name` varchar(31)";}else{$cols_str = "$cols_str `$col_name`varchar(31)";}}else{$cols_str = "$cols_str `$col_name` $type_name";switch($type_name){case "varchar" {#sql server中的VARCHAR(MAX)if($max_length == -1){$cols_str = "$cols_str(65535)";}else{$cols_str = "$cols_str($max_length)";}}case "numeric"{$cols_str = "$cols_str($precision,$scale)";}}#是否能為空白if($is_nullable == 0){$cols_str="$cols_str NOT NULL ";}#是否為標識符if($is_identity == 1){$cols_str="$cols_str AUTO_INCREMENT PRIMARY KEY";}}}#print "create table IF NOT EXISTS `$_[0]`($cols_str);";exec_mysql( "create table IF NOT EXISTS `$_[0]`($cols_str);");#$dbh2 ->disconnect; #這一句加了會報錯}#在MySQL中建表sub exec_mysql{my $db_name="##隱去的MySQL目標資料庫名##";my $location="##隱去的MySQL資料庫IP地址##";
my $port="##隱去的MySQL資料庫連接埠##";my $data_base = "DBI:mysql:$db_name:$location:$port";my $db_user="##隱去的MySQL資料庫使用者名稱##";my $db_pass="##隱去的MySQL資料庫密碼##";my $dbh3=DBI -> connect($data_base,$db_user,$db_pass);my $sth=$dbh3->prepare($_[0]);$sth->execute() or die "ERROR::$_[0]::$dbh3->errstr";$dbh3->disconnect;}