[英]Split column multiple values of an SQL 2005 table into new columns of a new temp table
我遇到的情況是,客戶表中包含150000條以上的記錄的電話號碼列包含多個值(電話),這些值用空格,逗號,破折號,點等分隔。原始列值是varchar類型,最大值30.我需要一種方法來檢查這些值並將它們拆分為新表的相等列,然后通過從其中刪除任何特殊字符來對其進行規范化。 新列的值均不得超過10位數字。
在下面找到當前表的選擇查詢結果,該表清楚地描述了當前混亂情況。 列號( ΠΕxxxxxx
)是Customer Unique Identifier
。 專欄Phone No_
是一團糟
- List item
-**No_** **Phone No_**
-ΠΕ000586 2310836590
-ΠΕ000589 2310.443602/6977.226818
-ΠΕ000591 2310740215
-ΠΕ000593 2310228976
-ΠΕ000598 2310444604
-ΠΕ000606 2310265616/6939686560
-ΠΕ000611 2310.227932(AΔΕΡΦΗ ΚΟΚΚΑΛΑ)
-ΠΕ000621 2310826921/6979552442
-ΠΕ000626 2310846216
-ΠΕ000629 2310931574
-ΠΕ000630 6977629688, 2310320441
-ΠΕ000631 2310.260886/6973.999840
-ΠΕ000633 2310.288408/342456/6944.503637
-ΠΕ000636 2310440143/6978008313
-ΠΕ000637 2310425655/6945365400
-ΠΕ000646 944111072
-ΠΕ000652 2310.201923,6942.693372
-ΠΕ000667 2310.482194/6977394456
-ΠΕ000675 6949199051
每個以/,-或空格分隔的數字都必須分成新的列
必須刪除所有文本。
少於10
位的任何數字序列,如果序列具有6
位數字,則必須添加2310前綴;如果序列具有9
位數字 ,並且序列的第一位數字以9開頭,則必須添加數字6
作為prefix 。 例如
the number 342456 must become 2310342456 and the number 944111072 must become 694411072
必須刪除10位數字序列之間的任何點(。),以便具有一個唯一的數字。例如
the number 231.282414 must be 231282414 or 6942.693372 must be 6942693372
任何幫助深表感謝
例如
if object_id('splitNums') is not null
drop function splitNums
go
create function splitNums(@nums varchar(30))
returns @tr table (n1 varchar(10), n2 varchar(10), n3 varchar(10), n4 varchar(10), n5 varchar(10)) as
begin
declare @v varchar(10)
declare @i int
insert into @tr values (null, null, null, null, null)
declare @ci int = 1
while (@ci <= 5 ) begin
if ( LEN(@nums) > 0 ) begin
set @i = charindex('/', @nums)
if ( @i <= 0 )
set @i = charindex(' ', @nums)
if ( @i <= 0 )
set @i = charindex('-', @nums)
if ( @i <= 0) begin
set @v = @nums
set @nums = ''
end else begin
set @v = SUBSTRING(@nums, 1, @i - 1)
set @nums = SUBSTRING(@nums, @i + 1, len(@nums) - @i)
end
end else set @v = ''
if ( @v = '' ) break
set @v = replace(@v, '.', '') -- more code needed here to remove text
if ( len(@v) = 6 ) set @v = '2310' + @v
else if (len(@v) = 9 and CHARINDEX('9', @v) = 1) set @v = '6' + @v
-- impossible to do dynamic sql in function so...
if (@ci = 1)
update @tr set n1 = @v
else if (@ci = 2)
update @tr set n2 = @v
else if (@ci = 3)
update @tr set n3 = @v
else if (@ci = 4)
update @tr set n4 = @v
else if (@ci = 5)
update @tr set n5 = @v
set @ci = @ci + 1
end
return
end
go
declare @t table (
id nvarchar(10),
number nvarchar(30)
)
insert into @t (id, number) values
(N'ΠΕ000586', '2310836590'),
(N'ΠΕ000589', '2310.443602/6977.226818'),
(N'ΠΕ000633', '2310.288408/342456/6944.503637')
select * from @t cross apply dbo.splitNums(number)
go
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.