Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 838
Ronnie Overby Avatar asked Feb 24 '10 13:02

Ronnie Overby


People also ask

How check DataTable is empty or not in C#?

GetChanges(); foreach (DataRow dr in dataTable1) { // ... } DataSet has DataSet. HasRow but DataTable doesn't have such method. If there is no changed rows.

Can DataTable be null?

Solution 1. If a DataTable is null then you can't copy anything to it: there isn't anything to copy into!

How can I get all data from a table?

SELECT statements SELECT column1, column2 FROM table1, table2 WHERE column2='value'; In the above SQL statement: The SELECT clause specifies one or more columns to be retrieved; to specify multiple columns, use a comma and a space between column names. To retrieve all columns, use the wild card * (an asterisk).


1 Answers

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;
}
like image 165
Richard R Avatar answered Oct 14 '22 17:10

Richard R