Our database has over 100k products in it and we feed to our clients every 10 mins a report with prices and many other data. I am currently trying to re-write the queries to streamline the whole process. At this point I should point out my SQL knowledge is self taught over the last few months so just a novice really.
The part I am really banging my head against a wall is:
The following WHERE
statement returns results event when there have been no changes and I cant work out want is causing it, or what I am doing wrong.
UPDATE variant_external_analysis
SET vaea_d_1 = GETDATE(), -- last updated
vaea_n_3 = ROUND((vaea_n_12 + vaea_n_18) * (SELECT CAST(jn_our_ref AS FLOAT) FROM job_number WHERE jn_id='20'),2) -- product price
FROM variant_external_analysis
JOIN variant_detail ON vad_id = vaea_vad_id
WHERE
((vaea_n_3 <> ROUND((vaea_n_12 + vaea_n_18) * (SELECT CAST(jn_our_ref AS FLOAT) FROM job_number WHERE jn_id='20'),2)) -- has price change
OR vaea_n_3 IS NULL) -- Is price field empty
AND vad_variant_code BETWEEN 1000 AND 990000 -- product range for client
This should update the price vaea_n_3
if it has changed or IS NULL
and at the same time change the last updated date vaea_d_1
under the same conditions.
However for some reason even when I run the query multiple times in a row it still returns about 6k products even though vaea_n_3
has not changed for any product and none have a NULL
value
I need vaea_d_1
so the price file we send to our clients can just include products where the price has changed rather than all 100k products.
Can anyone please what is wrong with this simple looking query?
SOLVED THANK YOU
From a combination of a few different peoples answers it proved that the problem was with the
(SELECT CAST(jn_our_ref AS FLOAT) FROM job_number WHERE jn_id='20')
So I have re-written the query and changed where/how I store my global variables:
UPDATE variant_external_analysis
SET vaea_d_1 = GETDATE(), -- last updated
vaea_n_3 = ROUND((vaea_n_12 + vaea_n_18) * jna_n_7, 2) -- product price
FROM job_number_analysis, variant_external_analysis
JOIN variant_detail ON vad_id = vaea_vad_id
WHERE ((vaea_n_3 <> ROUND((vaea_n_12 + vaea_n_16) * jna_n_7, 2)) -- has price changed
OR vaea_n_3 IS NULL) -- Is price field empty
AND vad_variant_code BETWEEN 1000 AND 990000 -- product range for client
AND jna_jn_id = 59
This now works correctly and only updates when something has changed. Thank you to everyone of put ideas forward.