views:

298

answers:

4

Hi!

I need something like this...

stored value in DB is: 5XXXXXX [where x can be any digit]

and i need to match incoming SQL query string like... 5349878.

Does anyone has an idea how to do it?

i have also different cases like XXXX7XX for example, so it has to be generic.

i don't care to represent the pattern in a differnet way inside the SQl server.

i'm working with c# .Net

Thanks For Advance!!!

+1  A: 

You can write queries like this in SQL Server:

--each [0-9] matches a single digit, this would match 5xx
SELECT * FROM YourTable WHERE SomeField LIKE '5[0-9][0-9]'
dan
A: 

SQL Wildcards are enough for this purpose. Follow this link: http://www.w3schools.com/SQL/sql%5Fwildcards.asp

you need to use a query like this:

select * from mytable where msisdn like '%7%'

or

select * from mytable where msisdn like '56655%'
JCasso
thanks for reple!these queries will give me many unwanted matches.%7% will match also 3373 which is not a good match for me.56655% will match also 56655444333 which is again not a good match for me.the query itself has to be with a fixed number. and the DB itself has to have the pattern. is there anything like that?
Jack
@Jack: yes there is. You may use len function. select * from mytable where msisdn like '56655%' and len(msisdn) = 10
JCasso
+1  A: 

stored value in DB is: 5XXXXXX [where x can be any digit]

You don't mention data types - if numeric, you'll likely have to use CAST/CONVERT to change the data type to [n]varchar.

Use:

WHERE CHARINDEX(column, '5') = 1
  AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
  AND ISNUMERIC(column) = 1

References:

i have also different cases like XXXX7XX for example, so it has to be generic.

Use:

WHERE PATINDEX('%7%', column) = 5
  AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
  AND ISNUMERIC(column) = 1

References:

Regex Support

SQL Server 2000+ supports regex, but the catch is you have to create the UDF function in CLR before you have the ability. There are numerous articles like this one, providing example code if you google them. Once you have that in place, you can use:

  • 5\d{6} for your first example
  • \d{4}7\d{2} for your second example

For more info on regular expressions, I highly recommend this website.

OMG Ponies
i haven't completely checked it yet, but i looks like a very good answer. i think that you help me a lot. thank you very much!
Jack
One minor detail, IsNumeric would consider a decimal point valid, so an expresssion of5123.45 would pass the IsNumeric () check, but might not meet your criteria
Sparky
@Sparky: True, updated answer with comment to exclude those if necessary.
OMG Ponies
A: 

Try this

select * from mytable
where p1 not like '%[^0-9]%' and substring(p1,1,1)='5'

Of course, you'll need to adjust the substring value, but the rest should work...

Sparky