Sql Server queries optimization techniques - stored-procedures

My Stored Procedure takes a very long time to execute.
Can anyone suggest me what I can do to speed up the stored procedure, apart from using some good practices for writing down the queries.
I've heard about creating indices, but I'm not sure what are they.
Please suggest all the best ways to speed up my queries.
Thanks
CREATE PROCEDURE [dbo].[usp_GetAlternates]
(
#NNumber CHAR(11) ,
#pid INT ,
#pbmid INT
)
AS
BEGIN
TRUNCATE TABLE TempTherapeuticAlt
INSERT INTO TempTherapeuticAlt
SELECT NULL AS MedicationID ,
PR.ePrescribingName AS MedicationName ,
U.Strength AS MedicationStrength ,
FRM.FormName AS MedicationForm ,
PR.DEAClassificationID AS DEASchedule ,
NULL AS NDCNumber
FROM Product PR
JOIN ( SELECT MP.MarketedProductID
FROM table2 TCTSP
JOIN table3 MP ON MP.SpecificProductID = TCTSP.SpecificProductID
JOIN ( SELECT TCTSP.TherapeuticConceptTreeID
FROM table3 MP
JOIN table2 TCTSP ON MP.SpecificProductID = TCTSP.SpecificProductID
JOIN ( SELECT
PR.MarketedProductID
FROM
table4 PA
JOIN Product PR ON PA.ProductID = PR.ProductID
WHERE
PA.NDC11 = #NNumber
) PAPA ON MP.MarketedProductID = PAPA.MarketedProductID
) xxx ON TCTSP.TherapeuticConceptTreeID = xxx.TherapeuticConceptTreeID
) MPI ON PR.MarketedProductID = MPI.MarketedProductID
JOIN ( SELECT P.ProductID ,
O.Strength ,
O.Unit
FROM Product AS P
INNER JOIN table3 AS M ON P.MarketedProductID = M.MarketedProductID
INNER JOIN table5 AS S ON M.SpecificProductID = S.SpecificProductID
LEFT OUTER JOIN table6 AS O ON S.SpecificProductID = O.SpecificProductID
GROUP BY P.ProductID ,
O.Strength ,
O.Unit
) U ON PR.ProductID = U.ProductID
JOIN ( SELECT PA.ProductID ,
S.ScriptFormID ,
F.Code AS NCPDPScriptFormCode ,
S.FormName
FROM table4 AS PA
INNER JOIN table7 AS S ON PA.NCPDPScriptFormCode = S.NCPDPScriptFormCode
INNER JOIN table8 AS F ON S.FormName = F.FormName
GROUP BY PA.ProductID ,
S.ScriptFormID ,
F.Code ,
S.FormName
) FRM ON PR.ProductID = FRM.ProductID
GROUP BY PR.ePrescribingName ,
U.Strength ,
FRM.FormName ,
PR.DEAClassificationID
ORDER BY pr.ePrescribingName
SELECT LL.ProductID AS MedicationID ,
temp.MedicationName ,
temp.MedicationStrength ,
temp.MedicationForm ,
temp.DEASchedule ,
temp.NDCNumber ,
fs.[ReturnFormulary] AS FormularyStatus ,
copay.CopaTier ,
copay.FirstCopayTerm ,
copay.FlatCopayAmount ,
copay.PercentageCopay
FROM TempTherapeuticAlt temp
OUTER APPLY ( SELECT TOP 1
ProductID
FROM Product
WHERE ePrescribingName = temp.MedicationName
) AS LL
OUTER APPLY function1(#pid, LL.ProductID, #pbmid) AS fs
OUTER APPLY function2(LL.ProductID, #pbmid) AS copay
ORDER BY LL.ProductID
TRUNCATE TABLE TempTherapeuticAlt
END
GO

Here are a few:
You should have indexes for every column in a WHERE clause. See
your SQL language for how to do it.
Learn how to EXPLAIN PLAN and see what's slow.
Stored procedure languages are functional, not set based. Use JOIN and don't fall into the (n+1) query/iteration trap.
Understand how using certain functions force you to TABLE SCAN in a WHERE clause.

Related

SSRS report: Could not update a list of fields for the query. An item with same key has already been added

I have written a stored procedure as follows:
ALTER PROCEDURE [dbo].[Transaction]
(
#date_start date,
#date_end date
)
AS
BEGIN
with
rntexportbatch as (
Select
fb.BatchId,
rt.TransactionId,
count(*) as line_Count
from CxWarehouse.dbo.FinancialBatchPostingDetail fbpd
INNER JOIN CxWarehouse.dbo.FinancialBatchPosting fb
on (fb.BatchPostingId = fbpd.BatchPostingId and NominalAccount='12000' ) ---and NominalAccount='12000'
INNER JOIN CxWarehouse.dbo.FinancialBatch finb
on (finb.BatchId = fb.BatchId)
INNER JOIN CxWarehouse.dbo.SystemLookup l
on (l.LookupReference = finb.TransactionTypeId and LookupTypeId = 42)
INNER JOIN CxWarehouse.dbo.Financialtransaction ft
on (ft.TransactionId = fbpd.TransactionId)
LEFT JOIN CxWarehouse.dbo.RentTransactionElement rte
on (rte.TransactionElementId = ft.EntityId)
LEFT JOIN CxWarehouse.dbo.RentElement re
ON (re.ElementId = rte.ElementId)
LEFT JOIN CxWarehouse.dbo.RentTransaction rt
ON (rt.TransactionId = rte.TransactionId)
Group by rt.TransactionId,fb.BatchId
)
Select
ast.AssetId,
ast.AssetReference,
ast.[Agreement Description],
ast.CompanyIds,
rntAcc.AccountId,
rntAcc.AccountReference,
rntAcc.PaymentReference,
rt.TransactionId,
rt.AccountId,
rt.TransactionDate,
rt.TransactionTypeId,
[Transaction Type Id Description],
rt.PostingDate,
rt.PeriodNumber,
rt.Description as 'Rent Transaction Description',
rt.Notes,
[ElementId Description] ,
rntPay.BatchReference as 'Import BatchId',
rntPay.[Import Value],
rntexportbatch.BatchId as 'Export BatchId',
final.Value as 'Export Value'
from CxWarehouse.dbo.RentTransaction as rt
LEFT Join (
Select LookupId,
LookupTypeId,
LookupReference,
Description as 'Transaction Type Id Description'
from CxWarehouse.dbo.SystemLookup
where LookupTypeId = 46
) lu
on rt.TransactionTypeId = lu.LookupReference
LEFT Join (
Select
te.TransactionId,
te.TransactionElementId,
te.ElementId,
te.Value,
rntElm.Description as 'ElementId Description'
from CxWarehouse.dbo.RentTransactionElement as te
LEFT Join (
Select * from CxWarehouse.dbo.RentElement
) rntElm
on te.ElementId = rntElm.ElementId
) final
on rt.TransactionId = final.TransactionId
LEFT JOIN (
Select
t.AccountId,
t.AccountReference,
t.PaymentReference,
typ.Description as 'AccountType Description'
from CxWarehouse.dbo.RentAccount as t
left Join CxWarehouse.dbo.RentAccountType as typ
on t.AccountTypeId = typ.AccountTypeId
) rntAcc
on rt.AccountId = rntAcc.AccountId
Left Join (
Select
ast.AssetId,
AssetReference,
rntInf.AccountId,
rntInf.[Agreement Description],
rntInf.CompanyIds
from CxWarehouse.dbo.Asset as ast
left join (
Select
rntAgAs.AgreementAssetId,
rntAgAs.AgreementId,
rntAgAs.AssetId,
rntAgr.AccountId,
rntAgr.[Agreement Description],
rntAgr.CompanyIds
from CxWarehouse.dbo.RentAgreementAsset as rntAgAs
left join (
Select
rntAgmt.AgreementId,
rntAgmt.AgreementReference,
rntAgmt.AgreementTypeId,
rntAgmtTyp.Description as 'Agreement Description',
rntAgmtTyp.CompanyIds,
accEpi.AccountId
from CxWarehouse.dbo.RentAgreement as rntAgmt
LEFT JOIN CxWarehouse.dbo.RentAgreementType rntAgmtTyp
on rntAgmt.AgreementTypeId = rntAgmtTyp.AgreementTypeId
Left Join (
Select
rntAgEp.AgreementEpisodeId,
rntAgEp.AgreementId,
rntAgAc.AccountId
from CxWarehouse.dbo.RentAgreementEpisode as rntAgEp
Left Join CxWarehouse.dbo.RentAgreementAccount as rntAgAc
on rntAgEp.AgreementEpisodeId =rntAgAc.AgreementEpisodeId
) accEpi
on rntAgmt.AgreementId = accEpi.AgreementId
) rntAgr
on rntAgAs.AgreementId = rntAgr.AgreementId
) rntInf
on ast.AssetId = rntInf.AssetId
) ast
on rntAcc.AccountId = ast.AccountId
Left Join (
Select
rp.PaymentId,
rp.BatchReference,
rpd.PaymentDetailId,
rpd.Value as 'Import Value',
GeneratedTransactionId
from CxWarehouse.dbo.RentPayment as rp
left Join CxWarehouse.dbo.RentPaymentDetail rpd
on rp.PaymentId = rpd.PaymentId
left join CxWarehouse.dbo.RentPaymentPosting rpp
on rpd.PaymentDetailId = rpp.PaymentDetailId
) rntPay
on rt.TransactionId = rntPay.GeneratedTransactionId
LEFT JOIN rntexportbatch
on rntexportbatch.TransactionId = rt.TransactionId
where rt.PostingDate between #date_start and #date_end
END
I used that stored procedure in SSRS report. When I clicked on the dataset option of the report and refresh the data set, it gave following error:
I looked at the forum and found that error comes due to two or more columns have same name. I looked at the code and made sure that no column have same name. However, the problem still exist. Could anyone help me where I am making the mistake?
You have two columns both called AccountID being returned from your query
...
rntAcc.AccountId,
rntAcc.AccountReference,
rntAcc.PaymentReference,
rt.TransactionId,
rt.AccountId,
....
Alias or remove one of these columns.

Querying two partitions from same table in Bigquery

I am looking to do some querying on two partitions (different partition date) on BQ.
Table format is the following
crm_id, attribute#1, attribute#2,attribute#3
For the IDs that are common from week 1 and week 2, I want to see how many changed attribute#1, attribute#2 and attribute# 3
I started with the inner join using:
WITH t1 AS
(SELECT crm_id AS w1_crm
FROM `table`
WHERE DATE(_PARTITIONTIME) = "date1"
)
SELECT crm_id
FROM `table`
WHERE DATE(_PARTITIONTIME) = "date2"
INNER JOIN
t1
ON
w1_crm = crm_id
I am getting an error on the INNER JOIN
Try below
WITH t1 AS (
SELECT crm_id AS w1_crm
FROM `table`
WHERE DATE(_PARTITIONTIME) = "date1"
), t2 AS (
SELECT crm_id
FROM `table`
WHERE DATE(_PARTITIONTIME) = "date2"
)
SELECT crm_id
FROM t2
INNER JOIN t1
ON w1_crm = crm_id

Any way to improve the performance of this store procedure?

Any way to improve the performance of this store procedure?
For example combining both updates clauses in a unique statement (T-SQL).
BonosConvenio and CON_Convenio are almost 5K rows.
create table #resultados (
monto_deuda float
,Cuenta float
,Rut varchar(10)
,CodCONVENIO varchar(4)
,CONVENIO varchar(50)
,Bono varchar(15)
,MontoBono float
,ApellDeudor varchar(100)
)
INSERT INTO #resultados(Cuenta,monto_deuda,Rut,CodCONVENIO,CONVENIO,Bono,MontoBono,ApellDeudor)
select ATC_CTA_Correlativo, monto_deuda, RutDeudor, CodCONVENIO,'','',0,''
from CartaCobProgramasCONVENIO
where Nomina = #Nomina
UPDATE #resultados
SET Bono=bc.Bono,
MontoBono=bc.Monto
FROM BonosCONVENIO bc
WHERE bc.ATC_CTA_Correlativo=#resultados.Cuenta;
UPDATE #resultados
SET ApellDeudor=upper(rtrim(ltrim(Paciente.PAC_PAC_Nombre))
FROM BD_ENTI_CORPORATIVA..ATC_Cuenta Cuenta, BD_ENTI_CORPORATIVA..PAC_Paciente Paciente
WHERE Cuenta.ATC_CTA_Correlativo=#resultados.Cuenta AND Paciente.PAC_PAC_Numero = Cuenta.PAC_PAC_Numero
UPDATE #resultados
SET CONVENIO=c.CON_CON_Descripcio
FROM BD_ENTI_CORPORATIVA..CON_Convenio c
WHERE c.CON_CON_Codigo =#resultados.CodCONVENIO
SELECT * FROM #resultados ORDER BY Cuenta,Bono
End
Try this:
SELECT
ccpc.ATC_CTA_Correlativo Cuenta
, ccpc.monto_deuda
, ccpc.RutDeudor Rut
, ccpc.CodCONVENIO
, c.CON_CON_Descripcio CONVENIO
, bc.Bono
, bc.Monto MontoBono
, UPPER(RTRIM(LTRIM(Paciente.PAC_PAC_Nombre))) ApellDeudor
FROM
CartaCobProgramasCONVENIO ccpc
INNER JOIN
BonosCONVENIO bc ON
ccpc.ATC_CTA_Correlativo = bc.ATC_CTA_Correlativo
INNER JOIN
BD_ENTI_CORPORATIVA..ATC_Cuenta Cuenta ON
ccpc.ATC_CTA_Correlativo = Cuenta.ATC_CTA_Correlativo
INNER JOIN
BD_ENTI_CORPORATIVA..PAC_Paciente Paciente ON
Cuenta.PAC_PAC_Numero = Paciente.PAC_PAC_Numero
INNER JOIN
BD_ENTI_CORPORATIVA..CON_Convenio c ON
c.CON_CON_Codigo = ccpc.CodCONVENIO
WHERE Nomina = #Nomina;
If you have duplicate records because of the joins, it's because there are multiple values in the tables. Your original query (using an update) would overwrite and only show the last row's value. To work around this, you would probably want to have a GROUP BY and MIN, MAX, SUM or whatever.

need to convert SQL CROSS JOIN into LINQ

I have two tables table1 and table2. Each table contains a column with itemPrice. I need to add the two columns together.
The SQL query below returns the correct SUM.
SELECT SUM(item1+ item2) FROM
(select SUM(t1.itemPrice) item1 from table1 t1 WHERE t1.userid=='jonh') tableA
CROSS JOIN
(select SUM(t2.itemPrice) item2 from table2 t2 WHERE t1.userid=='jonh') tableB
I am not been lazy but the above query has so many SUM functions that I don't know where to start to write LINQ queries.
Can anyone help?
Ceci,
Hopefully this will give you what you want...
from f in (
from x in ( from t1 in Table1
where t1.Userid.Equals("John")
select new { Userid = t1.Userid }
).Distinct()
select new { item1 = ( from z in Table1
where z.Userid.Equals("John")
select z.ItemPrice ).Sum() ??0 ,
item2 = ( from z in Table2
where z.Userid.Equals("John")
select z.ItemPrice ).Sum() ??0 }
) select new { total = f.item1 + f.item2 }
In the case where there are no records for "john" in one table, it will bring back a 0 and sum up the other tables.
hope this helps.

How to create a MariaDB 10 "VIEW" using LEFT OUTER JOIN excluding duplicate results

What changes to this database query are needed to create a VIEW while excluding the duplicate results?
SELECT
`acts2301_online_store`.`online_store_product_quantity`.`online_store_product_reference` ,
`acts2301_online_store`.`online_store_product_quantity`.`quantity` AS inventory_quantity ,
`acts2301_money`.`paypal_cart_info`.`quantity` AS purchase_quantity_cart ,
`acts2301_money`.`paypal_payment_info`.`quantity` AS purchase_quantity_payment ,
`acts2301_online_store`.`online_store_product`.`low_inventory_alert_quantity` ,
`acts2301_online_store`.`online_store_product`.`live` ,
`acts2301_online_store`.`online_store_product`.`discontinued`
FROM ( (
`acts2301_online_store`.`online_store_product_quantity`
LEFT OUTER JOIN
`acts2301_money`.`paypal_cart_info`
ON `acts2301_online_store`.`online_store_product_quantity`.`online_store_product_reference` = `acts2301_money`.`paypal_cart_info`.`itemnumber` )
LEFT OUTER JOIN
`acts2301_money`.`paypal_payment_info`
ON `acts2301_online_store`.`online_store_product_quantity`.`online_store_product_reference` = `acts2301_money`.`paypal_payment_info`.`itemnumber` )
INNER JOIN
`acts2301_online_store`.`online_store_product`
ON `acts2301_online_store`.`online_store_product_quantity`.`online_store_product_reference` = `acts2301_online_store`.`online_store_product`.`reference`

Resources