title: Regexp convert sql LIMIT syntax to SqlServer TOP syntax
body: <p>I have some query string written for PostgreSQL and I have to convert them to SqlServer. I'm using C# 6.</p>
  
  <p>In order to convert from LIMIT syntax to TOP syntax I've written the following simple regex:</p>
  
  <pre><code>SELECT ([\S\s]*)LIMIT (\d+) -&gt; SELECT TOP $2 $1
  </code></pre>
  
  <p>The complete line code is:</p>
  
  <pre><code>return Regex.Replace(query, @"SELECT ([\S\s]*)LIMIT (\d+)", "SELECT TOP $2 $1", RegexOptions.RightToLeft);
  </code></pre>
  
  <p>Now, eveything works fine for simple query but it does not work for subquery: the TOP string is put everytime in the super parent query.</p>
  
  <p>Try for example the following query:</p>
  
  <pre><code>SELECT b3.aaa,
         b3.count
  FROM
  (
      SELECT CONCAT(b.foo / 100.0, '-', (b.foo + 10) / 100.0) AS aaa,
                        COUNT(b.foo) AS count
      FROM
      (
          SELECT b2.foo - (b2.foo % 10) AS foo
          FROM
          (
              SELECT CAST(b.foo * 100 AS INT) AS foo
              FROM eee b
                   INNER JOIN bar f ON b.bar_id = f.id
              WHERE b.foo &lt; 1
                    AND f.nome = 'aaa'
          ) b2
      ) b
      GROUP BY b.foo
      ORDER BY b.foo
      LIMIT 10
  )
  </code></pre>
  
  <p>it is converted to:</p>
  
  <pre><code>SELECT TOP 10 b3.aaa,
         b3.count
  FROM
  (
      SELECT CONCAT(b.foo / 100.0, '-', (b.foo + 10) / 100.0) AS aaa,
                        COUNT(b.foo) AS count
      FROM
      (
          SELECT b2.foo - (b2.foo % 10) AS foo
          FROM
          (
              SELECT CAST(b.foo * 100 AS INT) AS foo
              FROM eee b
                   INNER JOIN bar f ON b.bar_id = f.id
              WHERE b.foo &lt; 1
                    AND f.nome = 'aaa'
          ) b2
      ) b
      GROUP BY b.foo
      ORDER BY b.foo
  )
  </code></pre>
  
  <p>while I'd like to have</p>
  
  <pre><code>SELECT b3.aaa,
         b3.count
  FROM
  (
      SELECT TOP 10 CONCAT(b.foo / 100.0, '-', (b.foo + 10) / 100.0) AS aaa,
                        COUNT(b.foo) AS count
      FROM
      (
          SELECT b2.foo - (b2.foo % 10) AS foo
          FROM
          (
              SELECT CAST(b.foo * 100 AS INT) AS foo
              FROM eee b
                   INNER JOIN bar f ON b.bar_id = f.id
              WHERE b.foo &lt; 1
                    AND f.nome = 'aaa'
          ) b2
      ) b
      GROUP BY b.foo
      ORDER BY b.foo
  )
  </code></pre>
  
  <p>How should I write the regex I need?</p>