How to remove the first character if it is a specific character in SQL - sql

I currently have a table Telephone it has entries like the following:
9073456789101
+773456789101
0773456789101
What I want to do is remove only the 9 from the start of all the entries that have a 9 there but leave the others as they are.
any help would be greatly appreciated.

While all other answer are probably also working, I'd suggest to try and use STUFF function to easily replace a part of the string.
UPDATE Telephone
SET number = STUFF(number,1,1,'')
WHERE number LIKE '9%'
SQLFiddle DEMO

Here is the code and a SQLFiddle
SELECT CASE
WHEN substring(telephone_number, 1, 1) <> '9'
THEN telephone_number
ELSE substring(telephone_number, 2, LEN(telephone_number))
END
FROM Telephone

Update Telephone set number = RIGHT(number,LEN(number)-1) WHERE number LIKE '9%';

I recently solved a similar problem with a combination of RIGHT(), LEN() & PATINDEX(). PATINDEX will return the integer 1 when it finds a 9 as the first character and 0 otherwise. This method allows all records to be returned at once without a CASE WHEN statement.
SELECT
RIGHT(number, LEN(number) - PATINDEX('9%', number))
FROM Telephone

UPDATE dbo.Telephone
SET column_name = SUBSTRING(column_name, 2, 255)
WHERE column_name LIKE '9%';

Stuff is a great function for this. However, using it with an update statement with a where clause is great, but what if I was doing an insert, and I needed all of the rows inserted in one pass. The below will remove the first character if it is a period, does not use the slower case statement, and converts nulls to an empty string.
DECLARE #Attachment varchar(6) = '.GIF',
#Attachment2 varchar(6)
SELECT
#Attachment2 = ISNULL(ISNULL(NULLIF(LEFT(#Attachment, 1), '.'), '') + STUFF(#Attachment, 1, 1, ''), '')
SELECT
#Attachment2

DECLARE #STR nvarchar(200) = 'TEST'
SET #STR = STUFF(#STR,1,1,'')
PRINT #STR
Result will be "EST"

You can use replace in select statement instead of where or update
SELECT REPLACE(REPLACE('_'+number,'_9',''),'_','') FROM #tbl

Related

in SQL how can I remove the first 3 characters on the left and everything on the right after an specific character

In SQL how can I remove (from displaying on my report no deleting from database) the first 3 characters (CN=) and everything after the comma that is followed by "OU" so that I am left with the name and last name in the same column? for example:
CN=Tom Chess,OU=records,DC=1234564786_data for testing, 1234567
CN=Jack Bauer,OU=records,DC=1234564786_data for testing, 1234567
CN=John Snow,OU=records,DC=1234564786_data for testing, 1234567
CN=Anna Rodriguez,OU=records,DC=1234564786_data for testing, 1234567
Desired display:
Tom Chess
Jack Bauer
John Snow
Anna Rodriguez
I tried playing with TRIM but I don't know how to do it without declaring the position and with names and last names having different lengths I really don't know how to handle that.
Thank you in advance
Update: I wonder about an approach of using Locate to match the position of the comma and then feed that to a sub-string. Not sure if a approach like would work and not sure how to put the syntax together. What do you think? will it be a feasible approach?
You can try this one SUBSTRING(ColumnName, 4, CHARINDEX(',', ColumnName) - 4)
In Postgres, you could use split_part() assuming no name contains a ,
select substr(split_part(the_column, ',', 1), 4)
from ...
Db2 11.x for LUW:
with tab (str) as (values
' CN = Tom Chess , OU = records,DC=1234564786_data for testing, 1234567'
, 'CN=Jack Bauer,OU=records,DC=1234564786_data for testing, 1234567'
, 'CN=John Snow,OU=records,DC=1234564786_data for testing, 1234567'
, 'CN=Anna Rodriguez,OU=records,DC=1234564786_data for testing, 1234567'
)
select REGEXP_REPLACE(str, '^\s*CN\s*=\s*(.*)\s*,\s*OU\s*=.*', '\1')
from tab;
Note, that such a regex pattern allows an arbitrary number of spaces as in the 1-st record of example above.
In Oracle 11g, it might work.
REGEXP_SUBSTR(REGEXP_SUBSTR(COLUMN_NAME, '[^CN=]+',1,1),'[^,OU]+',1,1)
I think there has to be a loop to handle this. Here's SQL Server function that will parse this out. (I know the question didn't specify SQL Server, but it's an example of how it can be done.)
select dbo.ScrubFieldValue(value) from table will return what you're looking for
CREATE FUNCTION ScrubFieldValue
(
#Input varchar(8000)
)
RETURNS varchar(8000)
AS
BEGIN
DECLARE #retval varchar(8000)
DECLARE #charidx int
DECLARE #remaining varchar(8000)
DECLARE #current varchar(8000)
DECLARE #currentLength int
select #retval = ''
select #remaining = #Input
select #charidx = CHARINDEX('CN=', #remaining,2)
while(LEN(#remaining) > 0)
BEGIN
--strip current row from remaining
if (#charidx > 0)
BEGIN
select #current = SUBSTRING(#remaining, 1, #charidx - 1)
END
else
BEGIN
select #current = #remaining
END
select #currentLength = LEN(#current)
-- get current name
select #current = SUBSTRING(#current, 4, CHARINDEX(',OU', #current)-4)
select #retval = #retval + #current + ' '
-- strip off current from remaining
select #remaining =substring(#remaining,#currentLength + 1,
LEN(#remaining) - #currentLength)
select #charidx = CHARINDEX('CN=', #remaining,2)
END
RETURN #retval
END
On my version of DB2 for Z/OS CHARINDEX throws a syntax error. Here are two ways to work around that.
SUBSTRING(ColumnName, 4, INSTR(ColumnName,',',1) - 4)
SUBSTRING(ColumnName, 4, LOCATE_IN_STRING(ColumnName,',') - 4)
I should add that the version is V12R1
If input str is wellformed (i.e. looks like your sample data without any additional tokens such as space), you could use something like:
substr(str,locate('CN=', str)+length('CN='), locate(',', str)-length('CN=')-1)
If your Db2 version support REGEXP, that's a better choice.

How to remove character from an SQL query in where condition

I got some dirty database of SQL to do a task. I have a column which can have data from different format like the following:
format 1 = 0000-0000000
format 2 = 0000.0000000
format 3 = 00000000000
The format 3 is a good format for my query.
$sql = "SELECT * from table where col='00000000000'"
I want to to remove these character in select query without disturbing the actual data.
Seems you need Replace function. Just remove extra symbols during comparison
SELECT * from table
where replace(replace(col, '-', ''), '.', '') ='00000000000'
There is a function to format the string:
create FUNCTION [dbo].[fn_StripString](#value as varchar(80), #KeepValues as varchar(80))
RETURNS varchar(80)
AS
begin
While PatIndex(#KeepValues, #value) > 0
Set #value = Stuff(#Valor, PatIndex(#KeepValues, #value), 1, '')
return #value
end
Then, assuming you just want numeric values:
SELECT *
from table
where dbo.fn_StripString(col, '%[^0-9]%') = '00000000000'
Use IN query
Select * from table where col in ('00000000000','0000.0000000','0000-0000000')

Replace Last character in SQL Server 2008

I am working with SQL server 2008, and facing problem about character replacement.
If I use
SELECT REPLACE(MYWORD,0,1) FROM MYTABLE
It is replacing all 0 into 1, I just want to replace Last character Like MYWORD = "ERMN0" so it will be MYWORD = "ERMN1"
using STUFF, which, IMO, ends up being most readable:
DECLARE #MyWORD VARCHAR(20) = 'ABCDEF123'
SELECT STUFF(#MyWORD, LEN(#MyWORD), 1, '2')
output:
ABCDEF122
You may use combination of LEFT, RIGHT, and CASE.
You need to use CASE to check the most RIGHT character whether it's a 0 or not and replace it with 1. And at last, combine it with the LEFT part (after being separated from the last character) of the MYWORD string.
However, depending on your requirement, it may have a drawback.
When there is a word ending with 10, it would also be replaced.
SELECT LEFT(MYWORD,LEN(MYWORD)-1) + CASE RIGHT(MYWORD,1) WHEN '0' THEN '1' ELSE RIGHT(MYWORD,1) END
Try this.
SELECT LEFT('ERMN0', Len('ERMN0')-1)
+ Replace(RIGHT('ERMN0', 1), 0, 1)
OUTPUT : ERMN1
In your case
SELECT LEFT(MYWORD, Len(MYWORD)-1)
+ Replace(RIGHT(MYWORD, 1), 0, 1) as [REPLACED] FROM MYTABLE
Try this
SELECT SUBSTRING(MYWORD, 1, LEN(MYWORD) - 1) +
REPLACE(SUBSTRING(MYWORD, LEN(MYWORD), LEN(MYWORD)), 0, 1) FROM MYTABLE
This will work
SELECT LEFT ('ERMN0' , Len('ERMN0') -1 ) + REPLACE(Right('ERMN0', 1), '0','1')
Or in your case
SELECT LEFT (MYWORD , Len(MYWORD) -1 ) + REPLACE(Right(MYWORD, 1), '0','1') AS MYWORD FROM MYTABLE
this is also use full to replace letters from end
It is used from replacing characters from end 1,2 or N
Declare #Name nvarchar(20) = 'Bollywood'
select #Name = REPLACE(#Name, SUBSTRING(#Name, len(#Name) - 1, 2), 'as')
SELECT #Name
output is "Bollywoas"
Here best part is you can repalce as many character from last you needed.

Trim Special Char from SQL String

I am using SQL Server 2008
I have sql string in column with ; separated values. How i can trim the below value
Current string:
;145615;1676288;178829;
Output:
145615;1676288;178829;
Please help with sql query to trim the first ; from string
Note : The first char may be or may not be ; but if it is ; then only it should trim.
Edit: What i had tried before, although it doesn't make sense after so many good responses.
DECLARE
#VAL VARCHAR(1000)
BEGIN
SET #VAL =';13342762;1334273;'
IF(CHARINDEX(';',#VAL,1)=1)
BEGIN
SELECT SUBSTRING(#VAL,2,LEN(#VAL))
END
ELSE
BEGIN
SELECT #VAL
END
END
SELECT CASE WHEN col LIKE ';%'
THEN STUFF(col,1,1,'') ELSE col END
FROM dbo.table;
Just check the first character, and if it matches, start from the second character:
SELECT CASE WHEN SUBSTRING(col,1,1) = ';'
THEN SUBSTRING(col,2,LEN(col))
ELSE col
END AS col
Here's an example:
DECLARE #v varchar(10)
SET #v = ';1234'
SELECT
CASE
WHEN LEFT(#v,1) = ';' THEN RIGHT(#v, LEN(#v) - 1)
ELSE #v
END
A further development on #Aaron Bertrand's answer:
SELECT
STUFF(col, 1, PATINDEX(';%', col), '')
FROM ...
PATINDEX is similar to LIKE in that it uses a pattern search, but being a function it also returns the position of the first match. In this case, since we a looking for a ; specifically at the beginning of a string, the position returned is going to be either 1 (if found) or 0 (if not found). If it is 1, the STUFF function will delete 1 character at the beginning of the string, and if the position is 0, STUFF will delete 0 characters.

Removing leading zeroes from a field in a SQL statement

I am working on a SQL query that reads from a SQLServer database to produce an extract file. One of the requirements to remove the leading zeroes from a particular field, which is a simple VARCHAR(10) field. So, for example, if the field contains '00001A', the SELECT statement needs to return the data as '1A'.
Is there a way in SQL to easily remove the leading zeroes in this way? I know there is an RTRIM function, but this seems only to remove spaces.
select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
select replace(ltrim(replace(ColumnName,'0',' ')),' ','0')
You can use this:
SELECT REPLACE(LTRIM(REPLACE('000010A', '0', ' ')),' ', '0')
I had the same need and used this:
select
case
when left(column,1) = '0'
then right(column, (len(column)-1))
else column
end
select substring(substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), 20),
patindex('%[^0]%',substring('B10000N0Z', patindex('%[0]%','B10000N0Z'),
20)), 20)
returns N0Z, that is, will get rid of leading zeroes and anything that comes before them.
If you want the query to return a 0 instead of a string of zeroes or any other value for that matter you can turn this into a case statement like this:
select CASE
WHEN ColumnName = substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
THEN '0'
ELSE substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
END
In case you want to remove the leading zeros from a string with a unknown size.
You may consider using the STUFF command.
Here is an example of how it would work.
SELECT ISNULL(STUFF(ColumnName
,1
,patindex('%[^0]%',ColumnName)-1
,'')
,REPLACE(ColumnName,'0','')
)
See in fiddler various scenarios it will cover
https://dbfiddle.uk/?rdbms=sqlserver_2012&fiddle=14c2dca84aa28f2a7a1fac59c9412d48
You can try this - it takes special care to only remove leading zeroes if needed:
DECLARE #LeadingZeros VARCHAR(10) ='-000987000'
SET #LeadingZeros =
CASE WHEN PATINDEX('%-0', #LeadingZeros) = 1 THEN
#LeadingZeros
ELSE
CAST(CAST(#LeadingZeros AS INT) AS VARCHAR(10))
END
SELECT #LeadingZeros
Or you can simply call
CAST(CAST(#LeadingZeros AS INT) AS VARCHAR(10))
Here is the SQL scalar value function that removes leading zeros from string:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Vikas Patel
-- Create date: 01/31/2019
-- Description: Remove leading zeros from string
-- =============================================
CREATE FUNCTION dbo.funRemoveLeadingZeros
(
-- Add the parameters for the function here
#Input varchar(max)
)
RETURNS varchar(max)
AS
BEGIN
-- Declare the return variable here
DECLARE #Result varchar(max)
-- Add the T-SQL statements to compute the return value here
SET #Result = #Input
WHILE LEFT(#Result, 1) = '0'
BEGIN
SET #Result = SUBSTRING(#Result, 2, LEN(#Result) - 1)
END
-- Return the result of the function
RETURN #Result
END
GO
To remove the leading 0 from month following statement will definitely work.
SELECT replace(left(Convert(nvarchar,GETDATE(),101),2),'0','')+RIGHT(Convert(nvarchar,GETDATE(),101),8)
Just Replace GETDATE() with the date field of your Table.
To remove leading 0, You can multiply number column with 1
Eg: Select (ColumnName * 1)
select CASE
WHEN TRY_CONVERT(bigint,Mtrl_Nbr) = 0
THEN ''
ELSE substring(Mtrl_Nbr, patindex('%[^0]%',Mtrl_Nbr), 18)
END
you can try this
SELECT REPLACE(columnname,'0','') FROM table
I borrowed from ideas above. This is neither fast nor elegant. but it is accurate.
CASE
WHEN left(column, 3) = '000' THEN right(column, (len(column)-3))
WHEN left(column, 2) = '00' THEN right(a.column, (len(column)-2))
WHEN left(column, 1) = '0' THEN right(a.column, (len(column)-1))
ELSE
END
select ltrim('000045', '0') from dual;
LTRIM
-----
45
This should do.