Skip to content
Advertisement

SQL Server: Return a string in a specific format

In TSQL, I need to format a string in a predefined format. For eg:

SNO STRING FORMAT OUTPUT
1 A5233GFCOP *XXXXX-XXXXX *A5233-GFCOP
2 K92374 /X-000XXXXX /K-00092374
3 H91543987 XXXXXXXXX H91543987

I am trying with FORMATMESSAGE() built in function.

For ex:

  1. FORMATMESSAGE(‘*%s-%s’,’A5233′,’GFCOP’)
  2. FORMATMESSAGE(‘/%s-000%s’,’K’,’92374′)
  3. FORMATMESSAGE(‘%s’,’H91543987′)

I am able to get the first argument by replace function but issue is second/third/fourth/.. arguments. I don’t know how to count respective X’s between the various delimiters, so that I can use substring to pass in second/third/.. arguments. If I can count the respective # of X’s from the Format column, I feel using substring we can get it but not sure how to count the respective X’s.

Please let me know how to get through it or if there is any other simple approach.

Appreciate your help.

Thanks!

Advertisement

Answer

It’s in theory quite simple, could probably be done set-based using string_split however that’s not ideal as the ordering is not guaranteed. As the strings are fairly short then a scalar function should suffice. I don’t think it can use function in-lining.

The logic is very simple, create a counter for each string, loop 1 character at a time and pull a character from one or the other into the output depending on if the format string is an X or not.

See working Fiddle

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