开发者

Creating database schema from DataTable

开发者 https://www.devze.com 2023-03-19 18:47 出处:网络
Is it possible, without writing any SQL or using any 3rd party libraries to create a data开发者_JAVA百科base schema from several ADO.NET DataTables?Not sure how \"not sql\" this is, but you can use SQ

Is it possible, without writing any SQL or using any 3rd party libraries to create a data开发者_JAVA百科base schema from several ADO.NET DataTables?


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


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 + ")";
    }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消