如何确保全球临时表坚持

时间:2016-11-11 22:08:12

标签: c# sql .net sql-server tsql

foreach 语句中,将会调用大约5个不同的存储过程,这些存储过程都依赖于相同的全局临时表。

因为我们可能同时运行此方法的100个不同线程,所以如何确保:

如何确保全局临时表仅在此方法的持续时间内使用** Updatetroup ?**

private DataTable Updatetroup(ProductCatalogSyncData syncDataModel, string connectionString)
{
    var ds = syncDataModel.SyncDataSet;
    var troupCommand = new SqlCommand();
    var troupConnection = new SqlConnection(connectionString);
    var dtResults = new DataTable("BillingIds");
    var syncConfig = syncDataModel.XDataMapping;

    string EntityName;
    //inside of this foreach statement is where i am calling multiple stored procedures that need to make use of the same global temporary table
    foreach (DataTable dt in ds.Tables)
    {
        EntityName =
            StringDefaultIfNull(
                syncConfig.Root.XPathSelectElement("./entity[@name='" + dt.TableName + "']"),
                "troupTableName").Substring(3);

        troupCommand.CommandType = CommandType.StoredProcedure;
        troupCommand.CommandText = "troup720_P_" + EntityName + "Sync";

        var entityNameParam = new SqlParameter("@EntityName", dt.TableName);
        troupCommand.Parameters.Clear();
        troupCommand.Parameters.Add(entityNameParam);
        var tblParam = new SqlParameter("@O720_" + EntityName, SqlDbType.Structured);
        tblParam.Value = dt;
        troupCommand.Parameters.Add(tblParam);

        troupCommand.Connection = troupConnection;

        try
        {

            // Define the data adapter and fill the dataset 
            using (var da = new SqlDataAdapter(troupCommand))
            {
                da.Fill(dtResults);
            }
        }
        finally
        {
            if (troupConnection.State == ConnectionState.Open)
                troupConnection.Close();
        }
    }
    return dtResults;
}

假设这个方法被100个不同的线程调用,我该如何巧妙地确保每个线程只获得自己的全局临时表?

0 个答案:

没有答案