Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to match any decimal number with T-SQL 'LIKE' expression?

For example, something like:

SELECT * FROM myTable WHERE myColumn LIKE '[0-9]n.[0-9]n'

Of course I know the syntax above will not work, but I m trying to explain: n digits, followed by a period, followed by n digits. Thanks

like image 857
Kambiz Avatar asked Oct 14 '25 08:10

Kambiz


2 Answers

You could use following patters for unsigned decimal values:

SELECT  *, 
        CASE 
            WHEN (x.Col1 LIKE '%[0-9]%.%[0-9]%' /*OR x.Col1 LIKE '.%[0-9]%' OR x.Col1 LIKE '%[0-9]%.' OR x.Col1 LIKE '%[0-9]%'*/) 
            AND x.Col1 NOT LIKE '%[^0-9.]%'  
            THEN 1 ELSE 0 
        END AS IsDecimal,
        ISNUMERIC(x.Col1) AS [IsNumeric]
FROM (
    SELECT '1.23' UNION ALL SELECT '.23' UNION ALL SELECT '1.'  UNION ALL SELECT '123'  UNION ALL 
    SELECT NULL UNION ALL SELECT '' UNION ALL SELECT '1A.23'  UNION ALL SELECT '1.2A3'  UNION ALL SELECT 'A.B'  UNION ALL 
    SELECT '.' UNION ALL SELECT '$' 
) x(Col1)

/*
Col1  IsDecimal   IsNumeric
----- ----------- -----------
1.23  1           1
.23   0           1
1.    0           1
123   0           1
NULL  0           0
      0           0
1A.23 0           0
1.2A3 0           0
A.B   0           0
.     0           1
$     0           1
*/

If you uncomment /*OR x.Col1 LIKE '.%[0-9]%' OR x.Col1 LIKE '%[0-9]%.' OR x.Col1 LIKE '%[0-9]%'*/ then .23 , 1. and 123 will be considered (also) valid decimal values.

like image 59
Bogdan Sahlean Avatar answered Oct 16 '25 22:10

Bogdan Sahlean


Do you need exactly n or just anything that will cast to decimal

select cast(varDec as Decimal(p,s)) 
where varDec not like '%[^.1-9]%' 
and varDec not like '%.%.%'
and len(varDec) > 0 
and varDec <> '.'
like image 41
paparazzo Avatar answered Oct 16 '25 22:10

paparazzo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!