Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing leading characters in string

How would i replace first two characters if they are zeros?

Example:

 1. 00001
 2. 00123
 3. 02451

Should be:

 1. 11001
 2. 11123
 3. 02451

EDIT: Forgot to mention i need this in select clause (in a view) Thanx.

like image 318
no9 Avatar asked Jan 08 '13 14:01

no9


People also ask

How do you remove leading characters from a string?

Use the TRIM() function with the LEADING keyword to remove characters at the beginning of a string. TRIM() allows you to remove specific character(s) or space(s) from the beginning, end, or both ends of a string.

Which function is used to remove leading and trailing characters in a string?

newStr = strip( str ) removes all consecutive whitespace characters from the beginning and end of str , and returns the result as newStr . newStr = strip( str , side ) removes all consecutive whitespace characters from the side specified by side . The side argument can be 'left' , 'right' , or 'both' .

How do I remove or replace characters in a string?

Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


2 Answers

update  YourTable
set     col1 = '11' + substring(col1, 3, len(col1)-2)
where   col1 like '00%'

In a view, you could do it like:

select   case
         when col1 like '00%' then stuff(col1, 1, 2, '11')
         else col1
         end
from     YourTable;

Live example at SQL Fiddle.

like image 85
Andomar Avatar answered Oct 17 '22 02:10

Andomar


declare @a varchar(10)

select @a='01123'

Select case when LEFT(@a,2)='00' then STUFF(@a,1,2,'11') else @a end
like image 30
bummi Avatar answered Oct 17 '22 03:10

bummi