2017-12-11 8 views
0

私はSQL Serverデータベース(ビット簡体字)に対してSQL SELECTに基づいてロードDataTableに対して次の補助機能を持っている:DataTableを満たすSELECTからSQL Server上の元のスキーマを取得する方法?

static private DataTable GetData_(string connectionString, string sqlSelect, bool doFillSchema = false) 
{ 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    using (SqlDataAdapter adapter = new SqlDataAdapter(sqlSelect, connection)) 
    { 
     DataTable table = new DataTable(); 

     if (doFillSchema) 
      adapter.FillSchema(table, SchemaType.Mapped); 

     adapter.Fill(table); 
     return table; 
    } 
} 

以降の目標は、コンテンツをエクスポートする必要があります別の関数に返されtableを渡すことですDBFテーブル(CREATE TABLEを作成し、エンジンのさまざまな機能に関連するいくつかの修正を含むコンテンツを書き込む)に変換します。

問題は、実装では、オリジナルのnumeric(10, 2)の列の種類がスキーマのDecimalに変更されることです。私はオリジナルを保存したいと思います。

私がよく理解していれば、元のスキーマを持つ別のDataTable schemaTableを取得する必要があります(アダプターによって列の種類が変更される前に)。私の考えは、そのような関数を変更することでした:

static private DataTable GetData_(string connectionString, string sqlSelect, 
            bool doFillSchema, ref DataTable schemaTable) 
{ 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    using (SqlDataAdapter adapter = new SqlDataAdapter(sqlSelect, connection)) 
    { 
     DataTable table = new DataTable(); 

     if (doFillSchema) 
      ??? fill the schema table 

     adapter.Fill(table); 
     return table; 
    } 
} 

どのように機能を実装する必要がありますか?目的のためにSqlDataAdapterを使用すべきですか?それとも別のやり方ですべきか?

答えて

0

私はこの自己回答を持っています。より良い解決策があれば、私はそれを受け入れることを嬉しく思うでしょう。 ;)

static private DataTable GetData_(string connectionString, string sqlSelect, Hashtable arg, 
            bool doFillSchema, ref DataTable schemaTable) 
{ 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    using (SqlCommand command = new SqlCommand(sqlSelect, connection)) 
    { 
     connection.Open(); 

     // If we want the schema, do the extra step. 
     if (doFillSchema) 
     { 
      using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo)) 
       schemaTable = reader.GetSchemaTable(); 
     } 

     // Use the adapter to fill the result table.. 
     using (SqlDataAdapter adapter = new SqlDataAdapter(command)) 
     { 
      DataTable table = new DataTable(); 

      // Set the SELECT arguments. 
      if (arg != null) 
      { 
       foreach (DictionaryEntry item in arg) 
       { 
        adapter.SelectCommand.Parameters.AddWithValue(item.Key.ToString(), item.Value); 
       } 
      } 

      // Get the result of the SQL query. 
      adapter.Fill(table); 
      return table; 
     } 
    } 
} 
関連する問題