views:

1235

answers:

2

In SQL server 2005 this query

select len(cast('the quick brown fox jumped over the lazy dog' as varchar))

returns 30 as length while the supplied string has more characters. This seems to be the default. Why 30, and not 32 or any other power of 2?

+5  A: 

Why don't you specify the varchar length? ie:

select cast('the quick brown fox jumped over the lazy dog' as varchar(45))

As far as why 30, thats the default length in SQL server for that type

Edit: Moved this up from my comment:

wanted to double check the default length statement...here it specifies it on MSDN http://msdn.microsoft.com/en-us/library/ms176089.aspx first sentence under "Remarks"

curtisk
+1. Why wouldn't you set the length? Not setting it is asking for trouble.
Bert Evans
It was a quick and dirty query, so that why I didn't specify. Thanks for pointing me to the docs though where it is mentioned though.
edosoft
+2  A: 

I don't know why they chose 30, but it was the same in Sybase SQL Server, which Microsoft's SQL Server was developed from. It seems to be a peculiarity of those RDBMSs as it's not in the SQL standards, and other servers differ in their behaviour.

xahtep
According to the SQL standard, a cast to VARCHAR with no length should be a cast to VARCHAR(1). That's not useful - so you should always provide a length. There's a case that 30 is a better default than 1; I'd even agree. But why 30 instead of 25, 32, 40, 64, ... aaah; that way lies madness!
Jonathan Leffler