DataTable插入數據,刪除重複記錄

之前有篇文章簡單講了下批量插入數據的方法,但是沒有考慮到有重複值的情況,SqlBulkCopy也沒有提供相關方法。

自己寫了一個方法,傳入兩個Table(目標Table和源Table)

 /// <summary>
        /// 刪除重複行
        /// </summary>
        /// <param name="tableTarget">目標table</param>
        /// <param name="tableSource">源table</param>
        /// <returns></returns>
        public int DeleteReptRows(DataTable tableTarget, DataTable tableSource)
        {
          <span style="color:#3366FF;">  DataColumn[] keys = new DataColumn[1];
            keys[0] = tableTarget.Columns[0];
            tableTarget.PrimaryKey = keys;//手動設置第一列爲主鍵</span>
            int count = tableSource.Rows.Count;
            int reptCount = 0;
            for (int i = 0; i < count; i++)
            {
                if (tableTarget.Rows.Contains(tableSource.Rows[i].ItemArray[0]))//包含重複報稅編號
                {
                    reptCount++;
                    <span style="color:#FF6600;">tableSource.Rows[i].Delete();//remove不行</span>
                }
            }
            return reptCount;

        }
藍色部分是手動爲目標Table添加一個主鍵,即使在數據庫裏設置了主鍵也不行,不然會報錯

異常詳細信息:System.Data.MissingPrimaryKeyException:表沒有主鍵

參考:http://blog.csdn.net/soarandy/article/details/4380158

紅色那裏,用DataRow的Remove不行,因爲即使Remove了,也只是記錄一個行狀態爲Delete,數據依然存在。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章