I agree with others that your problem would seem to be indicative of a mistake in your data design.
However, accepting that you cannot change the design, the following would allow you to achieve what you are looking for:
DECLARE @InstructorID VARCHAR(100)
DECLARE @Part VARCHAR(100)
DECLARE @Pos INT
DECLARE @Return VARCHAR(100)
SET @InstructorID = '79,instr1,inst2,13'
SET @Return = ''
-- Continue until InstructorID is empty
WHILE (LEN(@InstructorID) > 0)
BEGIN
-- Get the position of the next comma, and set to the end of InstructorID if there are no more
SET @Pos = CHARINDEX(',', @InstructorID)
IF (@Pos = 0)
SET @Pos = LEN(@InstructorID)
-- Get the next part of the text and shorted InstructorID
SET @Part = SUBSTRING(@InstructorID, 1, @Pos)
SET @InstructorID = RIGHT(@InstructorID, LEN(@InstructorID) - @Pos)
-- Check that the part is numeric
IF (ISNUMERIC(@Part) = 1)
SET @Return = @Return + @Part
END
-- Trim trailing comma (if any)
IF (RIGHT(@Return, 1) = ',')
SET @Return = LEFT(@Return, LEN(@Return) - 1)
PRINT @Return
Essentially, this loops through the @InstructorID
, extracting parts of text between commas.
If the part is numeric then it adds it to the output text. I am PRINT
ing the text but you could SELECT
it or use it however you wish.
Obviously, where I have SET @InstructorID = xyz
, you should change this to your SELECT
statement.
This code can be placed into a UDF
if preferred, although as I say, your data format seems less than ideal.