2017-09-21 45 views
0

我有一个表名和表名列表项。以下是数据。删除字母并将前导0插入某个字符长度

ABC123 
ABC1234 
ABC12345 
HA11 
K112 
L1164 

我需要删除字母,将其替换为前导0,并且总字符长度必须为9.下面是结果。

00000
0000
000
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的

谢谢。

回答

1

我以为,你只能在你的数据的开头字母的。

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 

在其应用到你的表方面:

select left('000000000', 9 - len([Digits])) + [Digits] from (
    select right([Item], len([Item]) - patindex('%[0-9]%', [Item]) + 1) as [Digits] from [Table] 
) 
+0

感谢米哈尔。它有效= D。因此,要更改整列,是否需要逐个声明值?因为我试图将值更改为声明@s varchar(20)=从表中选择项目,它不喜欢它。再次感谢您的帮助= D。 –

+0

@AdhityaSanusi请参阅编辑。另外,接受答案,这样就不需要管理员的注意。 –

+0

谢谢Michal。你又做了= D。抱歉,花了这么长时间回复。一直在度假。 –

相关问题