Search code examples
multithreadingsql-server-2008

Multi-threading in SQL Server


Lets say I have a table like:

a     b    c     d    e      f
---------------------------------
1.2  2.3  4.4   5.1  6.7    11.9   
7.2  2.3  4.3   5.1  4.7    3.9   
1.9  5.3  3.3   5.1  3.7    8.9   
5.2  2.7  7.4   9.1  1.7    2.9  

If I have to compute something as the sqrt of the multiplication of the sum of the columns

SQRT(sum(a*a)),SQRT(sum(a*b)),SQRT(sum(a*c)),SQRT(sum(a*d)),SQRT(sum(a*e)),SQRT(sum(a*f)),SQRT(sum(b*b)),SQRT(sum(b*c)),SQRT(sum(b*d))....SQRT(sum(f*f))
  • How could I use threads (in this case I guess 6 threads) to solve this and insert in a new table?
  • And if I do not know the number of columns in the table, is there a way to create threads depending on the number of columns, of course knowing a threshold (for example not more than 10 threads)??

Currently I have something like:

SELECT SQRT(sum(a*a)),SQRT(sum(a*b)), .... ,SQRT(sum(f*f)) INTO TEMP FROM a_table

Solution

  • The problem is that your schema does not match to the type of information you wish to extract which why getting the information you want is such a pain. In this case, the values are not normalized. If you normalize them, the query becomes trivial:

    With Inputs As
        (
        Select 1 As RowNum, 1.2 As a, 2.3 As b, 4.4 As c, 5.1 As d, 6.7 As e, 11.9 As f
        Union All Select 2, 7.2, 2.3, 4.3, 5.1, 4.7, 3.9   
        Union All Select 3, 1.9, 5.3, 3.3, 5.1, 3.7, 8.9   
        Union All Select 4, 5.2, 2.7, 7.4, 9.1, 1.7, 2.9 
        )
        , NormalizedInputs As
        (
        Select RowNum, 'a' As ColName, a As Value From Inputs
        Union All Select RowNum, 'b', b From Inputs
        Union All Select RowNum, 'c', c From Inputs
        Union All Select RowNum, 'd', d From Inputs
        Union All Select RowNum, 'e', e From Inputs
        Union All Select RowNum, 'f', f From Inputs
        )
    Select N1.RowNum, Sqrt( Sum( N1.Value * N2.Value ) )
    From NormalizedInputs As N1
        Left Join NormalizedInputs As N2
            On N2.RowNum = N1.RowNum
                And N2.ColName >= N1.ColName
    Group By N1.RowNum