Performance problems in SQL Server -


i´m trying sql sentence works fine (i think) have performance problem, takes 32 minutes execute, , think can poor code, can 1 me how improve it?

this code:

select distinct      s.nombre, l.nomcli cli,     (select max(lineas.fecalb)        lineas       lineas.codart = s.codart , lineas.codcli = l.codcli) fecha,    (select max(proveedores.nombre)      proveedores      proveedores.codpro = s.codpro) proveedor, (select max(lineas.codrep) lineas lineas.codart=s.codart) representante  stock s  inner join lineas l on s.codart=l.codart    s.codart in(select lineas.codart lineas inner join stock on   lineas.codart=stock.codart datediff("d",lineas.fecalb,getdate())<365 , stock.stoexi>0 group lineas.codart having count(lineas.codart)<=2  )and   (s.codart in(  select st.codart stock st st.codart not in  (select lineas.codart lineas  datediff("d",lineas.fecalb,getdate())<=60) , st.stoexi>0)  or s.codart in (select lineas.codart lineas  datediff("d",lineas.fecalb,getdate())<182 group lineas.codart having count(lineas.codart)<=2 , (s.stoexi>0)) or s.codart in (select lineas.codart lineas  datediff("d",lineas.fecalb,getdate())<=182 group lineas.codart having sum(lineas.unidad)<s.stoexi))  order s.nombre,l.nomcli desc ; 

first have more or less same sentence without first condition

 s.codart in (select lineas.codart                lineas                inner join stock on lineas.codart = stock.codart                datediff("d", lineas.fecalb, getdate()) < 365                  , stock.stoexi > 0                group lineas.codart                having count(lineas.codart) <= 2) , 

works fine takes 18 seconds.

the líneas table have 600000 rows , stock 53000

in condition calculating datediff each record. database won't able use index field, field isn't compared specific value. instead should calculate point in time compare field to.

instead of:

datediff("d",lineas.fecalb,getdate())<182 

try:

lineas.fecalb >= dateadd("d", -182, getdate()) 

your use of distinct means run subqueries more times need, discard duplicates. should try first filter out records want result for, can run subqueries on that.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -