2010-05-04 60 views
0

我需要用我在mysql表中選擇的記錄的Insert語句創建一個腳本文件。如何使用Insert語句爲在MySql中選擇的記錄創建腳本?

例如,當我做Select * from emp where empid = 5,並說我得到10條記錄作爲結果。 現在我應該創建一個帶有10條記錄的插入語句的腳本文件到emp表。

我使用C#作爲後面的代碼...

怎麼樣?

+0

由於沒有人知道你想要插​​入什麼,所以你最好舉一個你的表,數據和這些插入查詢的例子。 – 2010-05-04 06:24:21

+0

@Col。 Shrapnel,我有兩個數據庫A和B.這兩個數據庫都有相同的表格模式。所以我想從一個表中選擇並插入另一個數據庫中的類似表中。爲此,我需要爲任何選定的記錄創建一個Insert腳本。在這裏寫腳本是爲了我的項目需求。 – Anuya 2010-05-04 06:28:02

+0

Offcourse你知道如果兩個表都在同一臺服務器上,你可以插入B SELECT * FROM A,對吧? (或對該查詢的改進) – Konerak 2010-05-04 07:30:49

回答

0
DELIMITER $$ 

DROP PROCEDURE IF EXISTS `sample`.`InsGen` $$ 
CREATE DEFINER=`root`@`localhost` PROCEDURE `InsGen`(
in_db varchar(20), 
in_table varchar(20), 
in_ColumnName varchar(20), 
in_ColumnValue varchar(20) 
) 
BEGIN 

declare Whrs varchar(500); 
declare Sels varchar(500); 
declare Inserts varchar(200); 
declare tablename varchar(20); 
declare ColName varchar(20); 


set tablename=in_table; 


# Comma separated column names - used for Select 
select group_concat(concat('concat(\'"\',','ifnull(',column_name,','''')',',\'"\')')) 
INTO @Sels from information_schema.columns where table_schema=in_db and table_name=tablename; 


# Comma separated column names - used for Group By 
select group_concat('`',column_name,'`') 
INTO @Whrs from information_schema.columns where table_schema=in_db and table_name=tablename; 


#Main Select Statement for fetching comma separated table values 

set @Inserts=concat("select concat('insert IGNORE into ", in_db,".",tablename," values(',concat_ws(',',",@Sels,"),');') 
as MyColumn from ", in_db,".",tablename, " where ", in_ColumnName, " = " , in_ColumnValue, " group by ",@Whrs, ";"); 

PREPARE Inserts FROM @Inserts; 

EXECUTE Inserts;      

END $$ 

DELIMITER ; 
0

那麼現在你的問題是有道理的。 您可以在一個查詢

INSERT INTO B.emp SELECT * FROM A.emp WHERE empid = 5 
0

它曾與Norhtwind.Customer表內做到這一點。

using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Data.Common; 
    using System.Data; 
    using System.Data.Odbc; 
    using System.IO; 
    using System.Threading; 
    namespace DataAccessLayer 
    {  
     public class DBManager 
     { 
      //FILE LOGGER METHOD 
      public void SqlLogger(string SqlText) 
      { if (!File.Exists("SQL.txt")) 
       { using (StreamWriter sw = new StreamWriter("SQL.txt")) 
        { sw.Flush(); 
         sw.Close(); 
         sw.Dispose(); 
        } 
       } 

       using (StreamWriter sw = File.AppendText("SQL.txt")) 
       { sw.WriteLine(SqlText); 
        sw.WriteLine(" "); 
        sw.Flush(); 
        sw.Close(); 
        sw.Dispose(); 
       } 

      } 

      // DATABASE METHODS 
      public static OdbcConnection g_con = new OdbcConnection("Dsn=wsodbc1");  
      public DBManager() 
      { 

      } 
      public OdbcConnection GetConnection() 

      { try { g_con.Open();   } 
       catch (Exception ex)  {  } 
       return g_con;    
      } 
      public OdbcCommand GetCommand(string Query) 
      { 
       OdbcCommand cmd = new OdbcCommand(Query); 
       cmd.Connection = GetConnection(); 
       return cmd; 
      } 
      public void ExeCommand(string Query) 
      { 
       OdbcCommand cmd = GetCommand(Query); 
       cmd.ExecuteNonQuery();  


      } 
      public OdbcDataReader GetReader(string Query) 
      { return GetCommand(Query).ExecuteReader();  } 

      // SQL INSERT GENERATOR 
      public void GenerateSql(string tablename) 
      { 
       File.Delete("SQL.txt"); 
       List<string> cols = new List<string>(); 
       string ColNames; 


       OdbcDataReader reader = GetReader("SELECT  * FROM   Customers "); 

       DataTable schemaTable = reader.GetSchemaTable(); 

       foreach (DataRow row in schemaTable.Rows) 
       { foreach (DataColumn column in schemaTable.Columns) 
       {   
        if (column.ColumnName.Equals("ColumnName")) cols.Add(row[column].ToString().ToUpper());      
        } 
       } 


        ColNames = string.Join(",", cols.ToArray()); 


        while (reader.Read()) 
       { 

        SqlLogger("INSERT INTO " + tablename + " (" + ColNames + ") VALUES (" + Row_Values(reader) + ")"); 

       } 

      } 
      public string Row_Values(OdbcDataReader r) 
      { 
        List<string> colsVals = new List<string>(); 

        for (int i = 0; i < r.FieldCount; i++) 
        { 

         if (r[i].GetType().ToString().Equals("System.String")) 
         { 
          if (r[i] == null) 
          { 
           colsVals.Add("NULL"); 
          } 
          else 
          { 
           colsVals.Add("'" + r[i].ToString().Replace("'","''").Replace(",","-") + "'"); 
          } 

         } 
         else if (r[i].GetType().ToString().Equals("System.DBNull")) 
         { 
          colsVals.Add("NULL"); 
         } 
         else 

         { 
          if (r[i] == null) 
          { 
           colsVals.Add("NULL"); 
          } 
          else 
          { 
           var VAL = r[i].ToString(); 
           colsVals.Add("'" + VAL.ToString().Replace("'", "''").Replace(",", "-") + "'"); 
          } 

         } 
        } 

        return string.Join(",", colsVals.ToArray()); 
      } 
     } 
    } 
相關問題