tags:

views:

95

answers:

4

It is possible to write a query get all that record from a table where a certain field contains a numeric value?

something like "select street from tbladdress where street like '%0%' or street like '%1%' ect ect"

only then with one function?

+4  A: 

Yes, but it will be inefficient, and probably slow, with a wildcard on the leading edge of the pattern

LIKE '%[0-9]%'
martin clayton
+5  A: 

Try this

declare @t table(street varchar(50))
insert into @t 
    select 'this address is 45/5, Some Road' union all
    select 'this address is only text'

select street from @t
where street like '%[0-9]%'

street

this address is 45/5, Some Road
priyanka.sarkar
I will use this then, thanks for the answer
Ivo
A: 

I found this solution " select street from tbladresse with(nolock) where patindex('%[0-9]%',street) = 1"

it took me 2 mins to search 3 million on an unindexed field

Ivo
But it will not work for the cases I produced e.g. 'this address is 45/5, Some Road'
priyanka.sarkar
@pewned: true but all he has to do is change = 1 to > 0. I like your solution better though.
Lieven
For the record, no index in the world would help you with this query.
erikkallen
(at least no index supplied by any SQL database).
erikkallen
A: 

Searching for text within a column is horrendously inefficient and does not scale well (per-row functions, as a rule, all have this problem).

What you should be doing is trading disk space (which is cheap) for performance (which is never cheap) by creating a new column, hasNumerics for example, adding an index to it, then using an insert/update trigger to set it based on the data going into the real column.

This means the calculation is done only when the row is created or modified, not every single time you extract the data. Databases are almost always read far more often than they're written and using this solution allows you to amortize the cost of the calculation over many select statement executions.

Then, when you want your data, just use:

select * from mytable where hasNumerics = 1; -- or true or ...

and watch it leave a regular expression query or like '%...%' monstrosity in its dust.

paxdiablo
We use the query ones to make an export of the rows, and then put them back in with "street" and housenumber in a separate column, but thanks for they advice
Ivo
If this is not a one-off search, yes this is probably a good idea. But, of course, you should use a persisted computed column rather than a trigger.
erikkallen
Not all DBMS' have computed columns and I believe IBM actually has a patent on that feature anyway.
paxdiablo