I'm trying to change a field's value where the leading zeros need to be replaced with an _
. Examples:
000123 should be ___123
001234 should be __1234
0012004 should be __12004.
I thought it would have been simple but can't figure it out.
Appreciate all the help i can get!
I tried a REPLACE function but that would replace all zeroes, I only want the leading zeroes replaced
4条答案
按热度按时间laawzig21#
With mssql I'd suggest to write an according function, which first uses
LTRIM
to remove the leading (and only the leading) zeros. And then usesREPLICATE
to create the respective number of underscores.You can also do without the extra
@trimmed
but then you would need to executeLTRIM
twiceWhich you then can use as
tv6aics12#
use
try_cast
to make it an INT, then useSTR
to make it a right-aligned string of the appropriate length, then replace spaces with underscores:rur96b6h3#
https://dbfiddle.uk/-xUtQ_he
This is pure character manipulation. Find the index of the first non-zero character and remove everything before that via
stuff()
. Then you can use the standard left-padding technique of prepending underscores and keeping the same number of characters as the original string. This should work across all versions of SQL Server. This is a single inline expression, no casting is involved and no function installations are required.To handle a string of all zeroes you can augment that with something like this:
nwsw7zdq4#
Creating a function, as #derpircher suggests , is the ideal solution.
If you can't, because you only have read permission, and must use in a query you could use the following expression:
CONCAT(REPLICATE('_', PATINDEX('%[^0]%', MyCol)-1), TRY_CAST(MyCol AS INT));
The
PATINDEX
function found the first occurrence of a char different from zero.Full test code that return
__12004
:Version with fixed length to 11 and works with no leading zero