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

前端 未结 10 833
闹比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:17

    Assuming that you can connect to the SQL database which contains the table you want to copy at the point it time you want to do this, you could use a conventional resultset to datatable conversion, using

    select * from <tablename> where 1=2
    

    as your source query.

    This will return an empty result set with the structure of the source table.

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

    this works:

    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:21

    Here's what I did, which provides a blank DataTable ready to be used:

    SqlConnection _sqlConnection = new SqlConnection ();
    _sqlConnection.ConnectionString = @"Data Source=<SQL_Server/Instance>; Initial Catalog=<database_name>; Integrated Security=False; User ID=<user_id>;Password=<passowrd>";
    _sqlConnection.Open ();
    SqlCommand _sqlCommand = new SqlCommand ( "select * from DatabaseName.dbo.viewName", _sqlConnection ); 
    _dataSet = new DataSet ();
    _sqlDataAdapter = new SqlDataAdapter ( _sqlCommand );
    _sqlDataAdapter.Fill ( _dataSet );
    _schemaTable = new DataTable ();
    _sqlDataAdapter.FillSchema ( _schemaTable, SchemaType.Source );
    dataGridView.DataSource = _schemaTable;
    _sqlConnection.Close ();
    
    0 讨论(0)
  • 2021-02-07 05:25

    A statement I think is worth mentioning is SET FMTONLY:

    SET FMTONLY ON;
    SELECT * FROM SomeTable
    SET FMTONLY OFF;
    

    No rows are processed or sent to the client because of the request when SET FMTONLY is turned ON.

    The reason this can be handy is because you can supply any query/stored procedure and return just the metadata of the resultset.

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