title: Get characters before underscore and separated by comma from a string in SQL Server 2008
body: <p>I tried this query</p>
  
  <pre><code> DECLARE @AdvancedSearchSelectedDropdownName TABLE (
      SelectedIds VARCHAR(2048),
      AdvanceSearchOptionTypeId INT
  )
  
  INSERT INTO @AdvancedSearchSelectedDropdownName
  VALUES ('4_0,5_1,6_2,7_3', 23),
         ('62_3', 21), ('2_4', 23)
  
  DECLARE @selectedIds VARCHAR(MAX) = '';
  
  SELECT @selectedIds +=
      CASE WHEN SelectedIds IS NULL
              THEN  @selectedIds  +  ISNULL(SelectedIds + ',', '')
           WHEN SelectedIds IS NOT NULL
              THEN  SUBSTRING(SelectedIds, 0, CHARINDEX('_', SelectedIds, 0)) + ','
      END
     FROM @AdvancedSearchSelectedDropdownName WHERE advanceSearchOptionTypeId = 23
  
  SELECT @selectedIds
  </code></pre>
  
  <p>Current output: 4,2</p>
  
  <p>Required output: 4,5,6,7,2</p>
  
  <p>We may have n number of comma separated values in the <code>SelectedIds</code> column.</p>