gpt4 book ai didi

sql - 如何将单个字符串拆分为两个不同的列 sql

转载 作者:行者123 更新时间:2023-12-04 13:49:23 28 4
gpt4 key购买 nike

我有两列,我想创建一个拆分函数,它将接受一个字符串并将每两个连续数字放入我的列中。

例如:

如果我的字符串是(1,5,2,20,3,9).

结果应该是:

size   quantity
1 | 5
2 | 20
3 | 9

这是我一直在尝试的代码:

create FUNCTION [dbo].[getSizesAndQuantity1](@input AS Varchar(4000) )
RETURNS
@Result TABLE(Size BIGINT, Quantity BIGINT)
AS
BEGIN
DECLARE @str int
DECLARE @strQ int
DECLARE @ind Int
IF(@input is not null)
BEGIN
SET @ind = CharIndex(',',@input)
WHILE @ind > 0
BEGIN
SET @str = SUBSTRING(@input,1,@ind-1)
SET @input = SUBSTRING(@input,@ind+1,LEN(@input)-@ind)
SET @strQ = SUBSTRING(@input,1,@ind-1)
SET @input = SUBSTRING(@input,@ind+1,LEN(@input)-@ind)
INSERT INTO @Result(Size,Quantity) values (@str,@strQ)
SET @ind = CharIndex(',',@input)
END


END
RETURN
END

感谢您的帮助。

最佳答案

使用 DelimitedSplit8K

select  size = max(case when ItemNumber % 2 = 1 then Item end),
quantity = max(case when ItemNumber % 2 = 0 then Item end)
from DelimitedSplit8K('1,5,2,20,3,9', ',')
group by (ItemNumber - 1) / 2

关于sql - 如何将单个字符串拆分为两个不同的列 sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37647815/

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