need help filling in the blanks i am struggling with splitting a variable into 6 variables.
DECLARE @item VARCHAR(MAX) = 'MG1111.TG2222.MW3333.JG4444.MG5555.MH6666'
DECLARE @item1 VARCHAR(MAX)
DECLARE @item2 VARCHAR(MAX)
DECLARE @item3 VARCHAR(MAX)
DECLARE @item4 VARCHAR(MAX)
DECLARE @item5 VARCHAR(MAX)
DECLARE @item6 VARCHAR(MAX)
set @item1 = (SUBSTRING( @item, 0, CHARINDEX('.', @item)))
set @item2 = (SUBSTRING(SUBSTRING( @item, CHARINDEX('.', @item)+1,LEN(@ITEM)),0,CHARINDEX('.', SUBSTRING( @item, CHARINDEX('.', @item)+1,LEN(@ITEM))) ))
set @item6 = (REVERSE(SUBSTRING( REVERSE(@ITEM), 0, CHARINDEX('.' , REVERSE(@ITEM)))))
print @item1
print @item2
print @item3
print @item4
print @item5
print @item6
Just about any String Parser will do. That said, I have one that will return (currently) up to 9 variables
Select @item1=Pos1
,@item2=Pos2
,@item3=Pos3
,@item4=Pos4
,@item5=Pos5
,@item6=Pos6
From [dbo].[udf-Str-Parse-Row](@Item,'.')
The UDF
CREATE FUNCTION [dbo].[udf-Str-Parse-Row] (@String varchar(max),@Delimeter varchar(10))
--Usage: Select * from [dbo].[udf-Str-Parse-Row]('Dog,Cat,House,Car',',')
-- Select * from [dbo].[udf-Str-Parse-Row]('John Cappelletti',' ')
-- Select * from [dbo].[udf-Str-Parse-Row]('id26,id46|id658,id967','|')
Returns Table
As
Return (
SELECT Pos1 = xDim.value('/x[1]','varchar(250)')
,Pos2 = xDim.value('/x[2]','varchar(250)')
,Pos3 = xDim.value('/x[3]','varchar(250)')
,Pos4 = xDim.value('/x[4]','varchar(250)')
,Pos5 = xDim.value('/x[5]','varchar(250)')
,Pos6 = xDim.value('/x[6]','varchar(250)')
,Pos7 = xDim.value('/x[7]','varchar(250)')
,Pos8 = xDim.value('/x[8]','varchar(250)')
,Pos9 = xDim.value('/x[9]','varchar(250)')
FROM (Select Cast('<x>' + Replace(@String,@Delimeter,'</x><x>')+'</x>' as XML) as xDim) A
)