I have a string like:
@TempCol = sigma_x1,sigma_x2,…,sigma_xd,XX,YY,ZZ
So how could I get a specific part of that string, based on, lets say an index.
so
- if index is 0, get sigma_x1
- if index is 1, get sigma_x2
- if index is 2, get sigma_x3
- if index is d-1,get sigma_xd
- if index is d, get XX,
- if index is d+1,get YY
and so on.
Previously Andriy M solved a similar issue, his code gets a substring based on a nomber but returns a substring the following way:
- if @d is 1,get sigma_x1
- if @d is 2,get sigma_x1,sigma_x2
- if @d is 3,get sigma_x1,sigma_x2,sigma_x3
- if @d is 4,get sigma_x1,sigma_x2,sigma_x3,sigma_x4
- if @d is d,get sigma_x1,sigma_x2,sigma_x3,sigma_x4,…,sigma_xd (ALL THE STRING)
How to update this procedure to get specific element?
DECLARE @TempCol varchar(max), @d int, @p int, @Result varchar(max);
SET @TempCol = 'item1,item2,itemA,itemB,item#,item$';
SET @d = 3;
SET @p = 1;
WHILE @d > 0 AND @p > 0 BEGIN
SET @p = CHARINDEX(',', @TempCol, @p);
IF @p > 0 SET @p = @p + 1;
SET @d = @d - 1;
END;
IF @p = 0
SET @Result = @TempCol
ELSE
SET @Result = SUBSTRING(@TempCol, 1, @p - 2);
SELECT @Result;
just try this. hope this will meet your needs.
create a function
GetIndex, which accepts string and delimiter to split the stringand you can query like,
suppose you need 4th index then
to get an item of 4th index then
to get item to a variable