Skip to content
Advertisement

SQL Server – Ordering Combined Number Strings Prior To Column Insert

I have 2 string columns (thousands of rows) with ordered numbers in each string (there can be zero to ten numbers in each string). Example:

The end result is to combine these 2 columns, sort the numbers in ascending order and then put each number into individual columns (smallest, 2nd smallest etc). e.g. Colstring1 is 1;3;5;12; and ColString2 is 4;6; needs to return 1;3;4;5;6;12; which I then use xml to allocated into columns.

Everthing works fine using xml apart from the step to order the numbers (i.e I’m getting 1;3;5;12;4;6; when I combine the strings i.e. not in ascending order).
I’ve tried put them into a JSON array first to order, thinking I could do a top[1] etc but that did not work. Any help on how to combine the 2 columns and order them before inserting into columns:

Steps so far: Example data:

XML Approach (Combines strings and puts into columns but not in the correct order):

Current Output: numbers not in correct order,

Desired Output: numbers in ascending order.

JSON Approach: combines the columns into a JSON array but I still can’t order correctly when in JSON format.

Any help will be greatly appreciated whether there is a way to order the xml or JSON string prior to entry. Happy to consider an alternative way if there is an easier solution.

Advertisement

Answer

While waiting for a DDL and sample data population, etc., here is a conceptual example for you. It is using XQuery and its FLWOR expression.

CTE does most of the heavy lifting:

  • Concatenates both columns values into one string. CONCAT() function protects against NULL values.
  • Converts it into XML data type.
  • Sorts XML elements by converting their values to int data type in the FLWOR expression.
  • Filters out XML elements with no legit values.

The rest is trivial.

SQL

Output

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