gpt4 book ai didi

sql - 拆分字符串然后旋转结果

转载 作者:行者123 更新时间:2023-12-05 00:50:43 25 4
gpt4 key购买 nike

如果有一个从 .Net 应用程序传递的字符串,如下所示

2023|F66451,1684|648521,1684|600271,2137|019592

我已经开始使用下面的方法解析出字符串,但我需要透视从 Split(由 * 包围)函数返回的数据,以便插入到 #tmpExceptions 表中

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

到目前为止,返回的数据如下所示。我只需要将数据旋转到列,以便我可以插入它。我该怎么办?

enter image description here

分割函数

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

最佳答案

如果您使用的是 SQL Server 2016,您可以使用 String_Split() 函数并使用交叉应用/透视进入单行

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

关于sql - 拆分字符串然后旋转结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12195504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com