title: How do I select a top-level attribute of an XML column in SQL Server?
body: <p>I have an XML column in SQL Server that is the equivalent of:</p>
  <pre><code>&lt;Test foo=&quot;bar&quot;&gt;
    &lt;Otherstuff baz=&quot;belch&quot; /&gt;
  &lt;/Test&gt;
  </code></pre>
  <p>I want to get the value of the <code>foo</code> attribute of Test (the root element) as a varchar. My goal would be something along the lines of:</p>
  <pre><code>SELECT CAST('&lt;Test foo=&quot;bar&quot;&gt;&lt;Otherstuff baz=&quot;belch&quot; /&gt;&lt;/Test&gt;' AS xml).value('@foo', 'varchar(20)') AS Foo
  </code></pre>
  <p>But when I run the above query, I get the following error:</p>
  <blockquote>
  <p>Msg 2390, Level 16, State 1, Line 1
  XQuery [value()]: Top-level attribute
  nodes are not supported</p>
  </blockquote>