我想从SQL Server中提取的数据中排除数字。
我有一个表Student
,其列address
为text
数据类型。
我想选择地址中没有数字的地址。
例如:
select address from student;
该表的数据可能为TUCSON AZ 85705-7598 USA
。
我的结果应为TUCSON AZ USA
答案 0 :(得分:1)
这是一种在线方法。
CROSS APPLY将拆分/解析字符串,然后重新构建它,不包括任何以数字开头的部分
编辑 - 我应该补充一点,子查询B1可以很容易地迁移到表值函数中。
示例强>
Declare @YourTable table (addr varchar(250))
Insert into @YourTable values
('TUCSON AZ 85705-7598 USA'),
('TUCSON AZ 85705 USA'),
('TUCSON AZ USA')
Select A.addr
,NewAddress = B.S
From @YourTable A
Cross Apply (
Select S = Stuff((Select ' ' +RetVal
From (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(A.addr,' ','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
) B1
Where RetVal Not Like '[0-9]%'
Order by RetSeq
For XML Path ('')),1,1,'')
) B
<强>返回强>
addr NewAddress
TUCSON AZ 85705-7598 USA TUCSON AZ USA
TUCSON AZ 85705 USA TUCSON AZ USA
TUCSON AZ USA TUCSON AZ USA
答案 1 :(得分:1)
请尝试此解决方案......
解决方案
Declare @YourTable table (addr varchar(250))
Insert into @YourTable values
('TUCSON AZ 85705-7598 USA'),
('TUCSON AZ 85705 USA'),
('TUCSON AZ USA')
;WITH CTE AS
(
SELECT *, PATINDEX ( '%[0-9]%' , addr ) sta
, PATINDEX ( '%[a-zA-Z]%' , SUBSTRING (addr , PATINDEX ( '%[0-9]%' , addr ) , 1000 ))
chars
FROM @YourTable
)
SELECT addr oldaddr , CASE WHEN sta = 0 THEN addr else STUFF(addr,sta,chars-1,'') end addr
FROM CTE
输出
oldaddr addr
----------------------------- -------------------
TUCSON AZ 85705-7598 USA TUCSON AZ USA
TUCSON AZ 85705 USA TUCSON AZ USA
TUCSON AZ USA TUCSON AZ USA
(3 rows affected)