Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It would help if we knew <em>why</em> you can't use a loop, but you can either use a custom CLR function (which might use a loop behind the scenes) or <a href="http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/4126a010-6885-4eb0-b79c-c798c90edb85" rel="nofollow">XQuery</a>:</p> <pre><code>DECLARE @S varchar(max), @Split char(1), @X xml SELECT @S = '1,2,3,4,5', @Split = ',' SELECT @X = CONVERT(xml,'&lt;root&gt;&lt;s&gt;' + REPLACE(@S,@Split,'&lt;/s&gt;&lt;s&gt;') + '&lt;/s&gt;&lt;/root&gt;') SELECT [Value] = T.c.value('.','varchar(20)') FROM @X.nodes('/root/s') T(c) </code></pre> <p>Then to get only the third (or whatever ordinal you want) string you can use a <code>ROW_NUMBER</code>-based solution to pick out the row you care about.</p> <p>EDIT: Based on the question in the comment, here's a solution for retrieving the third string. You kind of have to fake out the <code>ROW_NUMBER</code> ordering due to the fact that you don't have any data-based ordering to impose. Normally it won't let you <code>ORDER BY</code> a constant, but the <code>CASE</code> statement gets around that. Change the <code>WHERE iq.Ordinal = 3</code> to whatever you want to retrieve the string you want:</p> <pre><code>DECLARE @S varchar(max), @Split char(1), @X xml SELECT @S = '1,2,3,4,5', @Split = ',' SELECT @X = CONVERT(xml,'&lt;root&gt;&lt;s&gt;' + REPLACE(@S,@Split,'&lt;/s&gt;&lt;s&gt;') + '&lt;/s&gt;&lt;/root&gt;') SELECT TOP 1 Value FROM ( SELECT [Value] = T.c.value('.','varchar(20)'), ROW_NUMBER() OVER (ORDER BY CASE WHEN T.c.value('.', 'varchar(20)') = 0 THEN 0 ELSE 0 END ASC) AS Ordinal FROM @X.nodes('/root/s') T(c) ) iq WHERE iq.Ordinal = 3 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload