Need to get empty datatable in .net with database table schema

前端 未结 10 853
闹比i
闹比i 2021-02-07 04:40

What is the best way to create an Empty DataTable object with the schema of a sql server table?

相关标签:
10条回答
  • 2021-02-07 05:09

    Here's what I did:

    var conn = new SqlConnection("someConnString");
    var cmd = new SqlCommand("SET FMTONLY ON; SELECT * FROM MyTable; SET FMTONLY OFF;",conn); 
    var dt = new DataTable();
    conn.Open();
    dt.Load(cmd.ExecuteReader());
    conn.Dispose();
    

    Works well. Thanks AdaTheDev.

    0 讨论(0)
  • 2021-02-07 05:10

    All of these solutions are correct, but if you want a pure code solution that is streamlined for this scenario.

    No Data is returned in this solution since CommandBehavior.SchemaOnly is specified on the ExecuteReader function(Command Behavior Documentation)

    The CommandBehavior.SchemaOnly solution will add the SET FMTONLY ON; sql before the query is executed for you so, it keeps your code clean.

    public static DataTable GetDataTableSchemaFromTable(string tableName, SqlConnection sqlConn, SqlTransaction transaction)
    {
        DataTable dtResult = new DataTable();
    
        using (SqlCommand command = sqlConn.CreateCommand())
        {
            command.CommandText = String.Format("SELECT TOP 1 * FROM {0}", tableName);
            command.CommandType = CommandType.Text;
            if (transaction != null)
            {
                command.Transaction = transaction;
            }
    
            SqlDataReader reader = command.ExecuteReader(CommandBehavior.SchemaOnly);
    
            dtResult.Load(reader);
    
        }
    
        return dtResult;
    }
    
    0 讨论(0)
  • 2021-02-07 05:12

    Try: SELECT TOP 0 * FROM [TableName]

    and use SQLDataAdapter to fill a DataSet, then get the Table from that DataSet.

    0 讨论(0)
  • 2021-02-07 05:14

    I know that this is an old question and specific to SQL Server. But if you are looking for generic solution that will work across different databases, use Richard's solution, but modify it to use "SELECT * FROM {0} WHERE 1=0" and change the types to use generic ADO.Net types IDataReader, IDbCommand etc.

    Most modern relational databases are intelligent enough to identify the 1=0 condition and will not run it like a regular tablescan query. I have tried this on SQL Server, Oracle and DB2 with tables have few 100 million records also. All do return empty result back in matter of few milliseconds.

    0 讨论(0)
  • 2021-02-07 05:16
    Class BlankTableWithSourceTableSchema
        Inherits DataTable
        Public Sub New(ByVal connstr As String, ByVal sourcetable As String)
            Try
                Using connection As SqlServerCe.SqlCeConnection = New SqlServerCe.SqlCeConnection(connstr)
                    Dim adapter As SqlServerCe.SqlCeDataAdapter = New SqlServerCe.SqlCeDataAdapter("SELECT * FROM " & sourcetable, connection)
                    adapter.TableMappings.Add("Table", "ABlankTable")
                    adapter.FillSchema(Me, SchemaType.Mapped)
                End Using
            Catch ex As Exception
            End Try
        End Sub
    End Class
    
    0 讨论(0)
  • 2021-02-07 05:16

    You can always create your own:

            DataTable table = new DataTable("TableName");
    
            table.Columns.Add(new DataColumn("Col1", typeof(int)));
            table.Columns.Add(new DataColumn("Col2", typeof(int)));
            table.Columns.Add(new DataColumn("Col3", typeof(string)));
            table.Columns.Add(new DataColumn("Col4", typeof(int)));
            table.Columns.Add(new DataColumn("Col5", typeof(string)));
    

    The obvious draw back being that you will have to update your code whenever the database schema changes.

    0 讨论(0)
提交回复
热议问题