I have the following three different strings which needs to split into three different columns.
Example:
String 1:
Declare @
If you have atmost three values then try this.
DECLARE @str1 VARCHAR(max) = 'A1,A2,A3'
SELECT Parsename(Replace(@str1, ',', '.'), 3) 'FST_COL',
Parsename(Replace(@str1, ',', '.'), 2) 'SCD_COL',
Parsename(Replace(@str1, ',', '.'), 1) 'TRD_COL' into #temp
Or
DECLARE @str1 VARCHAR(max) = 'A1,A2,A3',
@sql NVARCHAR(max),
@loop INT,
@cnt INT=1
SELECT @loop = Len(@str1) - Len(Replace(@str1, ',', '')) + 1
SET @sql=' WITH Split_cols ( xmlcol)
AS (SELECT CONVERT(XML, '' ''
+ Replace('''
+ @str1 + ''', '','', '' '') + '' '') as xmlcol)
SELECT '
WHILE @cnt <= @loop
BEGIN
SET @sql+=' xmlcol.value(''/cols[1]/col['
+ CONVERT(VARCHAR(30), @cnt)
+ ']'', ''varchar(100)'') AS col'
+ CONVERT(VARCHAR(30), @cnt) + ','
SET @cnt=@cnt + 1
END
SET @sql=LEFT(@sql, Len(@sql) - 1)
SET @sql +=' FROM Split_cols '
--PRINT @sql
EXEC Sp_executesql @sql