Categories
Uncategorized

SQL length

I was attempting to find the number of characters in a field in Microsoft SQL Server…

I was attempting to find the number of characters in a field in Microsoft SQL Server, so I tried this:

SELECT
  length(desc)
FROM
  foo;

That was the logical thing to try, and guess what? It worked just fine in MySQL, but no dice in Microsoft SQL Server, so after some searching and asking others I found out that Microsoft SQL Server has something called datalength, so I tried this:

SELECT
  datalength(desc)
FROM
  foo;

Well, that tells you the size of the field, but not the size of the data within the field… Oh, that’s right, rtrim is your friend…

SELECT
  datalength(rtrim(desc))
FROM
  foo;

Success! We get the number of characters instead of the size of the field itself. MySQL is blunt and just gives you the answer you want… Microsoft SQL Server has to get all technical on you, and make you clarify and specifically ask for what you want…

And if there’s something I missed, or there’s some other way to do it, let me know…

(Special thanks to O'Reilly for their SQL in a Nutshell info…)