iT邦幫忙

1

[MSDN] SqlBulk & SqlDataReader,單一大量複製作業 (非交易)

[MSDN] SqlBulk & SqlDataReader,單一大量複製作業 (非交易)

執行 SQL Server 大量複製作業的最簡單方法是:針對資料庫執行單一作業。
根據預設,會以"隔離作業"執行大量複製作業:複製作業會以 "非"交易性方式執行,且沒有復原的機會。

詳見原文 http://www.dotblogs.com.tw/mis2000lab/archive/2014/11/17/sqlbulk_20141117.aspx
下面的範例,使用 SqlDataReader

想要把 Product資料表

大量複製到另一個資料表(名為 目的地(資料表名稱))

我把程式碼簡化過

using (SqlConnection Conn = new SqlConnection("DB連結字串"))
{
            Conn.Open();

            // Get data from the source table as a SqlDataReader.  來源資料表
            SqlCommand com = new SqlCommand("SELECT A, B FROM Product;", Conn);
            SqlDataReader dr = com.ExecuteReader();


            // Open the destination connection. In the real world you would 
            // not use SqlBulkCopy to move data from one table to the other 
            // in the same database. This is for demonstration purposes only.
            using (SqlConnection destinationConnection = new SqlConnection("DB連結字串"))
            {
                destinationConnection.Open();

                // Set up the bulk copy object. 
                // Note that the column positions in the source data reader match the column positions in 
                // the destination table so there is no need to map columns.  若要改成「交易」,請參閱本文最後說明。
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
                {
                    bulkCopy.DestinationTableName = "目的地(資料表名稱)";

                    try   {
                        // Write from the source to the destination.
                                                    //  將已提供之 IDataReader中的所有資料列複製到 SqlBulkCopy物件之 DestinationTableName屬性所指定的目的資料表。
                                                    //  參考資料  http://msdn.microsoft.com/zh-tw/library/434atets(v=vs.110).aspx

                        bulkCopy.WriteToServer(dr);

                    }
                    catch (Exception ex)   {
                        // 例外狀況
                    }
                    finally   {
                        // 關閉連線、釋放資源
                        dr.Close();
                    }
                }

            }
        }

詳見原文 http://www.dotblogs.com.tw/mis2000lab/archive/2014/11/17/sqlbulk_20141117.aspx


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
賽門
iT邦超人 1 級 ‧ 2014-11-17 14:27:51

基本上,我不會建議用這種方式來維護資料庫。
如果有大量複製的情形,還是直接在SSMS中用複製功能來進行比較妥當。
用程式來大量複製資料,會造成資料庫Perofrmance不佳的問題。
如果還有資料格式轉換,用SSIS來處理比較好。

換句話說,歸DBA作的事,譞是讓DBA來完成。
不要用程式來處理"非"交易類別的Transactions。

0
mis2000lab
iT邦好手 1 級 ‧ 2014-11-17 17:09:20

大師說的沒錯,
每日定時的工作、備份、資料大量的轉移,最好給DB處理,不要寫程式自己硬幹(Hard Coding)喔

這是給使用者上傳Excel檔案,批次處理一些資料用的範例

okra iT邦研究生 3 級 ‧ 2014-11-17 23:13:39 檢舉

mis2000lab提到:
"非"交易性方式

蓋被純聊天是"非"交易性方式?偷笑

我要留言

立即登入留言