Daniel A. White
Daniel A. White

Reputation: 190915

Creating database schema from DataTable

Is it possible, without writing any SQL or using any 3rd party libraries to create a database schema from several ADO.NET DataTables?

Upvotes: 0

Views: 3259

Answers (3)

Prahalad Gaggar
Prahalad Gaggar

Reputation: 11599

Here is the code

SqlConnection con = connection string;
        con.Open();
        string sql = "Create Table abcd (";
        foreach (DataColumn column in dt.Columns)
        {
            sql += "[" + column.ColumnName + "] " + "nvarchar(50)" + ",";
        }
        sql = sql.TrimEnd(new char[] { ',' }) + ")";
        SqlCommand cmd = new SqlCommand(sql, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        cmd.ExecuteNonQuery();
con.close();

I am giving a predefined table-name abcd.

Upvotes: 0

GSerg
GSerg

Reputation: 78155

Not sure how "not sql" this is, but you can use SQL Server Management Objects.

Upvotes: 2

Sean Thoman
Sean Thoman

Reputation: 7489

Its easy to make a function that writes the SQL for you. However if you don't want to use SQL at all I would think you're out of luck:

    private string GetSqlCommand(Dictionary<string, Type> schema, string tableName, bool includeIdentity)
    {
        string sql = "CREATE TABLE [" + tableName + "] (\n";

        if (includeIdentity)
            sql += "[ID] int not null Identity(1,1) primary key,\n";

        foreach (KeyValuePair<string, Type> info in schema)
        {
            sql += "[" + info.Key + "] " + SQLGetType(info.Value) + ",\n";
        }

        sql = sql.TrimEnd(new char[] { ',', '\n' }) + "\n";

        return sql + ")";
    }

Upvotes: 0

Related Questions