Insert character into SQL string

David Hall picture David Hall · Jun 25, 2013 · Viewed 44.7k times · Source

I have an nvarchar column I need to insert a hyphen at fixed points within the string. The hyphen need to go between the rightmost character and the next, and again in the 3rd position from the right, such as: column value is

0000050704 

and I need it to be

0000050-70-4

or value is

0555256321 

and it should be

0555256-32-1

Can't see how this is done. Can anyone give me a little help?

Answer

Jaloopa picture Jaloopa · Jun 25, 2013

Assuming the strings can be a variable length, you'll need to use REVERSE() or lots of nasty looking LEN() values in your expression.

declare @txt varchar(100) = '0000050704'

--If using SQL Server, the STUFF() function is your friend
select REVERSE(STUFF(STUFF(REVERSE(@txt), 2, 0, '-'), 5, 0, '-'))

--if not you'll need to concatenate SUBSTRING()s
select REVERSE(SUBSTRING(REVERSE(@txt), 1, 1) + '-' + SUBSTRING(REVERSE(@txt),2, 2) + '-' + SUBSTRING(REVERSE(@txt),4, LEN(@txt)))