UPDATE QUERY TAKING MORE TIME - sql-server

UPDATE QUERY TAKING MORE TIME. IS THERE ANY OTHER WAY TO WRITE BELOW QUERY WITHOUT TOP 1? LIKE USING RANK OR ROWNUMBER FUNCTIONS?
SELECT proddiv,
prodstl,
prodcode,
lablcode,
proddim,
proddiv AS PRD_DIV,
prodstl AS PRD_PRODSTL,
prodcode AS PRDCOLOR,
label_code AS PRDlbl,
proddim AS par_dim,
0 AS low_level,
0 AS smuh_pkey,
IDENTITY(int) AS prdkey,
list_price
INTO #brandsdata
FROM products WITH (nolock)
DECLARE #Max INT = 30,
#x INT = 0
WHILE ( #x < 30 )
BEGIN
UPDATE t
SET smuh_pkey = (SELECT TOP 1 prdkey
FROM customers WITH (nolock)
WHERE ( proddiv = ''
OR proddiv = t.proddiv )
AND ( prodstl = ''
OR prodstl = t.prodstl )
AND ( prodcode = ''
OR prodcode = t.prodcode )
AND ( lablcode = ''
OR lablcode = t.lablcode )
AND ( proddim = ''
OR proddim = t.proddim )
AND prod_type = ''
AND active_ok = 'Y'
ORDER BY brand_name,
brand_type DESC)
FROM #brandsdata t
WHERE smuh_pkey = 0
AND low_level = #x
SET #x = #x + 1
END
THANKS IN ADVANCE.

Try something like this.
;with c as (
select c.prdKey, c.proddiv, c.prodstl, c.prodcode, c.lablcode, c.proddim,
ROW_NUMBER() over (
partition by c.proddiv, c.prodstl, c.prodcode, c.lablcode, c.proddim
order by c.brand_name, c.brand_type DESC) rn
from customers c
where prod_type = '' and
active_ok = 'Y'
)
update t
set smuh_pkey = c.prdKey
from #brandsdata t
inner join c
on ( c.proddiv = '' OR c.proddiv = t.proddiv )
AND ( c.prodstl = '' OR c.prodstl = t.prodstl )
AND ( c.prodcode = '' OR c.prodcode = t.prodcode )
AND ( c.lablcode = '' OR c.lablcode = t.lablcode )
AND ( c.proddim = '' OR c.proddim = t.proddim )
where c.rn = 1
I think it will not be enough for 100% of the cases, because if you can have multiple combinations of empty string with not empty, you could get different results.
then you could fine tune

Related

Is there any tool to convert stored procedure SQL to string with EscapeConcatenation?

I have over 50 stored procedures that I need to convert so that I can use a dynamic whereclause in them. My select statemement looks like this in SQL. I need to change this to a varchar(max) string and use Execute(#SQL) or sp_executesql #SQL
Is there any tool online or purchased that can convert this where clause into the proper string format with the correct escape sequences for the #Parameters?
;WITH TempResult AS(SELECT
DataDt
,EffDt
,SettlementDt
,BankId
,SeqNum
,DeleteFlag
,LoanNum
,BondLoanSaleType
,PurchaseProceedsAmt
,SettledPrinBal
,IntRecMiscAmt
,BuydownCashClearingAmt
,ARClearingDAPAmt
,ARCashClearingAmt
,ARSuspenseAmt
,ImpoundsSoldLoansAmt
,BondCommitmentFeesAmt
,SRPAmt
,OtherFeeAmt
,ActiveFlagBit = case ActiveFlagBit when 1 then 1 else 0 end
,UploadByCfcUserId
,UploadDtTm
,UploadedFileName
,ApprovedFlagBit = case ApprovedFlagBit when 1 then 1 else 0 end
,ApproveRejectByCfcUserId
,ApproveRejectDtTm
,ApprovalTaskId
,ArchiveDtTm
FROM guiUploadBondLoanSales u (nolock)
WHERE
(#LoanList.exist('/NewDataSet/Table1') = 0 or LoanNum in (select LoanNum from #tmpLoan))
and (#DataDtTo = '01/01/1900' or DataDt between #DataDtFrom and #DataDtTo)
and (#SettlementDtTo = '01/01/1900' or SettlementDt between #SettlementDtFrom and #SettlementDtTo)
and (#ShowOnlyLatest = 0 or (ActiveFlagBit = 1 and ApprovedFlagBit = 1 and u.DataDt =
(select max(DataDt) from guiUploadBondLoanSales u1 (nolock)
where u1.LoanNum = u.LoanNum and u1.ActiveFlagBit = 1 and u1.ApprovedFlagBit = 1)))
and (#TaskId = 0 or ApprovalTaskId = #TaskId)
and (#FileName = '' or UploadedFileName like '%' + #FileName + '%')
and (#UploadedByUsers.exist('/NewDataSet/Table1') = 0 or UploadByCfcUserId in (select UploadedByUsers from #UploadedByUsers))
and (#ApprovedByUsers.exist('/NewDataSet/Table1') = 0 or ApproveRejectByCfcUserId in (select ApprovedByUsers from #ApprovedByUsers))
and (#UploadDtTo = '01/01/1900' or UploadDtTm between #UploadDtFrom and #UploadDtTo)
and (#ApprovedDtTo = '01/01/1900' or ApproveRejectDtTm between #ApprovedDtFrom and #ApprovedDtTo)
and (#HideArchive = 0 or u.ArchiveDtTm = '1/1/1900' )
), TempCount AS ( SELECT COUNT(*) AS MaxRows FROM TempResult) SELECT *, TempCount.MaxRows FROM TempResult, TempCount ORDER BY TempResult.UploadDtTm OFFSET #OFFSET ROWS FETCH NEXT #FETCH ROWS ONLY OPTION(RECOMPILE)

sp_executesql not returning results in the same way as normal query

I saw in SQL when executing a query using sp_executesql it takes MINUTES to process it, while i run the same query in a normal way declaring the parameters runs in 2 seconds.
sp_executesql
EXEC Sp_executesql
N'SELECT TOP (27) [ARSalesPrice].[RecordID], [ARSalesPrice].[PriceType], [ARSalesPrice].[CustPriceClassID], [ARSalesPrice].[CustomerID], [ARSalesPrice].[InventoryID], [ARSalesPrice].[CuryID], [ARSalesPrice].[UOM], [ARSalesPrice].[IsPromotionalPrice], [ARSalesPrice].[EffectiveDate], [ARSalesPrice].[SalesPrice], [ARSalesPrice].[TaxID], [ARSalesPrice].[BreakQty], [ARSalesPrice].[ExpirationDate], [ARSalesPrice].[tstamp], [ARSalesPrice].[CreatedByID], [ARSalesPrice].[CreatedByScreenID], [ARSalesPrice].[CreatedDateTime], [ARSalesPrice].[LastModifiedByID], [ARSalesPrice].[LastModifiedByScreenID], [ARSalesPrice].[LastModifiedDateTime], [InventoryItem].[InventoryID], [InventoryItem].[InventoryCD], [InventoryItem].[Descr], [InventoryItem].[ItemClassID], [InventoryItem].[ItemStatus], [InventoryItem].[ItemType], [InventoryItem].[ValMethod], [InventoryItem].[TaxCategoryID], [InventoryItem].[BaseUnit], [InventoryItem].[SalesUnit], [InventoryItem].[PurchaseUnit], [InventoryItem].[Commisionable], [InventoryItem].[ReasonCodeSubID], [InventoryItem].[SalesAcctID], [InventoryItem].[SalesSubID], [InventoryItem].[InvtAcctID], [InventoryItem].[InvtSubID], [InventoryItem].[COGSAcctID], [InventoryItem].[COGSSubID], [InventoryItem].[DiscAcctID], [InventoryItem].[DiscSubID], [InventoryItem].[StdCstRevAcctID], [InventoryItem].[StdCstRevSubID], [InventoryItem].[StdCstVarAcctID], [InventoryItem].[StdCstVarSubID], [InventoryItem].[PPVAcctID], [InventoryItem].[PPVSubID], [InventoryItem].[POAccrualAcctID], [InventoryItem].[POAccrualSubID], [InventoryItem].[LCVarianceAcctID], [InventoryItem].[LCVarianceSubID], [InventoryItem].[DeferralAcctID], [InventoryItem].[DeferralSubID], [InventoryItem].[LastSiteID], [InventoryItem].[LastStdCost], [InventoryItem].[PendingStdCost], [InventoryItem].[PendingStdCostDate], [InventoryItem].[StdCost], [InventoryItem].[StdCostDate], [InventoryItem].[BasePrice], [InventoryItem].[BaseWeight], [InventoryItem].[BaseVolume], [InventoryItem].[BaseItemWeight], [InventoryItem].[BaseItemVolume], [InventoryItem].[WeightUOM], [InventoryItem].[VolumeUOM], [InventoryItem].[PackSeparately], [InventoryItem].[PackageOption], [InventoryItem].[PreferredVendorID], [InventoryItem].[PreferredVendorLocationID], [InventoryItem].[DefaultSubItemID], [InventoryItem].[DefaultSubItemOnEntry], [InventoryItem].[DfltSiteID], [InventoryItem].[DfltShipLocationID], [InventoryItem].[DfltReceiptLocationID], [InventoryItem].[ProductWorkgroupID], [InventoryItem].[ProductManagerID], [InventoryItem].[PriceWorkgroupID], [InventoryItem].[PriceManagerID], [InventoryItem].[StkItem], (SELECT TOP (1) ([INItemClass].[NegQty]) FROM INItemClass INItemClass WHERE (INItemClass.CompanyID = 3) AND INItemClass.DeletedDatabaseRecord = 0 AND ( [INItemClass].[ItemClassID] = [InventoryItem].[ItemClassID]) ORDER BY [INItemClass].[NegQty]), [InventoryItem].[LotSerClassID], [InventoryItem].[LotSerNumVal], [InventoryItem].[PostClassID], [InventoryItem].[DeferredCode], [InventoryItem].[DefaultTerm], [InventoryItem].[DefaultTermUOM], [InventoryItem].[PriceClassID], [InventoryItem].[IsSplitted], [InventoryItem].[UseParentSubID], [InventoryItem].[KitItem], [InventoryItem].[MinGrossProfitPct], [InventoryItem].[NonStockReceipt], [InventoryItem].[NonStockShip], [InventoryItem].[CompletePOLine], [InventoryItem].[ABCCodeID], [InventoryItem].[ABCCodeIsFixed], [InventoryItem].[MovementClassID], [InventoryItem].[MovementClassIsFixed], [InventoryItem].[MarkupPct], [InventoryItem].[RecPrice], [InventoryItem].[ImageUrl], [InventoryItem].[NoteID], NULL, NULL, NULL, [InventoryItem].[CreatedByID], [InventoryItem].[CreatedByScreenID], [InventoryItem].[CreatedDateTime], [InventoryItem].[LastModifiedByID], [InventoryItem].[LastModifiedByScreenID], [InventoryItem].[LastModifiedDateTime], [InventoryItem].[GroupMask], [InventoryItem].[CycleID], [InventoryItem].[tstamp], [InventoryItem].[IsRUTROTDeductible], [InventoryItem].[Body], [InventoryItem].[RUTROTType], [InventoryItem].[RUTROTItemType], [InventoryItem].[RUTROTWorkType], ( ( ( [InventoryItem].[UsrPartNumber] + N'' : '') + [InventoryItem].[UsrBrand])), [InventoryItem].[UsrSISupersededBy], [InventoryItem].[UsrPartNumber], [InventoryItem].[UsrBrand], [InventoryItem].[UsrFrgnName], [InventoryItem].[UsrSIPackSize], [InventoryItem].[UsrSICountryOfOrigin], [InventoryItem].[UsrSILength], [InventoryItem].[UsrSIWidth], [InventoryItem].[UsrSIHeight], [InventoryItem].[UsrSIAssocPartNumber], [InventoryItem].[UsrSISpecs], [InventoryItem].[UsrSIFactoryPartnumber], [InventoryItem].[UsrSIItemMovementClass], (SELECT TOP (1) ([INItemClass].[UsrSIMainGroup]) FROM INItemClass INItemClass WHERE (INItemClass.CompanyID = 3) AND INItemClass.DeletedDatabaseRecord = 0 AND ( [INItemClass].[ItemClassID] = [InventoryItem].[ItemClassID]) ORDER BY [INItemClass].[UsrSIMainGroup]), [InventoryItem].[UsrSIPrintDescr] FROM ARSalesPrice ARSalesPrice LEFT JOIN InventoryItem InventoryItem ON (InventoryItem.CompanyID = 3) AND InventoryItem.DeletedDatabaseRecord = 0 AND ( [InventoryItem].[InventoryID] = [ARSalesPrice].[InventoryID]) WHERE (ARSalesPrice.CompanyID = 3) AND [InventoryItem].[ItemStatus] <> N''IN'' AND [InventoryItem].[ItemStatus] <> N''DE'' AND ( #P0 = N''A'' OR [ARSalesPrice].[PriceType] = #P1) AND ( [ARSalesPrice].[CustomerID] = #P2 OR [ARSalesPrice].[CustPriceClassID] = #P3 OR #P4 IS NULL) AND ( [ARSalesPrice].[InventoryID] = #P5 OR #P6 IS NULL) AND ( ( ( [ARSalesPrice].[EffectiveDate] <= #P7 OR [ARSalesPrice].[EffectiveDate] IS NULL) AND ( [ARSalesPrice].[ExpirationDate] >= #P8 OR [ARSalesPrice].[ExpirationDate] IS NULL)) OR #P9 IS NULL) AND ( #P10 IS NULL OR #P11 = [InventoryItem].[ItemClassID]) AND ( #P12 IS NULL OR #P13 = [InventoryItem].[PriceClassID]) AND ( #P14 IS NULL OR #P15 = [InventoryItem].[PriceManagerID]) AND ( #P16 = CONVERT(BIT, 0) OR [InventoryItem].[PriceWorkgroupID] IN (SELECT EPCompanyTreeMember.workGroupID FROM EPCompanyTreeMember EPCompanyTreeMember WHERE (EPCompanyTreeMember.CompanyID = 3) AND EPCompanyTreeMember.userID= CONVERT(UNIQUEIDENTIFIER, ''b5344897-037e-4d58-b5c3-1bdfd0f47bf9'') AND EPCompanyTreeMember.active=1)) AND ( #P17 IS NULL OR #P18 = [InventoryItem].[PriceWorkgroupID]) ORDER BY (SELECT TOP (1) inventoryCD FROM InventoryItem InventoryItemExt WHERE (InventoryItemExt.CompanyID = 3) AND InventoryItemExt.DeletedDatabaseRecord = 0 AND [InventoryItemExt].[inventoryID] = [ARSalesPrice].[InventoryID]), CASE WHEN [ARSalesPrice].[PriceType] = ''B'' THEN ''Base'' WHEN [ARSalesPrice].[PriceType] = ''C'' THEN ''Customer'' WHEN [ARSalesPrice].[PriceType] = ''P'' THEN ''Customer Price Class'' END, [ARSalesPrice].[UOM], [ARSalesPrice].[BreakQty], [ARSalesPrice].[EffectiveDate], [ARSalesPrice].[RecordID] OPTION(OPTIMIZE FOR UNKNOWN) /* AR.20.20.00 */'
,
N'#P0 char(1),#P1 char(1),#P2 varchar(30),#P3 varchar(30),#P4 varchar(30),#P5 int,#P6 int,#P7 smalldatetime,#P8 smalldatetime,#P9 smalldatetime,#P10 varchar(10),#P11 varchar(10),#P12 varchar(10),#P13 varchar(10),#P14 uniqueidentifier,#P15 uniqueidentifier,#P16 bit,#P17 int,#P18 int'
,
#P0='A',
#P1='A',
#P2=NULL,
#P3=NULL,
#P4=NULL,
#P5=NULL,
#P6=NULL,
#P7=NULL,
#P8=NULL,
#P9=NULL,
#P10=NULL,
#P11=NULL,
#P12=NULL,
#P13=NULL,
#P14=NULL,
#P15=NULL,
#P16=0,
#P17=NULL,
#P18=NULL
Takes several minutes to process.
Same in normal SQL
DECLARE #P0 CHAR(1),
#P1 CHAR(1),
#P2 VARCHAR(30),
#P3 VARCHAR(30),
#P4 VARCHAR(30),
#P5 INT,
#P6 INT,
#P7 SMALLDATETIME,
#P8 SMALLDATETIME,
#P9 SMALLDATETIME,
#P10 VARCHAR(10),
#P11 VARCHAR(10),
#P12 VARCHAR(10),
#P13 VARCHAR(10),
#P14 UNIQUEIDENTIFIER,
#P15 UNIQUEIDENTIFIER,
#P16 BIT,
#P17 INT,
#P18 INT
SET #P0='A'
SET #P1='A'
SET #P2=NULL
SET #P3=NULL
SET #P4=NULL
SET #P5=NULL
SET #P6=NULL
SET #P7=NULL
SET #P8=NULL
SET #P9=NULL
SET #P10=NULL
SET #P11=NULL
SET #P12=NULL
SET #P13=NULL
SET #P14=NULL
SET #P15=NULL
SET #P16=0
SET #P17=NULL
SET #P18=NULL
SELECT TOP (27) [arsalesprice].[recordid],
[arsalesprice].[pricetype],
[arsalesprice].[custpriceclassid],
[arsalesprice].[customerid],
[arsalesprice].[inventoryid],
[arsalesprice].[curyid],
[arsalesprice].[uom],
[arsalesprice].[ispromotionalprice],
[arsalesprice].[effectivedate],
[arsalesprice].[salesprice],
[arsalesprice].[taxid],
[arsalesprice].[breakqty],
[arsalesprice].[expirationdate],
[arsalesprice].[tstamp],
[arsalesprice].[createdbyid],
[arsalesprice].[createdbyscreenid],
[arsalesprice].[createddatetime],
[arsalesprice].[lastmodifiedbyid],
[arsalesprice].[lastmodifiedbyscreenid],
[arsalesprice].[lastmodifieddatetime],
[inventoryitem].[inventoryid],
[inventoryitem].[inventorycd],
[inventoryitem].[descr],
[inventoryitem].[itemclassid],
[inventoryitem].[itemstatus],
[inventoryitem].[itemtype],
[inventoryitem].[valmethod],
[inventoryitem].[taxcategoryid],
[inventoryitem].[baseunit],
[inventoryitem].[salesunit],
[inventoryitem].[purchaseunit],
[inventoryitem].[commisionable],
[inventoryitem].[reasoncodesubid],
[inventoryitem].[salesacctid],
[inventoryitem].[salessubid],
[inventoryitem].[invtacctid],
[inventoryitem].[invtsubid],
[inventoryitem].[cogsacctid],
[inventoryitem].[cogssubid],
[inventoryitem].[discacctid],
[inventoryitem].[discsubid],
[inventoryitem].[stdcstrevacctid],
[inventoryitem].[stdcstrevsubid],
[inventoryitem].[stdcstvaracctid],
[inventoryitem].[stdcstvarsubid],
[inventoryitem].[ppvacctid],
[inventoryitem].[ppvsubid],
[inventoryitem].[poaccrualacctid],
[inventoryitem].[poaccrualsubid],
[inventoryitem].[lcvarianceacctid],
[inventoryitem].[lcvariancesubid],
[inventoryitem].[deferralacctid],
[inventoryitem].[deferralsubid],
[inventoryitem].[lastsiteid],
[inventoryitem].[laststdcost],
[inventoryitem].[pendingstdcost],
[inventoryitem].[pendingstdcostdate],
[inventoryitem].[stdcost],
[inventoryitem].[stdcostdate],
[inventoryitem].[baseprice],
[inventoryitem].[baseweight],
[inventoryitem].[basevolume],
[inventoryitem].[baseitemweight],
[inventoryitem].[baseitemvolume],
[inventoryitem].[weightuom],
[inventoryitem].[volumeuom],
[inventoryitem].[packseparately],
[inventoryitem].[packageoption],
[inventoryitem].[preferredvendorid],
[inventoryitem].[preferredvendorlocationid],
[inventoryitem].[defaultsubitemid],
[inventoryitem].[defaultsubitemonentry],
[inventoryitem].[dfltsiteid],
[inventoryitem].[dfltshiplocationid],
[inventoryitem].[dfltreceiptlocationid],
[inventoryitem].[productworkgroupid],
[inventoryitem].[productmanagerid],
[inventoryitem].[priceworkgroupid],
[inventoryitem].[pricemanagerid],
[inventoryitem].[stkitem],
(SELECT TOP (1) ( [initemclass].[negqty] )
FROM initemclass INItemClass
WHERE ( initemclass.companyid = 3 )
AND initemclass.deleteddatabaserecord = 0
AND ( [initemclass].[itemclassid] =
[inventoryitem].[itemclassid] )
ORDER BY [initemclass].[negqty]),
[inventoryitem].[lotserclassid],
[inventoryitem].[lotsernumval],
[inventoryitem].[postclassid],
[inventoryitem].[deferredcode],
[inventoryitem].[defaultterm],
[inventoryitem].[defaulttermuom],
[inventoryitem].[priceclassid],
[inventoryitem].[issplitted],
[inventoryitem].[useparentsubid],
[inventoryitem].[kititem],
[inventoryitem].[mingrossprofitpct],
[inventoryitem].[nonstockreceipt],
[inventoryitem].[nonstockship],
[inventoryitem].[completepoline],
[inventoryitem].[abccodeid],
[inventoryitem].[abccodeisfixed],
[inventoryitem].[movementclassid],
[inventoryitem].[movementclassisfixed],
[inventoryitem].[markuppct],
[inventoryitem].[recprice],
[inventoryitem].[imageurl],
[inventoryitem].[noteid],
NULL,
NULL,
NULL,
[inventoryitem].[createdbyid],
[inventoryitem].[createdbyscreenid],
[inventoryitem].[createddatetime],
[inventoryitem].[lastmodifiedbyid],
[inventoryitem].[lastmodifiedbyscreenid],
[inventoryitem].[lastmodifieddatetime],
[inventoryitem].[groupmask],
[inventoryitem].[cycleid],
[inventoryitem].[tstamp],
[inventoryitem].[isrutrotdeductible],
[inventoryitem].[body],
[inventoryitem].[rutrottype],
[inventoryitem].[rutrotitemtype],
[inventoryitem].[rutrotworktype],
(( ( [inventoryitem].[usrpartnumber] + ' : ' ) +
[inventoryitem].[usrbrand] )),
[inventoryitem].[usrsisupersededby],
[inventoryitem].[usrpartnumber],
[inventoryitem].[usrbrand],
[inventoryitem].[usrfrgnname],
[inventoryitem].[usrsipacksize],
[inventoryitem].[usrsicountryoforigin],
[inventoryitem].[usrsilength],
[inventoryitem].[usrsiwidth],
[inventoryitem].[usrsiheight],
[inventoryitem].[usrsiassocpartnumber],
[inventoryitem].[usrsispecs],
[inventoryitem].[usrsifactorypartnumber],
[inventoryitem].[usrsiitemmovementclass],
(SELECT TOP (1) ( [initemclass].[usrsimaingroup] )
FROM initemclass INItemClass
WHERE ( initemclass.companyid = 3 )
AND initemclass.deleteddatabaserecord = 0
AND ( [initemclass].[itemclassid] =
[inventoryitem].[itemclassid] )
ORDER BY [initemclass].[usrsimaingroup]),
[inventoryitem].[usrsiprintdescr]
FROM arsalesprice ARSalesPrice
LEFT JOIN inventoryitem InventoryItem
ON ( inventoryitem.companyid = 3 )
AND inventoryitem.deleteddatabaserecord = 0
AND ( [inventoryitem].[inventoryid] =
[arsalesprice].[inventoryid] )
WHERE ( arsalesprice.companyid = 3 )
AND [inventoryitem].[itemstatus] <> 'IN'
AND [inventoryitem].[itemstatus] <> 'DE'
AND ( #P0 = N'A'
OR [arsalesprice].[pricetype] = #P1 )
AND ( [arsalesprice].[customerid] = #P2
OR [arsalesprice].[custpriceclassid] = #P3
OR #P4 IS NULL )
AND ( [arsalesprice].[inventoryid] = #P5
OR #P6 IS NULL )
AND ( ( ( [arsalesprice].[effectivedate] <= #P7
OR [arsalesprice].[effectivedate] IS NULL )
AND ( [arsalesprice].[expirationdate] >= #P8
OR [arsalesprice].[expirationdate] IS NULL ) )
OR #P9 IS NULL )
AND ( #P10 IS NULL
OR #P11 = [inventoryitem].[itemclassid] )
AND ( #P12 IS NULL
OR #P13 = [inventoryitem].[priceclassid] )
AND ( #P14 IS NULL
OR #P15 = [inventoryitem].[pricemanagerid] )
AND ( #P16 = CONVERT(BIT, 0)
OR [inventoryitem].[priceworkgroupid] IN
(SELECT epcompanytreemember.workgroupid
FROM
epcompanytreemember EPCompanyTreeMember
WHERE (
epcompanytreemember.companyid = 3 )
AND
epcompanytreemember.userid =
CONVERT(UNIQUEIDENTIFIER,
'b5344897-037e-4d58-b5c3-1bdfd0f47bf9')
AND
epcompanytreemember.active = 1) )
AND ( #P17 IS NULL
OR #P18 = [inventoryitem].[priceworkgroupid] )
ORDER BY (SELECT TOP (1) inventorycd
FROM inventoryitem InventoryItemExt
WHERE ( InventoryItemExt.companyid = 3 )
AND InventoryItemExt.deleteddatabaserecord = 0
AND [InventoryItemExt].[inventoryid] =
[arsalesprice].[inventoryid]),
CASE
WHEN [arsalesprice].[pricetype] = 'B' THEN 'Base'
WHEN [arsalesprice].[pricetype] = 'C' THEN 'Customer'
WHEN [arsalesprice].[pricetype] = 'P' THEN 'Customer Price Class'
END,
[arsalesprice].[uom],
[arsalesprice].[breakqty],
[arsalesprice].[effectivedate],
[arsalesprice].[recordid]
OPTION(optimize FOR unknown) /* AR.20.20.00 */
Just takes 2-3 seconds to run.
I tried clearing the query plan after adding indexes. still issue persists.
sp_executesql is generated by a framework and I am trying to optimize that query result. so is there anything i can do to make it run faster?
Any help?

Old SQL Query Optimization

I have a pre written SQL Query, which takes 45 minutes to actually run and show the data. It returns total 80000+ records. But it takes hell lot of time to run and show the data.
SELECT
hq.QuoteHeaderId,
hq.HandsetQuoteId,
hq.QuoteDate,
t_PhoneAudit.PhoneModelId,
t_PhoneAudit.IMEI,
t_PhoneModel.ModelName,
t_PhoneBrand.Name As BrandName
, al.ActivityId
, par.Result
, al.CustomMessage,
al.[Description]
,thqai.Value AS AgentName
FROM [t_DynaGroupMissingRecordsProcessing]
INNER JOIN t_HandsetQuote hq ON t_DynaGroupMissingRecordsProcessing.HandsetQuoteId = hq.HandsetQuoteId
INNER JOIN t_PhoneAudit ON t_PhoneAudit.PhoneAuditId = hq.QuotePhoneAuditId
INNER JOIN t_PhoneModel ON t_PhoneModel.PhoneModelId = t_PhoneAudit.PhoneModelId
INNER JOIN t_PhoneBrand ON t_PhoneBrand.PhoneBrandId = t_PhoneModel.PhoneBrandId
INNER JOIN
(
SELECT par.HandsetQuoteId, txt_Value AS ActivityId, 'OK' AS Result FROM t_PhoneAuditRetail par CROSS APPLY dbo.fn_ParseText2Table(par.Ok, ',')
UNION
SELECT par.HandsetQuoteId, txt_Value AS ActivityId, 'Fault' AS Result FROM t_PhoneAuditRetail par CROSS APPLY dbo.fn_ParseText2Table(par.Fault, ',')
) par ON hq.HandsetQuoteId = par.HandsetQuoteId
INNER JOIN t_ActivityLocalization al ON par.ActivityId = al.ActivityId
INNER JOIN t_ContactChannel CC ON al.ContactChannelId = CC.ContactChannelId
INNER JOIN t_testingProfiledetails ON t_testingProfiledetails.ActivityId = al.ActivityId AND ( IsVisibleForRetail = '1' OR t_testingProfiledetails.ActivityId IN ('93','97')) AND t_testingProfiledetails.ProfileId IN (SELECT DefailtRetailProfileId FROM t_ContactChannel WHERE Name IN ('Holland Retail', 'BelCompanyNPEY Retail', 'Belcompany Retail', 'HollandNPEY Retail'))
LEFT OUTER JOIN t_HandsetQuoteAdditionalInfo thqai on thqai.HandsetQuoteId = hq.HandsetQuoteId and thqai.KeyName = 'AgentName'
WHERE [t_DynaGroupMissingRecordsProcessing].IsProcessed = 0
AND CC.Name IN ('Holland Retail', 'BelCompanyNPEY Retail', 'Belcompany Retail', 'HollandNPEY Retail')
ORDER BY hq.HandsetQuoteId
The main problem is with CC.Name IN ('Holland Retail', 'BelCompanyNPEY Retail', 'Belcompany Retail', 'HollandNPEY Retail') this statement.
If i keep on adding the name in the In Statement, the query becomes more and more slow.
Below is the defintion for the function i am using:
ALTER FUNCTION [dbo].[fn_ParseText2Table]
(
#p_SourceText VARCHAR(8000)
,#p_Delimeter VARCHAR(100) = ',' --default to comma delimited.
)
RETURNS #retTable TABLE
(
txt_value VARCHAR(2000)
)
AS
BEGIN
DECLARE #w_Continue int
,#w_StartPos int
,#w_Length int
,#w_Delimeter_pos int
,#w_tmp_txt VARCHAR(2000)
,#w_Delimeter_Len tinyint
SET #w_Continue = 1
SET #w_StartPos = 1
SET #p_SourceText = RTRIM( LTRIM( #p_SourceText))
SET #w_Length = DATALENGTH( RTRIM( LTRIM( #p_SourceText)))
SET #w_Delimeter_Len = len(#p_Delimeter)
WHILE #w_Continue = 1
BEGIN
SET #w_Delimeter_pos = CHARINDEX(#p_Delimeter,(SUBSTRING( #p_SourceText, #w_StartPos,((#w_Length - #w_StartPos)+#w_Delimeter_Len))))
IF #w_Delimeter_pos > 0 -- delimeter(s) found, get the value
BEGIN
SET #w_tmp_txt = LTRIM(RTRIM( SUBSTRING( #p_SourceText, #w_StartPos
,(#w_Delimeter_pos - 1)) ))
SET #w_StartPos = #w_Delimeter_pos + #w_StartPos + (#w_Delimeter_Len- 1)
END
ELSE -- No more delimeters, get last value
BEGIN
SET #w_tmp_txt = LTRIM(RTRIM( SUBSTRING( #p_SourceText, #w_StartPos
,((#w_Length - #w_StartPos) + #w_Delimeter_Len)) ))
SELECT #w_Continue = 0
END
INSERT INTO #retTable VALUES( #w_tmp_txt )
END
RETURN
END
Please help me to optimize this query.
you can try this
Insert the list of names to #table(name) and join it to cc
on cc.name=#table.name

Optimize assigning values to local variables in T-SQL

Is there any way to combine the following and set #FH_RecordKey and #VF_dept_seq in one SET or SELECT statement?
set #FH_RecordKey =(
case #lnktble
when 'ems' then (select FH_inci_id from FH_Catherine_live.dbo.FH_MAP_EMS_INCI where VF_ems_seq = #tempseq)
when 'imaster' then (select FH_insp_id from FH_Catherine_live.dbo.FH_MAP_INSPID where VF_in_seq = #tempseq)
when 'n5basic' then (select inci_id from [dbo].[VF_IncWorkTable] where inc_seq = #tempseq)
END)
set #VF_dept_seq = (
case #lnktble
when 'ems' then (select VF_dept_seq from FH_Catherine_Live.dbo.FH_MAP_EMS_INCI where VF_ems_seq = #tempseq)
when 'imaster' then (select VF_dept_seq from FH_Catherine_Live.dbo.FH_MAP_INSPID where VF_in_seq = #tempseq)
when 'n5basic' then (select dept_seq from [dbo].[VF_IncWorkTable] where inc_seq = #tempseq)
end)
Use an IF statement rather than CASE
IF #lnktble = 'ems'
select #FH_RecordKey = FH_inci_id ,#VF_dept_seq = VF_dept_seq
from FH_Catherine_live.dbo.FH_MAP_EMS_INCI
where VF_ems_seq = #tempseq
ELSE IF #lnktble = 'imaster' /*...*/
Select #FH_RecordKey =
(case statement here),
#VF_dept_seq =
(case statement here)

SQL Server - How to make an INTERSECT select optional?

I'm working on an advanced search sproc and would like to know if it is possible for a portion of my select to be included or not based on a parameter. I could use an IF ELSE on my parameter, but I already have one for another parameter, and that seems like a lot of code duplication.
-- My advanced search function allows a user to specify various parameters. The basic search can be EXACT or not (contains vs freetext - first if), and other parameters (AND) can be specified. Specific keywords can also be selected as well (intersect).
My issue is that when #Keywords is null, I don't want to include the final INTERSECT SELECT ... portion of the code at the bottom of my example. Is there a quick way to do this without adding another IF ELSE in the top and bottom queries? Let me know if you need more detailed information.
declare #SearchTerms nvarchar(4000)
declare #GalleryId int
declare #Keywords nvarchar(4000)
declare #ExactWord int
declare #BeginDateUpload datetime
declare #EndDateUpload datetime
declare #BeginDateTaken datetime
declare #EndDateTaken datetime
declare #MinFileSize int
declare #MaxFileSize int
declare #AlbumType bit
declare #ImageType int
declare #AudioType int
declare #OtherType int
declare #VideoType int
set #SearchTerms = 'tulips'
set #GalleryId = 1
set #Keywords = null -- 'st-jean'
set #ExactWord = null
set #BeginDateUpload = null
set #EndDateUpload = null
set #BeginDateTaken = null
set #EndDateTaken = null
set #MinFileSize = null
set #MaxFileSize = null
set #AlbumType = 1
set #ImageType = 1
set #AudioType = 1
set #OtherType = 1
set #VideoType = 1
IF ISNULL(#ExactWord, 0) = 1
BEGIN
[... snip ...]
END
ELSE
select t1.* from (
SELECT 'm' as objType, m.MediaObjectId
FROM gs_mediaObjectMetadata md
INNER JOIN dbo.[gs_MediaObject] m
ON md.FKMediaObjectId = m.MediaObjectId
INNER JOIN dbo.[gs_Album] a
ON a.AlbumId = m.FKAlbumId
WHERE FREETEXT (value, #SearchTerms)
AND a.FKGalleryId = #GalleryId
AND (m.DateAdded >= ISNULL(#BeginDateUpload, m.DateAdded))
AND (m.DateAdded <= ISNULL(#EndDateUpload, m.DateAdded))
AND (m.DateTaken is NULL OR m.DateTaken >= ISNULL(#BeginDateTaken, m.DateTaken))
AND (m.DateTaken is NULL OR m.DateTaken <= ISNULL(#EndDateTaken, m.DateTaken))
AND (m.OriginalSizeKB >= ISNULL(#MinFileSize, m.OriginalSizeKB))
AND (m.OriginalSizeKB <= ISNULL(#MaxFileSize, m.OriginalSizeKB))
AND((m.FKMediaObjectTypeId = ISNULL(#ImageType, 0))
OR (m.FKMediaObjectTypeId = ISNULL(#AudioType, 0))
OR (m.FKMediaObjectTypeId = ISNULL(#VideoType, 0))
OR (m.FKMediaObjectTypeId = ISNULL(#OtherType, 0)))
union
SELECT 'm' as objType, m.MediaObjectId
FROM dbo.[gs_MediaObject] m
INNER JOIN dbo.[gs_Album] a
ON a.AlbumId = m.FKAlbumId
WHERE FREETEXT ((m.Title, OriginalFilename), #SearchTerms)
AND a.FKGalleryId = #GalleryId
AND (m.DateAdded >= ISNULL(#BeginDateUpload, m.DateAdded))
AND (m.DateAdded <= ISNULL(#EndDateUpload, m.DateAdded))
AND (m.DateTaken is NULL OR m.DateTaken >= ISNULL(#BeginDateTaken, m.DateTaken))
AND (m.DateTaken is NULL OR m.DateTaken <= ISNULL(#EndDateTaken, m.DateTaken))
AND (m.OriginalSizeKB >= ISNULL(#MinFileSize, m.OriginalSizeKB))
AND (m.OriginalSizeKB <= ISNULL(#MaxFileSize, m.OriginalSizeKB))
AND((m.FKMediaObjectTypeId = ISNULL(#ImageType, 0))
OR (m.FKMediaObjectTypeId = ISNULL(#AudioType, 0))
OR (m.FKMediaObjectTypeId = ISNULL(#VideoType, 0))
OR (m.FKMediaObjectTypeId = ISNULL(#OtherType, 0)))
) t1
--IF #Keywords != null -- conditional intersect
intersect
SELECT 'm' as objType, m.MediaObjectId
FROM dbo.[gs_MediaObject] m
INNER JOIN dbo.[gs_Album] a
ON a.AlbumId = m.FKAlbumId
left join dbo.gs_MediaObjectMetadata md
on m.MediaObjectId = md.FKMediaObjectId
WHERE FREETEXT ((m.Title, OriginalFilename), #SearchTerms)
AND a.FKGalleryId = #GalleryId
AND (m.DateAdded >= ISNULL(#BeginDateUpload, m.DateAdded))
AND (m.DateAdded <= ISNULL(#EndDateUpload, m.DateAdded))
AND (m.DateTaken is NULL OR m.DateTaken >= ISNULL(#BeginDateTaken, m.DateTaken))
AND (m.DateTaken is NULL OR m.DateTaken <= ISNULL(#EndDateTaken, m.DateTaken))
AND (m.OriginalSizeKB >= ISNULL(#MinFileSize, m.OriginalSizeKB))
AND (m.OriginalSizeKB <= ISNULL(#MaxFileSize, m.OriginalSizeKB))
AND((m.FKMediaObjectTypeId = ISNULL(#ImageType, 0))
OR (m.FKMediaObjectTypeId = ISNULL(#AudioType, 0))
OR (m.FKMediaObjectTypeId = ISNULL(#VideoType, 0))
OR (m.FKMediaObjectTypeId = ISNULL(#OtherType, 0)))
and UPPER(md.Description) = 'KEYWORDS'
and exists (
SELECT *
FROM dbo.fnSplit(Replace(md.Value, '''', ''''''), ',') split
WHERE split.item in
(SELECT * from dbo.fnSplit(Replace(#Keywords, '''', ''''''), ','))
)
Thank you
What about instead of doing the intersect, try this out in your inner queries : #Keyword is null or .....
and ( #Keywords is null or (UPPER(md.Description) = 'KEYWORDS'
and exists (
SELECT *
FROM dbo.fnSplit(Replace(md.Value, '''', ''''''), ',') split
WHERE split.item in
(SELECT * from dbo.fnSplit(Replace(#Keywords, '''', ''''''), ','))
)
)
)

Resources