我有一个似乎有效的SQL查询,但是它使我感到不必要的冗长(有益于理解,但可能不利于速度)。我希望有人可以将其编码为更多功能。
DECLARE @temp TABLE
(
strng varchar(5000)
)
INSERT INTO @temp (strng)
VALUES
('555-444-6285'),
('intercom 5362'),
('555-444-6285 ext. 5362'),
('(306) 250-4968'),
('011-555-888 9965-6859'),
('Not a Phone Number')
SELECT LeftNumeric
, CASE WHEN PosOfNum > 1 THEN LEFT(RightRemainder, PosOfNum-1) ELSE RightRemainder END AS MiddleAlpha
, CASE WHEN PosOfNum > 1 THEN RIGHT(RightRemainder, LEN(RightRemainder)-PosOfNum+1) ELSE '' END AS RightNumeric
FROM
(
SELECT strng
, LeftNumeric
, RightRemainder
, PATINDEX('%[-0-9()]%', RightRemainder) as PosOfNum
FROM
(
SELECT strng
,PosOfChar
, CASE WHEN PosOfChar > 0 THEN LEFT(strng, PosOfChar-1) ELSE Strng END AS LeftNumeric
, CASE WHEN PosOfChar > 0 THEN RIGHT(strng, LEN(strng)-PosOfChar+1) ELSE '' END AS RightRemainder
FROM
(
SELECT strng
, PATINDEX('%[^-0-9.() ]%', strng) as PosOfChar
FROM @Temp
) Process1
) Process2
) Process3
运行以上命令的最终结果如下:
LeftNumeric MiddleAlpha RightNumeric
555-444-6285
intercom 5362
555-444-6285 ext. 5362
(306) 250-4968
011-555-888 9965-6859
Not a Phone Number
答案 0 :(得分:0)
这是我们采用的最终解决方案,效果很好。