删除字母并插入前导 0 到特定字符长度
Remove Alphabet and Insert Leading 0 up to Certain Character Length
我有一个 table 名称 Table 和列名称 Item。下面是数据。
ABC123
ABC1234
ABC12345
HA11
K112
L1164
我需要去掉字母,用0开头,总字符长度必须是9。下面是结果。
000000123
000001234
000012345
000000011
000000112
000001164
我只知道如何更改 ABC(特定字母集),但我不知道如何构建 CASE 语句。以下是我取得的成功。
select REPLICATE('0',9-LEN(A.B)) + A.B
from
(select replace(Item, 'ABC','') as B from Table) as A
我尝试将 CASE 与 SELECT 结合使用,但它看起来并不像。
Case when Item like '%ABC%' then
select REPLICATE('0',9-LEN(A.B)) + A.B
from
(select replace(Item, 'ABC','') as B from Table) as A
when Item like '%HA%' then
select REPLICATE('0',9-LEN(A.B)) + A.B
from
(select replace(Item, 'HA','') as B from Table) as A
when Item like '%K%' then
select REPLICATE('0',9-LEN(A.B)) + A.B
from
(select replace(Item, 'K','') as B from Table) as A
when Item like '%L%' then
select REPLICATE('0',9-LEN(A.B)) + A.B
from
(select replace(Item, 'L','') as B from Table) as A
else Item
End
有谁知道如何实现结果?我正在使用 SQL Server 2012。
谢谢。
我假设,您的数据仅在开头有字母。
declare @s varchar(20) = 'ABS123'
-- we find index of first occurence of digit and then we cut out the letters
set @s = right(@s, len(@s) - patindex('%[0-9]%', @s) + 1)
-- here we just produce string with amount of zeros we need
select left('000000000', 9 - len(@s)) + @s
在将它应用到您的 table 方面:
select left('000000000', 9 - len([Digits])) + [Digits] from (
select right([Item], len([Item]) - patindex('%[0-9]%', [Item]) + 1) as [Digits] from [Table]
)
我有一个 table 名称 Table 和列名称 Item。下面是数据。
ABC123
ABC1234
ABC12345
HA11
K112
L1164
我需要去掉字母,用0开头,总字符长度必须是9。下面是结果。
000000123
000001234
000012345
000000011
000000112
000001164
我只知道如何更改 ABC(特定字母集),但我不知道如何构建 CASE 语句。以下是我取得的成功。
select REPLICATE('0',9-LEN(A.B)) + A.B
from
(select replace(Item, 'ABC','') as B from Table) as A
我尝试将 CASE 与 SELECT 结合使用,但它看起来并不像。
Case when Item like '%ABC%' then
select REPLICATE('0',9-LEN(A.B)) + A.B
from
(select replace(Item, 'ABC','') as B from Table) as A
when Item like '%HA%' then
select REPLICATE('0',9-LEN(A.B)) + A.B
from
(select replace(Item, 'HA','') as B from Table) as A
when Item like '%K%' then
select REPLICATE('0',9-LEN(A.B)) + A.B
from
(select replace(Item, 'K','') as B from Table) as A
when Item like '%L%' then
select REPLICATE('0',9-LEN(A.B)) + A.B
from
(select replace(Item, 'L','') as B from Table) as A
else Item
End
有谁知道如何实现结果?我正在使用 SQL Server 2012。
谢谢。
我假设,您的数据仅在开头有字母。
declare @s varchar(20) = 'ABS123'
-- we find index of first occurence of digit and then we cut out the letters
set @s = right(@s, len(@s) - patindex('%[0-9]%', @s) + 1)
-- here we just produce string with amount of zeros we need
select left('000000000', 9 - len(@s)) + @s
在将它应用到您的 table 方面:
select left('000000000', 9 - len([Digits])) + [Digits] from (
select right([Item], len([Item]) - patindex('%[0-9]%', [Item]) + 1) as [Digits] from [Table]
)