2017-09-21 55 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。抱歉,花了這麼長時間回覆。一直在度假。 –