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?
MySQL INSERT() Function The INSERT() function inserts a string within a string at the specified position and for a certain number of characters.
The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.
Placeholders. pixel13 commented 16 years ago. They're just placeholders for the values that follow in the command (e.g. in db_query). You must use %d for integer values and %s for string values. You can also use %f for a floating point value, %b for binary data and %% just to insert a percent symbol.
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)))
You can use this easy function:
CREATE FUNCTION [dbo].[SetHyphen] (@S varchar(50)) RETURNS varchar(52)
BEGIN
RETURN STUFF(STUFF(@S,LEN(@S)-2,0,'-'),LEN(@S)+1,0,'-')
END
For example:
select [dbo].[SetHyphen]('0000050704')
0000050-70-4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With