title: Use STUFF() on a result set coming from OPENJSON
body: <p>I have a <code>ClassTable</code> as shown below with a <code>Languages</code> column in which the data is in JSON:</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>ID</th>
  <th>Title</th>
  <th>Languages</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>1</td>
  <td>Class1</td>
  <td>[{&quot;ID&quot;: 1, &quot;Name&quot;: &quot;English&quot;},{&quot;ID&quot;: 2, &quot;Name&quot;: &quot;Hindi&quot;}]</td>
  </tr>
  <tr>
  <td>2</td>
  <td>Class2</td>
  <td>[{&quot;ID&quot;: 1, &quot;Name&quot;: &quot;Marathi&quot;},{&quot;ID&quot;: 2, &quot;Name&quot;: &quot;Telugu&quot;}]</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>and a <code>Master</code> table of <code>Languages</code> as</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>ID</th>
  <th>Name</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>1</td>
  <td>English</td>
  </tr>
  <tr>
  <td>2</td>
  <td>Hindi</td>
  </tr>
  <tr>
  <td>3</td>
  <td>Marathi</td>
  </tr>
  <tr>
  <td>4</td>
  <td>Telugu</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>I need output as below</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>ID</th>
  <th>Title</th>
  <th>LanguageIDs</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>1</td>
  <td>TestTitle1</td>
  <td>1,2</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>I am trying to achieve this with <code>OPENJSON</code> to get data from <code>JSON</code> and then I am applying <code>STUFF()</code> to that data so that I would get comma separated LanguageIDs</p>
  <p>This is the query, I have written but I am not getting the expected output</p>
  <pre><code>SELECT 
      A.ID,
      A.Title,
      LanguageIDs = STUFF ((SELECT CONCAT(',',A.ID)
                            FROM Master.Languages
                            WHERE ID IN (A.LanguageID)
                            FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, SPACE(0))
  FROM
      (SELECT 
           X.ID,
           X.Title,
           X.CreatedOn,
           B.ID as LanguageID
       FROM 
           ClassTable X
       CROSS APPLY  
           OPENJSON(Languages)
               WITH (ID INT '$.ID') as B
       WHERE 
           X.ID = 1) AS A
  </code></pre>
  <p>Can anybody tell me whats the mistake I am making? Or do I have to try a different approach for this problem?</p>