Skip to content

Instantly share code, notes, and snippets.

@nosilex
Last active August 29, 2015 14:09
Show Gist options
  • Save nosilex/3229736bf7f58cda93ed to your computer and use it in GitHub Desktop.
Save nosilex/3229736bf7f58cda93ed to your computer and use it in GitHub Desktop.
Convert MySQL query with LIMIT to work in MS SQL Server
/**
* Convert MySQL query with LIMIT to work in MS SQL Server
* Author: Elison Gomes
*
* @param string $query
* @return string
*
* Ex: convertLimit("select id, name from person limit 0, 10");
*/
function convertLimit($query) {
$query = trim($query);
if (!preg_match("/(limit) (\d+)(\D+)(\d+)/i", $query, $matches, PREG_OFFSET_CAPTURE)) {
return $query;
}
$page = $matches[2][0];
$pageSize = $matches[4][0];
$query = substr($query, 0, $matches[0][1]);
/* Field for ORDER BY */
if (strripos($query, 'order by') === false) {
$orderBy = substr($query, strpos($query, ' '), strpos($query, ',')-strpos($query, ' '));
} else {
$orderByAt = strripos($query, 'order by');
$orderBy = substr($query, $orderByAt+8, strlen($query));
$query = substr($query, 0, $orderByAt);
}
$query = "
WITH OrderedOrders AS
(
".substr_replace($query, " ROW_NUMBER() OVER (ORDER BY {$orderBy}) AS 'RowNumber', ", strpos($query, ' '), 0)."
)
SELECT *
FROM OrderedOrders
WHERE RowNumber BETWEEN ".($page+1)." AND ".($page+$pageSize).";
";
return $query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment