Click here to Skip to main content
16,017,297 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi We save file size in bytes,when selete data in sql query need to convert as mb and add word "MB" at end of result . This is data in "File Size" column in my table

SQL
File Size
25327668
9463163
1016575
1645595
11475


1. I am try following ways,if file size is below 20 mb then can get result,otherwise (25327668 this 24mb in bytes) it show error like
C#
Msg 8115, Level 16, State 8, Line 4
Arithmetic overflow error converting nvarchar to data type numeric.


SQL
select convert(nvarchar(50),db.[File Size]/ 1048576.0 ) +' MB' as FSize from  [thumbnaa] db 


2.if i try like this ,then below 1mb always show 0,pls see screeshot
http://prntscr.com/9cdhyz[^]

SQL
select convert(nvarchar(50),db.[File Size]/ (1024*1024) ) +' MB' as FSize from  [thumbnaa] db 




This one work finally,but i need to show only 2 digit after dot
SQL
convert(nvarchar(50) ,cast(db.[File Size] as numeric(35,2))/1048576.0 ) +' MB' as FSize 


like this 24.15 MB
pls reply asap

Regards
Aravind
Posted
Updated 13-Dec-15 15:00pm
v3
Comments
Tomas Takac 10-Dec-15 5:07am    
#1 works for me (SQL Server 2008R2). Are you sure that not something else is causing the error? In your example there is FTR.[Version] which clearly does not belong there. Maybe you are not showing the whole query?

1 solution

I suspect your File Size column is declared as nvarchar - you are storing numbers as strings.

Change the column type to bigint, or add an extra conversion to your query:
SQL
select convert(nvarchar(50), Convert(bigint, db.[File Size]) / 1048576.0 ) +' MB' as FSize from  [thumbnaa] db 
-- Output: 24.154346466 MB
 
Share this answer
 
Comments
Aravindba 10-Dec-15 20:59pm    
Hi Actually my file size column declare as Int,in this select query i am try to add "MB" at the end of result,so i convert result to nvarchar.And in description i mention below 20mb in bytes format can convert to mb successfully.
Richard Deeming 11-Dec-15 7:43am    
I can't reproduce the error you've reported using the query and data you've provided unless the [File Size] column is declared as varchar / nvarchar.

With the column declared as int, your first query works perfectly.

Here's a SQLFiddle[^] to demonstrate.
Dave Kreskowiak 13-Dec-15 23:07pm    
Your [File Size] column is not an int. The error says you saved the sizes as strings (nvarchar).
Aravindba 13-Dec-15 20:59pm    
Ok,it will work when i change like this
convert(nvarchar(50) ,cast(db.[File Size] as numeric(35,2))/1048576.0 ) +' MB' as FSize
I need to do other thing,after dot ,only need to show first 2 digit only like 24.15 MB
How
Richard Deeming 14-Dec-15 8:06am    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900