A couple of comments:

1) there is no guarantee that the update is acting on a single record. What should happen if your subquery returns more than one record?

2)in the second update you set the field to a constant based on a table join. The subquery is expensive in terms of time and probably unnecessary

It might be better to calculate the result first then update in one step. This might work
DECLARE @result float -- if you are certain there is only one record per condition (primary +key constraints or something -- you can omit this statement and the IF..ELSE block /* SET @result = (SELECT COUNT(*) FROM Calculation D INNER JOIN Lookup_table L ON D.SUM_xi = L.SUM_xi WHERE (D.SUM_xi < 13) AND (D.Key_m = @Count_me)); */ -- try this instead SET @result = (SELECT COUNT(*) FROM Calculation D WHERE (D.SUM_xi < 13) AND (D.Key_m = @Count_me)); IF(@result = 1) begin SET @result = (SELECT D.SUM_wixi + SQRT(D.SUM_wi2xi / D.SUM_xi) * +(L.c - L.SUM_xi) FROM Calculation D INNER JOIN Lookup_table L ON D.SUM_xi = L.SUM_xi WHERE (D.SUM_xi < 13) AND (D.Key_m = @Count_me)); UPDATE Calculation SET Lower_95 = @result, Lower_95_Calc_method = 'UPDATE' WHERE SUM_xi < 13 AND Key_m = @Count_me; SET @Count_me = @Count_me + 1; end ELSE begin -- do something here to indicate multiple or zero records returned end

Update: I just noticed the WHERE condition doesn't require Lookup_table. You could simplify the query to a select on Calculation only. It will save you some time on the lookup. You could even incorporate the lookup back into your original query (but then you would lose some error checking)

PJ
use strict; use warnings; use diagnostics;

In reply to Re: OT: SQL problem by periapt
in thread OT: SQL problem by NodeReaper

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.