Daily Archives: Sep 23, 2014

Reverse the string with a delimiter (Recursive CTE) 1

In this article, we are going to learn how we can “Reverse string in sql server”¬†with some specified delimiter e.g, based on space or comma or tilde or semi-colon etc;

If you will input “A B C”, the output should be as “C B A”


Lets assume space as a delimiter in this example and now to achieve our goal, we will use a recursive CTE(Common table expression). Just have a look on below code and then we will discuss in detail;


In this demo, i have used a common table expression with recursion. A recursive CTE consists of three parts;

  1. Anchor part – Part of CTE above UNION ALL
  2. Recursive part – Part below UNION ALL which will be called recursively
  3. Condition to break – Condition to break the recursion where certain condition met

In sample code, i have used a trick that in anchor … More