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

前端 未结 10 830
闹比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: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;
    }
    

提交回复
热议问题