sql 多線程


1、codeproject上面一個多線程執行sql的庫。

     開發中常常要執行一些耗時的數據操作,比如update、insert、bulk insert、index creation,

     若順序執行,則操作總時間是每個單獨sql的時間之和  為了加快速度,采用線程池異步執行的做法,比如要要create 10個表以及加數據,則可以開10個線程去分別執

 codeproject上庫源碼地址 http://www.codeproject.com/Articles/29356/Asynchronous-T-SQL-Execution-Without-Service-Broke
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SqlClrLib.Model;

namespace ExampleTransaction
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //開發中常常要執行一些耗時的數據操作,比如update、insert、bulk insert、index creation,
            //若順序執行,則操作總時間是每個單獨sql的時間之和,
            //為了加快速度,引入異步執行的做法,比如要要create 10個表以及加數據,則可以開10個線程去分別執行
        }

        [Microsoft.SqlServer.Server.SqlProcedure]
        public static int SaveWarehouseFinalData(Guid fileDefinitionId)
        {
            Console.WriteLine("Start");
            StoredProcedures.Parallel_Declare(new SqlString("Parallel SaveWarehouseFinalData"));
            //Console.WriteLine("Database connection is ... {0}", StoredProcedures.Block.ConnectionString);
            //Console.WriteLine("Max threads count is ... {0}", StoredProcedures.Block.MaxThreads);
            ////ParallelProcedures.Block.IsTransactional = true;
            ////ParallelProcedures.Parallel_UseTransaction("Serializable");
            //依次將存儲過程加入到線程池
            StoredProcedures.Parallel_AddSql(new SqlString("usp_WarehouseImportSaveToEAV"), new SqlChars(string.Format("usp_WarehouseImportSaveToEAV '{0}'", fileDefinitionId)));
            StoredProcedures.Parallel_AddSql(new SqlString("usp_WarehouseImportSaveToAdminHistory"), new SqlChars(string.Format("usp_WarehouseImportSaveToAdminHistory '{0}'", fileDefinitionId)));
            StoredProcedures.Parallel_AddSql(new SqlString("usp_WarehouseImportSaveToValResult"), new SqlChars(string.Format("usp_WarehouseImportSaveToValResult '{0}'", fileDefinitionId)));
            //執行save操作(此處用的事務,如果不成功會回滾)
            int failedCount = StoredProcedures.Parallel_Execute();
            //Console.WriteLine("Failed count is ... {0}", failedCount);
            ResultItem[] resultItems = (ResultItem[])StoredProcedures.Parallel_GetExecutionResult();
            foreach (ResultItem r in resultItems)
            {
                //Console.WriteLine(r.ToString());
            }
            //Console.WriteLine("End...");
           
            return failedCount;
        }

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM