title: What characters are valid in an SQL Server database name?
body: <p>We're going to provide our clients with a tool that (among other things) creates a new SQL Server database, and I want to be able to do basic validation on the database name they provide. SQL Server's documentation explains what characters are valid in a database name. However, the documentation is apparently incorrect, because I can successfully create databases whose names violate the documented rules.</p>
  
  <p>According to SQL Server's documentation for <a href="http://msdn.microsoft.com/en-us/library/ms176061.aspx">CREATE DATABASE</a>, database names must comply with the rules for identifiers; and the rules for <a href="http://msdn.microsoft.com/en-us/library/ms175874.aspx">identifiers</a> depend on the database compatibility level. When the compatibility level is 100 (which, according to SQL Server Management Studio, means "SQL Server 2008"), the name must start with a Unicode letter, <code>_</code>, <code>@</code>, or <code>#</code>; followed by one or more letters, numbers, <code>@</code>, <code>$</code>, <code>#</code>, or <code>_</code>. The documentation clearly states that embedded spaces or special characters are not allowed.</p>
  
  <p>This flies in the face of the available evidence, because I can use SQL Server Management Studio to create a database whose name is <code>This &amp; That | "Other"</code> -- which not only contains embedded spaces (explicitly forbidden), but contains special characters (<code>|</code>, <code>"</code>) that aren't even valid in a filename. I checked, and the database's compatibility level is indeed "SQL Server 2008 (100)", even though its name is documented to be invalid at that compatibility level.</p>
  
  <p>Heck, I can even do <code>CREATE DATABASE " "</code> (yes, that's a single space), which proves that the first character does <em>not</em> have to be a letter, underscore, at sign, or pound sign.</p>
  
  <p>So I guess my question is, what characters <strong>are</strong> valid in an SQL Server database name? Are there any documented rules that are consistent with SQL Server's actual behavior?</p>