title: Syntax for STUFF/FOR XML PATH
body: <p>Can anyone see what I am doing wrong syntactically to be getting </p>
  
  <blockquote>
    <p>Msg 156, Level 15, State 1, Line 33<br>
    Incorrect syntax near the keyword 'FOR'.</p>
  </blockquote>
  
  <p>I boiled down my query for readability and am still getting the error in the various ways I've tried to execute it:</p>
  
  <pre><code>SELECT 
      STUFF((SELECT * 
             FROM
                 (SELECT N',' + N'first' 
                  UNION 
                  SELECT N',' + N'second') 
             FOR XML PATH('')), 1, 1, '')
  </code></pre>
  
  <p>Also tried:</p>
  
  <pre><code>SELECT 
      STUFF((SELECT * 
             FROM
                 (SELECT N',' + N'first' 
                  UNION 
                  SELECT N',' + N'second')) 
             FOR XML PATH(''), 1, 1, '')
  </code></pre>
  
  <p>For a while I was getting </p>
  
  <blockquote>
    <p>The FOR XML clause is invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the <code>SELECT</code> containing a set operator using derived table syntax and apply FOR XML on top of it.</p>
  </blockquote>
  
  <p>but amended the code per <a href="http://www.exacthelp.com/2012/04/for-xml-clause-is-invalid-in-views.html" rel="nofollow noreferrer">ExactHelp's post</a>.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Based on answer from @NenadZivkovic I came up with the following which did what I was looking to do:</p>
  
  <pre><code>WITH CTE_perca_categories AS
  (
      SELECT 
          category = STUFF((SELECT ', ' + category 
                            FROM perca_categories 
                            FOR XML PATH('')), 1, 2, '')
  ) , CTE_perca_tags AS
  (
      SELECT tag = (SELECT ', ' + tag from perca_tags FOR XML PATH(''))
  )
  SELECT 
      CONCAT((SELECT * FROM CTE_perca_categories),
             (SELECT * FROM CTE_perca_tags))
  </code></pre>
  
  <p>Output (where tag begins with 'Food'):</p>
  
  <pre><code>Charitable Giving, Nondiscretionary Spending, Saving, Discretionary Spending, Food, Dining, Groceries, Bills
  </code></pre>