DECLARE @table table(XYZ VARCHAR(8) , id int)
INSERT INTO @table
SELECT '4000', 1
UNION ALL
SELECT '3.123', 2
UNION ALL
SELECT '7.0', 3
UNION ALL
SELECT '80000', 4
UNION ALL
SELECT NULL, 5
Query:
SELECT CASE
WHEN PATINDEX('^[0-9]{1,5}[\.][0-9]{1,3}$', XYZ) = 0 THEN XYZ
WHEN PATINDEX('^[0-9]{1,8}$',XYZ) = 0 THEN CAST(XYZ AS decimal(18,3))/1000
ELSE NULL
END
FROM @table
This part – CAST(XYZ AS decimal(18,3))/1000 doesn’t divide the value.
It gives me more number of zeros after decimal instead of dividing it. (I even enclosed that in brackets and tried but same result).
Ex:2000/1000 = 2000.000000
Am I doing something wrong here? Are patindex expression parameters correct?
Expected result:
4.000
3.123
7.000
80.000
Do let me know if PATINDEX is not correct method to use?
I’m trying to check if it is already decimal with 3 decimal points else i want to divide by 1000.
Try this..
Output
Edit – to keep to 3 decimal places in output do this
Note the (8,3) defines this, total precision 8 digits, 3 after the point.
You may wish to convert back to varchar(8) too