Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

concat two strings and put smaller string at first in sql server

for concating two varchars from columns A and B ,like "1923X" and "11459" with the hashtag, while I always want the smallest string become at first, what should I do in SQL server query?

inputs:
Two Columns

A="1923X"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

B="11459"

procedure:

while we are checking two inputs from right to left, in this example the second character value in B (1) is smaller than the second character in A (9) so B is smaller.

result: new column C

"11459#1923X"

>Solution :

Original answer:

If you need to order the input strings, not only by second character, STRING_AGG() is also an option:

DECLARE @a varchar(5) = '1923X'
DECLARE @b varchar(5) = '11459'

SELECT STRING_AGG(v.String, '#') WITHIN GROUP (ORDER BY v.String) AS Result
FROM (VALUES (@a), (@b)) v (String)

Output:

Result
11459#1923X

Update:

You changed the requirements (now the strings are stored in two columns), so you need a different statement:

SELECT 
   A, 
   B, 
   C = (
      SELECT STRING_AGG(v.String, '#') WITHIN GROUP (ORDER BY v.String)
      FROM (VALUES (A), (B)) v (String)
   )
FROM (VALUES ('1923X', '11459')) t (a, b)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading