Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This can be cleaned up/optimized and is intentionally verbose but should get you started. Notably, the logic inside the last IF is almost identical to that of the WHILE and the block that gets the numeric value of the left/right elements is repeated four times.</p> <pre><code>declare @input varchar(max) set @input = 'R1,R15-R19,RN5-RN6' select @input declare @elements table ( Element varchar(10), [Count] int ) declare @element varchar(10) declare @index int declare @count int declare @left varchar(10) declare @right varchar(10) declare @position int while (len(@input) &gt; 0 and charindex(',', @input) &gt; 0) begin set @element = substring(@input, 0, charindex(',', @input)) if (charindex('-', @element) &gt; 0) begin set @index = charindex('-', @element) set @left = left(@element, @index - 1) set @right = substring(@element, @index + 1, len(@element) - len(@left)) set @position = 0 while (isnumeric(substring(@left, @position, 1)) = 0) begin set @position = @position + 1 end set @left = substring(@left, @position, len(@left)) set @position = 0 while (isnumeric(substring(@right, @position, 1)) = 0) begin set @position = @position + 1 end set @right = substring(@right, @position, len(@right)) set @count = cast(@right as int) - cast(@left as int) + 1 end else begin set @count = 1 end insert into @elements select @element, @count set @input = replace(@input, @element + ',', '') end if (len(@input) &gt; 0) begin set @element = @input if (charindex('-', @element) &gt; 0) begin set @index = charindex('-', @element) set @left = left(@element, @index - 1) set @right = substring(@element, @index + 1, len(@element) - len(@left)) set @position = 0 while (isnumeric(substring(@left, @position, 1)) = 0) begin set @position = @position + 1 end set @left = substring(@left, @position, len(@left)) set @position = 0 while (isnumeric(substring(@right, @position, 1)) = 0) begin set @position = @position + 1 end set @right = substring(@right, @position, len(@right)) set @count = cast(@right as int) - cast(@left as int) + 1 end else begin set @count = 1 end insert into @elements select @element, @count end select * from @elements select sum([Count]) from @elements </code></pre> <p>Outputs the following results:</p> <pre><code>R1,R15-R19,RN5-RN6 R1 1 R15-R19 5 RN5-RN6 2 8 </code></pre>
 

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