SQL Server SQL - Column delimit

xvw2m8pv  于 2023-05-05  发布在  其他
关注(0)|答案(1)|浏览(132)

I have a column like this

ID
--------
00012345
00067891
12345678

I need to eliminate 0's if there is any in the first 3 rows. What should I use as a query to achieve this?

I have no idea how to do this

8e2ybdfx

8e2ybdfx1#

If your input is number and want zeros removed, use the this code This code deletes all leading zeros but Code two only first 3 character delete

declare @m varchar(100)='00012345'
select try_cast(@m as int)

Otherwise, your input is not just a number or if you want it not to be deleted if there are two or one to zero, you can use the this code

declare @m varchar(100)='00012345'
select iif( SUBSTRING(@m, 1, 3)='000','' + SUBSTRING(@m, 4, len(@m)-3),@m)
--result:12345

declare @m varchar(100)='00A147474'
select iif( SUBSTRING(@m, 1, 3)='000','' + SUBSTRING(@m, 4, len(@m)-3),@m)
--result:00A147474

declare @m varchar(100)='00147474'
select iif( SUBSTRING(@m, 1, 3)='000','' + SUBSTRING(@m, 4, len(@m)-3),@m)
--result:00A147474

declare @m varchar(100)='12345678'
select iif( SUBSTRING(@m, 1, 3)='000','' + SUBSTRING(@m, 4, len(@m)-3),@m)
--result:12345678

相关问题