Объединить sql в хранимую процедуру для лучшей производительности - PullRequest
0 голосов
/ 24 июня 2018

У меня все еще есть реальная проблема производительности в списке из наших 38 тысяч записей, и мне нужно сопоставить их с другой таблицей для экспорта. Я думаю перенести ее в сохраненный процесс, но все еще беспокоюсь о том, какова будет производительность. Код работает, но его выполнение занимает очень много времени, и он хочет превратить его в хранимый процесс.

private List<TradeItemsExport> MapTradeItems(List<TradeItems> tradeItem)
{
    List<TradeItemsExport> retList = new List<TradeItemsExport>();

    try
    {
        var StockImport = new StockItemExported();

        List<StandardLookUpList> _AnalsisCodes = GetAnayalsisCodesForExportCode();

        StandardLookUpList sport = new StandardLookUpList();
        StandardLookUpList gender = new StandardLookUpList();
        StandardLookUpList colour = new StandardLookUpList();
        StandardLookUpList Size = new StandardLookUpList();
        StandardLookUpList categorycode = new StandardLookUpList();
        StandardLookUpList categorydesc = new StandardLookUpList();
        StandardLookUpList subcategorycode = new StandardLookUpList();
        StandardLookUpList subcategorydesc = new StandardLookUpList();

        StandardLookUpList brandcode = new StandardLookUpList();
        StandardLookUpList branddesc = new StandardLookUpList();

        using (var db = new liveEntities1())
        {
            int count = 0;

            foreach (var item in tradeItem)
            {
                count++;
                bool hasprocessed = HasTransactionBeenProcessed(item.ItemCode);

                if (hasprocessed == false)
                {
                    var codesForThisItem = _AnalsisCodes.Where(w => w.ItemCode == item.ItemCode);

                    if (codesForThisItem.Any())
                    {
                        sport = codesForThisItem.FirstOrDefault(x => x.code == Constants.Sport);

                        gender = codesForThisItem.FirstOrDefault(x => x.code == Constants.Gender);
                        colour = codesForThisItem.FirstOrDefault(x => x.code == Constants.Colour);
                        Size = codesForThisItem.FirstOrDefault(x => x.code == Constants.Size);
                        categorycode = codesForThisItem.FirstOrDefault(x => x.code == Constants.Category);
                        categorydesc = codesForThisItem.FirstOrDefault(x => x.code == Constants.Category);

                        subcategorycode = codesForThisItem.FirstOrDefault(x => x.code == Constants.SubCategory);
                        subcategorydesc = codesForThisItem.FirstOrDefault(x => x.code == Constants.SubCategory);
                        brandcode = codesForThisItem.FirstOrDefault(x => x.code == Constants.Brand);

                        string SportCodeValue, SportDescValue;

                        if (sport == null)
                        {
                            SportCodeValue = "";
                            SportDescValue = "";
                        }
                        else
                        {
                            SportCodeValue = sport.LookupValue.ToString();
                            SportDescValue = sport.description;
                        }

                        string GenderCodeValue, GenderCodeDesc;

                        if (gender == null)
                        {
                            GenderCodeValue = "";
                            GenderCodeDesc = "";
                        }
                        else
                        {
                            GenderCodeValue = gender.LookupValue.ToString();
                            GenderCodeDesc = gender.description;
                        }

                        string ColourCodeValue, ColourCodeDesc;

                        if (colour == null)
                        {
                            ColourCodeValue = "";
                            ColourCodeDesc = "";
                        }
                        else
                        {
                            ColourCodeValue = colour.LookupValue.ToString();
                            ColourCodeDesc = colour.description;
                        }

                        string SizeCodeValue, SizeCodeDesc;

                        if (Size == null)
                        {
                            SizeCodeValue = "";
                            SizeCodeDesc = "";
                        }
                        else
                        {
                            SizeCodeValue = Size.LookupValue.ToString();
                            SizeCodeDesc = Size.description;
                        }

                        string CategoryCodeValue, CategoryCodeDesc;

                        if (categorycode == null)
                        {
                            CategoryCodeValue = "";
                            CategoryCodeDesc = "";
                        }
                        else
                        {
                            CategoryCodeValue = categorycode.LookupValue.ToString();
                            CategoryCodeDesc = categorydesc.description;
                        }

                        string subcategorycodevalue, subcategorycodedesc;

                        if (categorycode == null)
                        {
                            subcategorycodevalue = "";
                            subcategorycodedesc = "";
                        }
                        else
                        {
                            subcategorycodevalue = subcategorycode.LookupValue.ToString();
                            subcategorycodedesc = subcategorydesc.description;
                        }

                        string brandcodecodevalue, brandcodecodedesc;

                        if (brandcode == null)
                        {
                            brandcodecodevalue = "";
                            brandcodecodedesc = "";
                        }
                        else
                        {
                            brandcodecodevalue = brandcode.LookupValue.ToString();
                            brandcodecodedesc = brandcode.description;
                        }

                        retList.Add(new TradeItemsExport()
                        {
                            ItemCode = item.ItemCode,
                            BarCode = item.BarCode,
                            Description = item.Description,
                            SupplierCode = item.SupplierCode,
                            SupplierStockCode = item.SupplierStockCode,
                            Product_Group_Code = "",
                            Product_Group_Desc = "",
                            SportCode = SportCodeValue,
                            SportDesc = SportDescValue,
                            GenderCode = GenderCodeValue,
                            GenderDesc = GenderCodeDesc,
                            ColourCode = ColourCodeValue,
                            ColourDesc = ColourCodeDesc,
                            SizeCode = SizeCodeValue,
                            SizeDesc = SizeCodeDesc,
                            CategoryCode = CategoryCodeValue,
                            CategoryDesc = CategoryCodeDesc,
                            subcategorycode = subcategorycodevalue,
                            subcategorydesc = subcategorycodedesc,
                            BrandsCode = brandcodecodevalue,
                            BrandsDesc = brandcodecodedesc,
                            Vat = item.Vat,
                            GrossWeight = item.Weight,
                            CommodityCode = item.CommodityCode,
                            price_exVAT = item.price_exVAT,
                            price_incVAT = item.price_incVAT,
                            currentprice_exVAT = item.currentprice_exVAT,
                            currentprice_incVAT = item.currentprice_incVAT,
                            creation_date = item.creation_date,
                            Inactive_date = item.Inactive_date,
                            status = 1
                        });

                        Console.Write(String.Format("Exporting stock item {0} with a current record of {1} of {2} \n", item.ItemCode.ToString(), count.ToString(), tradeItem.Count.ToString()));
                        EFStockItemExported _newStockitemImported = new EFStockItemExported();

                        _newStockitemImported.StockItemID = item.ItemCode;
                        _newStockitemImported.IsProcessed = true;
                        _newStockitemImported.DateImported = DateTime.Now;

                        db.EFStockItemExporteds.Add(_newStockitemImported);
                        db.SaveChanges();
                    }
                    else
                    {
                        Console.Write(string.Format("Stock Items to Process  [{0}] check the  table and remove entry if wish to re process.", 0));
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
    }

    return retList;
}

Моя проблема в том, что для вычисления результатов требуется около 30 минут, что очень медленно.

Это sql, который я делаю, и это точка зрения, которую я передаю.

SELECT        
    dbo.PLSupplierAccount.SupplierAccountNumber, dbo.PLSupplierAccount.PLSupplierAccountID, dbo.PLSupplierAccount.SupplierAccountName, 
    dbo.PLSupplierAccount.SYSCurrencyID, dbo.PLSupplierAccount.MainTelephoneAreaCode, dbo.PLSupplierAccount.MainTelephoneCountryCode, 
    dbo.PLSupplierAccount.MainTelephoneSubscriberNumber, dbo.PLSupplierAccount.MainFaxCountryCode, dbo.PLSupplierAccount.MainFaxSubscriberNumber, 
    dbo.PLSupplierAccount.MainFaxAreaCode, dbo.PLSupplierContact.ContactName, dbo.PLSupplierContact.Description, dbo.PLSupplierContact.FirstName, 
    dbo.PLSupplierContact.MiddleName, dbo.PLSupplierContact.LastName, loc.AddressLine1, loc.AddressLine2, loc.AddressLine3, loc.AddressLine4, loc.PostCode, 
    loc.City, loc.County, 
    CAST(CASE WHEN loc.Country = 'Ireland' THEN 'IRL' 
              WHEN loc.Country = 'Great Britain' 
              THEN 'GBR' 
              ELSE 'ERR' 
         END AS nvarchar(3)) AS Country, 
    dbo.SYSCurrency.SYSCurrencyISOCodeID, dbo.SYSCurrency.SYSExchangeRateTypeID, dbo.SYSCurrency.Name AS CurrencyDescription, 
    dbo.SYSCurrency.Symbol AS CurrencySymbol
FROM
    dbo.PLSupplierAccount 
INNER JOIN
    dbo.PLSupplierContact ON dbo.PLSupplierAccount.PLSupplierAccountID = dbo.PLSupplierContact.PLSupplierAccountID 
INNER JOIN
    dbo.PLSupplierLocation AS loc ON dbo.PLSupplierAccount.PLSupplierAccountID = loc.PLSupplierAccountID 
                                  AND dbo.PLSupplierContact.PLSupplierLocationID = loc.PLSupplierLocationID 
INNER JOIN
    dbo.SYSCurrency ON dbo.PLSupplierAccount.SYSCurrencyID = dbo.SYSCurrency.SYSCurrencyID

Мой вопрос: как бы я изменил вышеприведенное, чтобы включить подзапрос, который выполнял бы то же самое, что и эта функция, описанная выше.

Запрос поиска кодов, который снова является другим представлением, приведен ниже.

SELECT        
    dbo.StockItem.ItemID, dbo.StockItem.Code, dbo.StockItem.Name, dbo.StockItemSearchCatVal.SearchValueID, dbo.SearchValue.Name AS Expr1, 
    dbo.SearchCategory.Name AS Expr2
FROM
    dbo.SearchCategory 
INNER JOIN
    dbo.SearchValue ON dbo.SearchCategory.SearchCategoryID = dbo.SearchValue.SearchCategoryID 
INNER JOIN
    dbo.StockItemSearchCatVal ON dbo.SearchCategory.SearchCategoryID = dbo.StockItemSearchCatVal.SearchCategoryID 
                              AND dbo.SearchValue.SearchValueID = dbo.StockItemSearchCatVal.SearchValueID 
INNER JOIN
    dbo.StockItem ON dbo.StockItemSearchCatVal.ItemID = dbo.StockItem.ItemID

Я просто чувствую, что получил бы больше пользы, изменив это на подзапрос, так что я просто возвращаю результаты в .net. Я использую библиотеку filehelpers для вывода набора результатов MapTradeItems в csv, так что я могу сделать больше вещей, которые я могу сделать. лучше на сервере.

Obv. Мне понадобится какая-то временная таблица для циклического просмотра результатов, но как быстро это будет на сервере sql по сравнению с .net для каждого цикла.

Это класс Poco, который я должен воспроизвести в CSV.

[DelimitedRecord(",")]
public class TradeItemsExport
{
    [FieldOrder(1)]
    public string ItemCode { get; set; }
    [FieldOrder(2)]
    public string BarCode { get; set; }
    [FieldOrder(3)]
    public string Description { get; set; }
    [FieldOrder(4)]
    public string SupplierCode { get; set; }
    [FieldOrder(5)]
    public string SupplierStockCode { get; set; }
    [FieldOrder(6)]
    public string Product_Group_Code { get; set; }
    [FieldOrder(7)]
    public string Product_Group_Desc { get; set; }
    [FieldOrder(8)]
    public string SportCode { get; set; }
    [FieldOrder(9)]
    public string SportDesc { get; set; }
    [FieldOrder(10)]
    public string GenderCode { get; set; }
    [FieldOrder(11)]
    public string GenderDesc { get; set; }
    [FieldOrder(12)]

    public string ColourCode { get; set; }
    [FieldOrder(13)]
    public string ColourDesc { get; set; }
    [FieldOrder(14)]
    public string SizeCode { get; set; }
    [FieldOrder(15)]
    public string SizeDesc { get; set; }
    [FieldOrder(16)]
    public string CategoryCode { get; set; }
    [FieldOrder(17)]
    public string CategoryDesc { get; set; }
    [FieldOrder(18)]
    public string subcategorycode { get; set; }
    [FieldOrder(19)]
    public string subcategorydesc { get; set; }
    [FieldOrder(20)]
    public string BrandsCode { get; set; }
    [FieldOrder(21)]
    public string BrandsDesc { get; set; }
    [FieldOrder(22)]

    public Nullable<short> Vat { get; set; }
    [FieldOrder(23)]
    public decimal GrossWeight { get; set; }
    [FieldOrder(24)]
    public string CommodityCode { get; set; }
    [FieldOrder(25)]
    public decimal price_exVAT { get; set; }
    [FieldOrder(26)]
    public Nullable<decimal> price_incVAT { get; set; }
    [FieldOrder(27)]
    public Nullable<decimal> currentprice_exVAT { get; set; }
    [FieldOrder(28)]
    public Nullable<decimal> currentprice_incVAT { get; set; }
    [FieldOrder(29)]
    public System.DateTime creation_date { get; set; }
    [FieldOrder(30)]
    public Nullable<System.DateTime> Inactive_date { get; set; }
    [FieldOrder(31)]
    public int status { get; set; }
   }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...