SQL Server converting variable field varchar to money / decimal / something with decimal places
I'm looking for an elegant way to convert a varchar field with variable data to it to a data type that can be used to sample math operations data from the field (excluding quotes)
''
'abc'
'23'
'23.2'
The method should work for everyone, and for the first and second values, it should return 0 and not throw a SQL Server error.
source to share
I know this is a long dead thread, but I recently stumbled upon it from a google search and thought. It is less elegant than the CASE statement, but it is an alternative.
SELECT
COALESCE(CAST(NULLIF(ISNUMERIC(LEFT(MyColumn, PATINDEX('% %', MyColumn + ' ') - 1)), 1) AS MONEY), LEFT(MyColumn, PATINDEX('% %', MyColumn + ' ') - 1))
FROM
myTable
or you could do:
Select COALESCE(CAST(NULLIF(ISNUMERIC(MyColumn), 1) AS MONEY), MyColumn)
FROM
myTable
The upper version will see "2 5" as soon as 2, the lower one will see it as a text box.
source to share
COALESCE
is a great option for this: Find more information here. It evaluates the arguments in order and returns the current value of the first expression, which does not initially evaluate to NULL.
ISNUMERIC
returns 0 or 1 depending on whether the value being evaluated can be considered one of the SQL types 'number' or 'numeric'. e.g. int, bigint, money ..
NULLIF
essentially finds the value you specified and, if it matches, replaces it with the value NULL
.
CAST
Will just change the datatype to something else in this example to MONEY
As you can see, if you break the bottom down using this information, it's a pretty elegant solution I guess?
COALESCE(CAST(NULLIF(ISNUMERIC(COL1), 1) AS MONEY), COL1)
source to share