Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

sql - Strip non-numeric characters from a string

I'm currently doing a data conversion project and need to strip all alphabetical characters from a string. Unfortunately I can't create or use a function as we don't own the source machine making the methods I've found from searching for previous posts unusable.

What would be the best way to do this in a select statement? Speed isn't too much of an issue as this will only be running over 30,000 records or so and is a once off statement.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this in a single statement. You're not really creating a statement with 200+ REPLACEs are you?!

update tbl
set S = U.clean
from tbl
cross apply
(
    select Substring(tbl.S,v.number,1)
    -- this table will cater for strings up to length 2047
    from master..spt_values v
    where v.type='P' and v.number between 1 and len(tbl.S)
    and Substring(tbl.S,v.number,1) like '[0-9]'
    order by v.number
    for xml path ('')
) U(clean)

Working SQL Fiddle showing this query with sample data

Replicated below for posterity:

create table tbl (ID int identity, S varchar(500))
insert tbl select 'asdlfj;390312hr9fasd9uhf012  3or h239ur ' + char(13) + 'asdfasf'
insert tbl select '123'
insert tbl select ''
insert tbl select null
insert tbl select '123 a 124'

Results

ID  S
1   390312990123239
2   123
3   (null)
4   (null)
5   123124

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...