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.
Related
Is there a way to use joins in update statements for DB2?
Google has really let me down.
This is roughly what I'm trying to achieve (... except obviously working ....)
Update gk.WR_VEHICLE_WARRANTY w
join gk.VGARANT_FRIST_ZUWEIS z
on z.PK_GARANT_FRIST_ZUWEIS = w.FK_GARANT_FRIST_ZUWEIS
set CURRENT = '1'
where z.GW = '1'
and z.FK_GBE is null
and z.INTERN = '0';
I solved the problem , just took out the join and did a inner select
Update gk.WR_VEHICLE_WARRANTY
set CURRENT = '1'
Where FK_GARANT_FRIST_ZUWEIS in
(select PK_GARANT_FRIST_ZUWEIS from gk.VGARANT_FRIST_ZUWEIS z
where z.GW = '1'
and z.FK_GBE is null
and z.INTERN = '0' )
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.
I'm having a bit of brain fade today and can't figure out how I should express this SQL query correctly using ActiveRecord/Squeel/ARel:
SELECT `d1`.* FROM `domain_names` d1
WHERE `d1`.`created_at` = (
SELECT MAX(`d2`.`created_at`)
FROM `domain_names` d2
WHERE `d2`.`owner_type` = `d1`.`owner_type`
AND `d2`.`owner_id` = `d1`.`owner_id`
AND `d2`.`key` = `d1`.`key`
)
Any ideas?
Background: The DomainName model has a polymorphic owner as well as a "key" field that allows owners to have many different types of domain name. The query above fetches the latest domain name for each unique [owner_type, owner_id, key] tuple.
Edit:
Here's the same query using JOIN:
SELECT `d1`.* FROM `domain_names` d1
JOIN (
SELECT `owner_type`, `owner_id`, `key`, MAX(`created_at`) max_created_at
FROM `domain_names`
GROUP BY `owner_type`, `owner_id`, `key`
) d2
ON `d2`.`owner_type` = `d1`.`owner_type`
AND `d2`.`owner_id` = `d1`.`owner_id`
AND `d2`.`key` = `d1`.`key`
WHERE `d1`.`created_at` = `d2`.`max_created_at`
I have multiple tables in a join and every table has a column ID. So in the resultig join there are a lot of ID columns. How I can access a specific ID column with the criteria API?
ParameterExpression<A> idParam = criteriaBuilder.parameter(A.class, PARAM_NAME);
Subquery<B> sq = query.subquery(B.class);
Root<B> root = sq.from(B.class);
Join<C, D> joinTogether = root.join("memberX").join("memberY");
sq.select(root);
sq.where(criteriaBuilder.and(criteriaBuilder.equal(joinTogether.get("id"), idParam), criteriaBuilder.equal(parentQuery.get("id"), root.get("id"))));
The problem is, that in the resulting SQL contains
SELECT 1 FROM E t6, B t5, C t4, D t3 WHERE ((( = paramName) AND (t0.ID = t5.ID)) AND (((t6.memberZ = t5.ID) AND (t4.ID = t6.memberX)) AND (t3.ID = t4.memberY))))
The table E (t6) is an additional join table between table B and C, t0 is the reference to the parent query. Instead t3.id = :paramName EclipseLink creates nothing just before the first equal-sign (paramName is the content of the constant PARAM_NAME). My idea is, that the "id" column could reference all tables and EclipseLink can not decide, which table I mean.
How I can change that?
Thank you
André
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.