Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate size in megabytes from SQL varbinary field

We have a db table that stores files as varbinary(MAX). When we run the following script:

SELECT SUM(LEN(Content)) FROM dbo.File 

The result is:

35398663

I want to convert this number into megabytes? Is this possible?

like image 218
Shai Cohen Avatar asked Sep 14 '12 16:09

Shai Cohen


People also ask

How many bytes is a Varbinary?

varbinary [ ( n | max) ] Variable-length binary data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of the data entered + 2 bytes.

How do I get the size of a field in SQL?

Use COL_LENGTH() to Get a Column's Length in SQL Server In SQL Server, you can use the COL_LENGTH() function to get the length of a column. More specifically, the function returns the defined length of the column, in bytes. The function accepts two arguments: the table name, and the column name.

How do I find the size of a varchar in SQL?

So remember to use LEN() function in SQL Server to find out the length of any String stored in VARCHAR column. It doesn't need to be VARCHAR, but LEN() function accepts a text value, which means it could be CHAR, VARCHAR, NCHAR or NVARCHAR as well.

How do I find the length of a column of data in SQL Server?

You can use the LEN function () to find the length of a string value in SQL Server, for example, LEN (emp_name) will give you the length stored in the emp_name string. Remember that this is different from the actual length you specified when creating the table, for example, emp_name VARCHAR (60).


1 Answers

Use DATALENGTH to retrieve the number of bytes and then convert, like this:

SQL Fiddle

MS SQL Server 2017 Schema Setup:

CREATE TABLE supportContacts      (      id int identity primary key,       type varchar(20),       details varchar(30)     );  INSERT INTO supportContacts (type, details) VALUES ('Email', '[email protected]'), ('Twitter', '@sqlfiddle'); 

Query 1:

select *, gigabytes / 1024.0 as terabytes from (   select *, megabytes / 1024.0 as gigabytes   from (     select *, kilobytes / 1024.0 as megabytes     from (       select *, bytes / 1024.0 as kilobytes       from (         select sum(datalength(details)) as bytes         from supportContacts              ) a     ) b     ) c ) d 

Results:

| bytes | kilobytes |     megabytes |      gigabytes |         terabytes | |-------|-----------|---------------|----------------|-------------------| |    29 |   0.02832 | 0.00002765625 | 2.700805664e-8 | 2.63750553125e-11 | 
like image 147
D'Arcy Rittich Avatar answered Sep 20 '22 11:09

D'Arcy Rittich