SqlBulkCopy的使用
2012-11-22 17:12 Carl Xing 阅读(245) 评论(0) 编辑 收藏 举报将datatable 中的表写入一张临时表。注意:临时表只存在与一个连接中,只有当前连接可以操作临时表,当连接关闭,临时表消失。
DataTable dt = new DataTable(); dt.Columns.Add("col", typeof(int)); for (int i = 10000; i < 100000; i++) { dt.Rows.Add(new object[] { i }); } string connStr = ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString; using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); SqlCommand cmdTemp = new SqlCommand("select -1 col into #bulkInt", conn); cmdTemp.ExecuteNonQuery(); using (System.Data.SqlClient.SqlBulkCopy bulk= new System.Data.SqlClient.SqlBulkCopy(conn)) { bulk.DestinationTableName = "#bulkInt"; try { bulk.WriteToServer(dt); } catch { } } SqlCommand cmd = new SqlCommand("select count(*) from #bulkInt", conn); int rows = Convert.ToInt32(cmd.ExecuteScalar()); Response.Write(rows.ToString()); }