title: SQL Server For Xml Path
body: <p>I am returning an xml result for a query.</p>
  
  <p>Given two tables:</p>
  
  <pre><code>**Foo**
  FooId int
  FooName varchar(10)
  
  **Bar**
  BarId int
  FooId int (FK)
  BarName varchar(10)
  </code></pre>
  
  <p>I create a select statement like:</p>
  
  <pre><code>SELECT
    FooId,
    FooName,
    (
      SELECT
        BarId,
        FooId,
        BarName
      FROM
        Bar
      WHERE
        Bar.FooId = Foo.FooId
        AND Bar.BarName = 'SomeBar'
      FOR XML PATH('Bar'), TYPE
    )
  FROM
    Foo
  WHERE
    Foo.FooName = 'SomeFoo'
    AND Foo.FooId IN
    (
      SELECT
        Bar.FooId
      FROM
        Bar
      WHERE
        Bar.BarName = 'SomeBar'
    )
  FOR XML PATH('Foo'), TYPE  
  </code></pre>
  
  <p>This works as I expect it and returns the correct results.  I realized while developing it I needed to duplicate the filtering clauses in both the sub select and the nested selects in the where clause in order to get the correct results.</p>
  
  <p>I'd like to make sure there isn't a better way to do this.  A coworker mentioned using aliases to remove the duplicate clauses but am not sure how that would accomplish anything.</p>
  
  <p>Is this necessary, or is there a better way?  </p>