我在数据库中有一些字段,值为54D,325A,2E等,字母优先,数字最后。
如何在select语句中拆分它们,或者将其过滤为仅显示字母或数字?我不能使用udf函数。
我需要能够将54插入另一列,将D插入另一列,依此类推。
我在MS SQL Server上
由于
答案 0 :(得分:4)
使用第一个非数字位置的一种方法:
;with T(f) as (
select '325A' union
select '54D' union
select '2E' union
select '555' union
select 'Z'
)
select
f,
rtrim(left(f, patindex('%[^0-9]%', f + ' ') - 1)),
rtrim(substring(f + ' ', patindex('%[^0-9]%', f + ' '), len(f)))
from T
----
2E 2 E
325A 325 A
54D 54 D
555 555
Z Z
答案 1 :(得分:1)
declare @t table(col1 varchar(20))
insert @t values('54D'),('325A'),('2E'), ('A'), ('3')
SELECT
substring(col1, 0, patindex('%[^0-9]%', col1 + 'a')),
stuff('0' + col1, 1, patindex('%[^0-9]%', col1 + 'a'), '')
FROM @t
结果:
54 D
325 A
2 E
A
3
答案 2 :(得分:0)
这是一些残酷的解决方案,但它也能够分离混合字符串:
DECLARE @t TABLE(ID INT, S NVARCHAR(MAX))
INSERT INTO @t VALUES (1, '123AB'), (2, '45CDEF'), (3, '1AS^&*876YU')
DECLARE @m INT
SELECT @m = MAX(LEN(S)) FROM @t
;WITH cte AS
(SELECT ID, SUBSTRING(S, 1, 1) AS S, 1 AS N, ISNUMERIC(SUBSTRING(S, 1, 1)) AS NU FROM @t
UNION ALL
SELECT t.ID, SUBSTRING(t.S, N + 1, 1) AS S, N + 1 AS N, ISNUMERIC(SUBSTRING(t.S, N + 1, 1)) AS NU FROM cte
JOIN @t t ON t.ID = cte.ID
WHERE N < @m
)
SELECT
(SELECT S FROM cte c2 WHERE c2.ID = c1.ID AND NU = 1 FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)') AS NumericPart,
(SELECT S FROM cte c2 WHERE c2.ID = c1.ID AND NU = 0 FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)') AS TextPart
FROM cte c1
WHERE S <> ''
GROUP BY ID
输出:
NumericPart TextPart
123 AB
45 CDEF
1876 AS^&*YU