SQL UPDATE SUM VALUE NOT NULL

Asked

Viewed 166 times

0

dataTmp     referencia  nStock
2017-02-18  DC01234567  NULL    
2017-02-18  DC01234567  NULL    
2017-02-18  DC01234567  NULL    
2017-02-19  DC01234567  0   
2017-02-19  DC01234567  0   
2017-02-19  DC01234567  0   
2017-02-20  DC01234567  0
2017-02-20  DC01234567  -450    
2017-02-20  DC01234567  -450    
2017-02-18  RE21341241  NULL    
2017-02-18  RE21341241  NULL    
2017-02-18  RE21341241  NULL    
2017-02-19  RE21341241  1000    
2017-02-19  RE21341241  1000
2017-02-19  RE21341241  1000    
2017-02-20  RE21341241  1000
2017-02-20  RE21341241  -5000   
2017-02-20  RE21341241  -6000   

I have this table where I update from a "Stored Procedures" the value of today in all references , Sum the Stock in a table where you have the stocks and put the results In this same table , for example , search the "sum(stock) from stocks" and put in the respective day

the problem is that when it does not find the value puts NULL, what I intend is that it puts 0 when it does not find the sum ... I have tried to search but I am a little lost

Stored Procedure:

UPDATE tabela1 SET nStock=(
SELECT  SUM(stock) as TotalStock
FROM Tabelastock 
INNER JOIN Vis_Armazem ON Tabelastock .Sloc=Vis_Armazem.Sloc 
WHERE Vis_Armazem.mostrar=1 AND Tabelastock.data=(select dateadd(dd,0, cast(getdate() as date))) 
AND Tabelastock.referencia=tabela1 .referencia
group by referencia)
where tabela1.dataTmp=(select dateadd(dd,0, cast(getdate() as date)))
  • Use Isnull(sum(stock), 0) as TotalStock

  • hello yes I’ve tried , however continues to give NULL in some references

  • Use in the set subselect then.

1 answer

0

After some time of research here is :

UPDATE Matrix SET nStock=COALESCE((
SELECT sum(stock) as TotalStock               
FROM stock 
INNER JOIN Vis_Armazem ON stock.Sloc=Vis_Armazem.Sloc 
WHERE Vis_Armazem.mostrar=1 AND stock.data=(select dateadd(dd,0, cast(getdate() as date))) 
AND stock.referencia=Matrix.referencia
group by referencia
),0)
FROM Matrix 
where Matrix.dataTmp=(select dateadd(dd,0, cast(getdate() as date))) 

"COALESCE" works on SELECT integer and replaces with a value if not found, in this case "0"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.