Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace first occurrence of '.' in sql String

Let's say we saved inside a table the following values on Column as String:

 Select ValuesT from TableT; 

  ValuesT
-9.827.08
-9.657.40
-80.000.00
-8.700.00
-8.542.43
-8.403.00

How could be replaced with nothing only the first occurrence of '.' (dot) from the string?

Ex: for -9.827.08 should be -9827.08

I tried with stuff function but this won't work for -80.000.00

 select stuff( ValuesT ,3,1,'') from TableT
like image 963
Pirvu Georgian Avatar asked Nov 21 '16 09:11

Pirvu Georgian


People also ask

How to replace only first occurrence of string in SQL?

Perform search/replace for only the first occurrence of a character in MySQL table records? You can achieve this with the help of CONCAT() along with REPLACE() function. To find the first occurrences you need to use INSTR() function.

How do you find first occurrence of a character in a string SQL?

The INSTR functions search string for substring . The function returns an integer indicating the position of the character in string that is the first character of this occurrence.


2 Answers

Use STUFF function

Find the first occurance of . using CHARINDEX and remove it using STUFF

SELECT STUFF(valuesT, CHARINDEX('.', valuesT), 1, '')
FROM TableT
like image 57
Pரதீப் Avatar answered Nov 16 '22 03:11

Pரதீப்


Another way.

WITH sampleData AS
( 
  SELECT val FROM (VALUES 
  ('-9.827.08'), ('-9.657.40'), ('-80.000.00'), ('-8.700.00'),
  ('-8.542.43'),('-8.403.00')) x(val)
)
SELECT SUBSTRING(val, 1, d1.d-1)+SUBSTRING(val, d1.d+1, 100)
FROM sampleData
CROSS APPLY (VALUES (CHARINDEX('.',val))) d1(d);

Its a little more code but just as efficient. There's a lot more you can do with this technique.

like image 41
Alan Burstein Avatar answered Nov 16 '22 04:11

Alan Burstein