I am trying to remove alphabets, space from left, right and in between, preceding zeros, and all the characters after special characters(comma,semicolon,backslash, forward slash)
I have a column which contains value like below :
051 765 999
MK00564123
KJ786453425/9
432563542/3
096745632
53452BMG441,8
I am trying to remove alphabets and space from left and right from the value for those value containing alphabets in the value and also preceeding 0.
Expected Output:
51765999
564123
96745632
Also I am trying to remove everything after special character in the column(comma,semicolon,backslash, forward slash):
Expected Output:
786453425
432563542
53452441
Final Output:
51765999
564123
96745632
786453425
432563542
53452441
I have created the fiddle but not getting expected output as shown below:
Fiddle: http://sqlfiddle.com/#!18/0b383/1123
Can someone please help me to identify what is the issue and how can I get expected output?
6条答案
按热度按时间nkcskrwz1#
One way of doing this is
and then
,;\/
(if present)TRANSLATE
function as in edit history)( DB Fiddle )
ilmyapht2#
To trim leading zeroes from a numeric string:
Change your return to:
See live demo.
This works by changing all
0
to a space, left trimming, then changing all space back to0
.Of course if SQL Server ever gets around to supporting
REGEXP_REPLACE()
it would be trivial:nwlls2ji3#
This function can be easily inlined.
42fyovps4#
Here You can use this function which uses
PATINDEX
.And this is a test.
acruukt95#
One method would be to use
PATINDEX
to find the position of the first non-alphanumeric or space character, and get theLEFT
most characters up to that point.Then I use a helper function I wrote which replaces characters that fit a certain pattern with another character. As you are on SQL Server 2016, then you'll need to use the XML version of it, as
STRING_AGG
was added in 2017. (note that the helper function also uses a tally helper function, asGENERATE_SERIES
was added in 2022).Finally I convert the value to a
bigint
to trim leading zeroes.This'll certainly work on versions as old as SQL Server 2012 for strings where the numbers to return are 18 numbers or less.
If the numerical value would be greater than 9,223,372,036,854,775,807 then you could use
PATINDEX
andSTUFF
to remove the leading0
characters.5ssjco0h6#
SQL Fiddle
MS SQL Server 2017 Schema Setup:
Query 1:
Results:
Query 2:
Results:
Query 3:
Results: