SDU Tools: Formatting Bytes in SQL Server T-SQL
Our free SDU Tools for developers and DBAs, now includes a very large number of tools, with procedures, functions, and views. The FormatBytes function can now be used to take a number of bytes, and to format it as a string, with appropriate units.
The calculation can be done using SI units (where 1000 bytes is one kB, or binary units where 1024 bytes is one KB. It can also output IEC based units like the kibibyte.
The function takes two parameters:
- @ByteCount -> number of bytes to format
- @UnitsType -> defaults to BINARY but can be SI, or IEC
For details on how these units work, see my recent blog post about these .
Binary units align well with SQL Server internals and DMVs. SI units are more appropriate for human-facing reports, and IEC units avoid the potential ambiguity that comes from using binary units.
The precision of the function is fixed at 2 decimal places for display consistency and negative and NULL inputs return NULL.
FormatBytes takes a number of bytes and returns the value as a string, with units as a suffix e.g., 1.02kB or 1.02KB. The calculation can be done using SI units (where 1000 bytes is one kB, or binary units where 1024 bytes is one KB. It can also output IEC based units like the kibibyte.
Find out more
You can see it in action in the main image above, and in the video here:
You can use our tools as a set or as a great example of how to write functions like these.
Access to SDU Tools is one of the benefits of being an SDU Insider, along with access to our other free tools and eBooks. Please just visit here for more info:
http://sdutools.sqldownunder.com
2026-03-27