代码改变世界

DataTable 2 Sql Table

2013-03-16 21:50  迷路中的路人甲  阅读(240)  评论(0编辑  收藏  举报
        public void ExecuteDataTable2Table(DataTable dt,string tbName)
        {
            SqlBulkCopy sbc = new SqlBulkCopy(conn);
            sbc.DestinationTableName = tbName;
            DataTable dtFields = this.ExecuteDataTable("select * from dictionary_V where pcode='" + tbName + "_Fields'");
            string guid = Guid.NewGuid().ToString();
            dt.Columns.Add(new DataColumn("GUIDStr"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["GUIDStr"] = guid;
            }
            for (int i = 0; i < dtFields.Rows.Count; i++)
            {
                sbc.ColumnMappings.Add(new SqlBulkCopyColumnMapping(dtFields.Rows[i]["name"].ToString(), dtFields.Rows[i]["code"].ToString()));   
            }

            sbc.ColumnMappings.Add(new SqlBulkCopyColumnMapping("GUIDStr", "GUID"));
            sbc.WriteToServer(dt);
        }