简体   繁体   中英

Convert nvarchar value to Decimal or Numeric datatype?

I have a column called 'Market value' in my SQL table where values of this column is like '+000000034567.4563' (18 char length including + symbol) and datatype is NVARCHAR .

I need to apply group by and take sum of 'Market Value' but group by does not work with NVARCHAR data type. So I am converting using CONVERT .

SELECT CONVERT(Numeric(18,4), '+000000034567.4563') 

But I am getting output is '34567.4563' But my expectation is '+000000034567.4563'.

How can I achieve this using SQL?

you could use Format to convert it to your desired string representation again like this

SELECT format(CONVERT(numeric(18,4), '+000000034567.4563'), '+000000000000.0000') 

and use it to calculate and then format

SELECT format(sum(CONVERT(numeric(18,4), yt.[Market Value])), '+000000000000.0000')
from yourtable yt
group by yt.whatever

Check this code if it will help you in any way. It was written on MySQL Language.

Select Concat(Left(Market_Value,1),
        Repeat('0',(Length(Market_value)-Length(concat(left(Market_Value,1),
        sum(substring(Market_value,2,Length(Market_Value))))))),
        sum(substring(Market_value,2,Length(Market_Value)))) as Market_Value 
        from Test57 group by Market_value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM