Removing leading zeroes from a field in a SQL statement - sql

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.

Related

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')

find the len of the field and update the field if the len is less than 8 in the column

I Have a column policy_date with datatype varchar
Policy_date
-----------
A1999062
20010405
I would like to update the data with
case when isnumeric(policy_date) = 0 then trim the alphabet (1999062) and check if the len is less than 8 then make it as NULL else Policy_date.
NOTE: i have to convert the date field to date datatype instead of varchar.
My out put should look like:
Policy_Date
-----------
NULL
2001-04-05
Can anyone write the sql case statement .
Thank You,
Swathi.
Based on your comment you just want to remove the first character position if it is alpha. That eliminates the need for a function / CLR call. If this requirement changes you will need to create a function to strip the chars but the rest of the query will work.
Create Table #Test (PolicyDate Varchar(8000))
Insert #Test Values ('A19990602')
Insert #Test Values ('A1999062')
Insert #Test Values ('20010405')
Select Convert(Date,
Case When IsNumeric(PolicyDate) = 0 Then
Case When Len(PolicyDate) < 9 Then Null
Else Right(PolicyDate, Len(PolicyDate) -1) End
Else PolicyDate
End) PolicyDate2
From #Test
Example function, there are many topics available on which approach is faster.
CREATE Function [fnRemoveNonNumericCharacters](#strText VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
WHILE PATINDEX('%[^0-9]%', #strText) > 0
BEGIN
SET #strText = STUFF(#strText, PATINDEX('%[^0-9]%', #strText), 1, '')
END
RETURN #strText
END
ps. I used IsNumeric() because that is what you said you wanted to implement. However take note that by design certian characters can be included and still have the function return that it is a number. IsNumeric($1,230.54) will return a 1. If that is a concern then use an alternative, for example TRY_PARSE(PolicyDate as int) for sql2012 and above.
You could take the rightmost 8 characters, inject two hyphens with stuff(), and check if that is a valid date with isdate(). If so, repeat the same and make the conversion with cast():
select case when len(policy_date) >= 8
and isdate(stuff(stuff(right(policy_date, 8), 7, '-'), 5, '-')) then
cast(stuff(stuff(right(policy_date, 8), 7, '-'), 5, '-') as datetime)
end

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.

How to remove the first character if it is a specific character in 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

Most efficient method for adding leading 0's to an int in sql

I need to return two fields from a database concatenated as 'field1-field2'. The second field is an int, but needs to be returned as a fixed length of 5 with leading 0's. The method i'm using is:
SELECT Field1 + '-' + RIGHT('0000' + CAST(Field2 AS varchar),5) FROM ...
Is there a more efficient way to do this?
That is pretty much the way: Adding Leading Zeros To Integer Values
So, to save following the link, the query looks like this, where #Numbers is the table and Num is the column:
SELECT RIGHT('000000000' + CONVERT(VARCHAR(8),Num), 8) FROM #Numbers
for negative or positive values
declare #v varchar(6)
select #v = -5
SELECT case when #v < 0
then '-' else '' end + RIGHT('00000' + replace(#v,'-',''), 5)
Another way (without CAST or CONVERT):
SELECT RIGHT(REPLACE(STR(#NUM),' ','0'),5)
If you can afford/want to have a function in your database you could use something like:
CREATE FUNCTION LEFTPAD
(#SourceString VARCHAR(MAX),
#FinalLength INT,
#PadChar CHAR(1))
RETURNS VARCHAR(MAX)
AS
BEGIN
RETURN
(SELECT Replicate(#PadChar, #FinalLength - Len(#SourceString)) + #SourceString)
END
I would do it like this.
SELECT RIGHT(REPLICATE('0', 5) + CAST(Field2 AS VARCHAR(5),5)
Not necessarily all that "Easier", or more efficient, but better to read. Could be optimized to remove the need for "RIGHT"
If you want to get a consistent number of total strings in the final result by adding different number of zeros, here is a little bit modification (for vsql)
SELECT
CONCAT(
REPEAT('0', 9-length(TO_CHAR(var1))),
CAST(var1 AS VARCHAR(9))
) as var1
You can replace 9 by any number for your need!
BRD