Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Varchar To Money

I am trying to convert a varchar column to money but I keep getting this error

Implicit conversion from data type varchar to money is not allowed. Use the CONVERT function to run this query.

Am I not using the convert function like the error suggests?

Select
    tellerID,
    SUM(CASE 
           WHEN CONVERT(money, value1) IS NULL THEN '0' 
           ELSE CONVERT(money, value1) 
        END) AS [Total Value 1]
From 
    intakedrawer
Group By 
    tellerID
Order By 
    tellerID
like image 517
Rashid Abib Avatar asked Dec 05 '25 03:12

Rashid Abib


2 Answers

Try like this:

Select
tellerID,
SUM(CASE WHEN IsNumeric(value1) = 0 THEN 0 
       ELSE CAST(value1 AS decimal(18, 2)) 
END) as [Total Value 1]
From intakedrawer
Group By tellerID
Order By tellerID
like image 90
Rahul Tripathi Avatar answered Dec 06 '25 23:12

Rahul Tripathi


If you're on SQL Server 2012 or higher you can also use TRY_CONVERT. If the conversion doesn't work it returns NULL.

SELECT
 tellerid,
 SUM(TRY_CONVERT(MONEY, value1)) AS [Total Value 1]
FROM intakedrawer
GROUP BY tellerid
ORDER BY tellerid;

There's a SQL Fiddle here.

like image 34
Ed Gibbs Avatar answered Dec 07 '25 00:12

Ed Gibbs



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!