Skip to content
Advertisement

Port MySQL script to MS SQL -> simultaneous data asignement and retrieval

I have been trying to make this work for hours but I can’t really find a way to do it. I have a MySQL script that I need to migrate to MS SQL 2014, however, I can’t seem to make it work. As far as I have understood, the big issue is that MySQL allows this kind of instructions:

SELECT @row_number = @row_number + 1, hora_int FROM table1;

where you assign a value at the same time you retrieve data, but MS SQL does not.

I have a relatively big script which has that issue:

SELECT GLOBAL.year, GLOBAL.month, '1111111' as metric_id, GLOBAL.margin as metric_value FROM (SELECT A.year,
         A.month,
         CASE
           WHEN A.month = 1 THEN (@csum_fdo := A.imp)
           ELSE (@csum_fdo := @csum_fdo + A.imp) END as margin
  FROM (SELECT Act.year, Act.month, Act.imp - Pas.imp as imp
        FROM (SELECT year(tie.date) as year, month(tie.date) as month, sum(importe) as imp
              FROM accounting con,
                   dim_time tie,
                   dim_account cta
              WHERE con.account_date = tie.date
                AND con.account = cta.nivel_10
                AND cta.level_id = '2'
                AND con.subtype_id <> 'O'
              GROUP BY year(tie.date),
                       month(tie.date)) Act,
             (SELECT year(tie.date) as year, month(tie.date) as month, sum(importe) * -1 as imp
              FROM accounting con,
                   dim_time tie,
                   dim_account cta
              WHERE con.account_date = tie.date
                AND con.account = cta.nivel_10
                AND cta.level_id = '3'
                AND con.subtype_id <> 'O'
              GROUP BY year(tie.date),
                       month(tie.date)) Pas
        WHERE Act.year = Pas.year
          AND Act.month = Pas.month) A,
       (SELECT @csum_fdo := 0) E) GLOBAL

Can anybody point me in the direction of what I have to do to recreate the code in MS SQL? Thank you all in advance

Advertisement

Answer

My big problem lied in this line:

CASE
           WHEN A.month = 1 THEN (@csum_fdo := A.imp)
           ELSE (@csum_fdo := @csum_fdo + A.imp) END as margin

but as Gordon Linoff pointed me. this problem could be solved with window functions, the right translation od that function is:

SUM(A.imp) OVER(PARTITION BY A.Year ORDER BY A.month) as margin

it ended up being easier than I thought
Thanks a lot and I hope it can help others as well

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement