Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert character into SQL string

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?

like image 272
David Hall Avatar asked Jun 25 '13 14:06

David Hall


People also ask

How do I add a character to a string in SQL?

MySQL INSERT() Function The INSERT() function inserts a string within a string at the specified position and for a certain number of characters.

What is the use of %% in SQL?

The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

What is %s in SQL statement?

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.


2 Answers

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)))
like image 112
Jaloopa Avatar answered Sep 19 '22 13:09

Jaloopa


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
like image 41
merrais Avatar answered Sep 22 '22 13:09

merrais