If have a string passed from a .Net application that looks like the below
2023|F66451,1684|648521,1684|600271,2137|019592
I have started to parse out the string using the method below but I need to Pivot the data returned from the Split ( surrounded by *'s) function in order to insert into the #tmpExceptions table
DECLARE @ExceptionsList as nvarchar(MAX)
SET @ExceptionsList = '2023|F66451,1684|648521,1684|600271,2137|019592'
SET NOCOUNT ON;
DECLARE @CurrentLineItem as nvarchar(255)
CREATE TABLE #ParsePassOne
(
LineItem nvarchar(255)
)
CREATE TABLE #tmpExceptions
(
AccountNumber int,
ClaimNumber nvarchar(50)
)
INSERT INTO #ParsePassOne
SELECT value FROM Split( ',' ,@ExceptionsList)
WHILE EXISTS(SELECT LineItem FROM #ParsePassOne)
BEGIN
SELECT TOP 1 @CurrentLineItem = LineItem FROM #ParsePassOne
*******
SELECT value FROM Split( '|' ,@CurrentLineItem)
*******
DELETE FROM #ParsePassOne WHERE LineItem = @CurrentLineItem
END
SELECT * FROM #tmpExceptions
DROP TABLE #ParsePassOne
DROP TABLE #tmpExceptions
So far the data returned looks as below. I just need to pivot the data to columns so I can insert it. How do I go about this?
Split Function
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Creates an 'InLine' Table Valued Function (TVF)
ALTER FUNCTION [dbo].[Split]
( @Delimiter varchar(5),
@List varchar(8000)
)
RETURNS @TableOfValues table
( RowID smallint IDENTITY(1,1),
[Value] varchar(50)
)
AS
BEGIN
DECLARE @LenString int
WHILE len( @List ) > 0
BEGIN
SELECT @LenString =
(CASE charindex( @Delimiter, @List )
WHEN 0 THEN len( @List )
ELSE ( charindex( @Delimiter, @List ) -1 )
END
)
INSERT INTO @TableOfValues
SELECT substring( @List, 1, @LenString )
SELECT @List =
(CASE ( len( @List ) - @LenString )
WHEN 0 THEN ''
ELSE right( @List, len( @List ) - @LenString - 1 )
END
)
END
RETURN
END
If you are using SQL Server 2016 you can use String_Split() function and use cross apply/pivot to get into single row
create table #t (v varchar(50), i int)
insert into #t (v, i) values ('2023|F66451',1)
,('1684|648521',2), ('1684|600271', 3), ('2137|019592', 4)
--Inorder to get into same row -pivoting the data
select * from (
select * from #t t cross apply (select RowN=Row_Number() over (Order by (SELECT NULL)), value from string_split(t.v, '|') ) d) src
pivot (max(value) for src.RowN in([1],[2])) p
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With