SQL Datalength vs. Len Functions

The other day I had an SSAS cube process failure which stemmed from values padded with spaces in our database. To fix this issue I ended up having to use a new SQL function I hadn’t heard of called “DATALENGTH”. Most colleagues of mine use the traditional “LEN” function to return the length of a given string. This quick post is aimed at outlining the differences in the two functions and when you should be using them.

LEN – This function returns the number of characters, rather than the number of bytes, of the given string. LEN will exclude trailing blanks and spaces.

Example: select LEN(MYSTRING) from dbo.MYDB

DATALENGTH – This function returns the number of bytes used to represent any type of expression.

Example: select DATALENGTH(MYSTRING) from dbo.MYDB

So when do you use each function? Typically, the LEN function is used to return the length of a string expression when you don’t care about blanks or want to overlook them. Alternatively, DATALENGTH is used to find the number of bytes and should therefore be used when you’re worried about blanks and trailing spaces.

For more documentation you can visit Microsoft Developer’s Network:

LEN( )

DATALENGTH( )

About the author

Dan Cody

I'm Dan! I'm a software developer with the 3M Corporation and a co-owner of SnagMobile. I won't bore you with the details, you can get them here if you like: http//www.dancody.me

In a nutshell I enjoy software, being outside, biking and being on boats. Hopefully I can spread some knowledge with you all. If you have any requests for posts, questions, or would just like to talk feel free to get in touch with me through the contact page. Sayonara!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2014. Dummy Dojo