我有两列,我想创建一个拆分函数,它将接受一个字符串并将每两个连续的数字放入我的列中。
例如:
如果我的字符串是 (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
我很感激帮助。
答案 0 :(得分:3)
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
答案 1 :(得分:1)
请参阅以下内容可能会解释您
DECLARE @Result TABLE
(
Size BIGINT ,
Quantity BIGINT
)
DECLARE @str INT ,
@input VARCHAR(MAX) = '1,20,2,10,3,15,5,20'
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))
SET @ind = CHARINDEX(',', @input)
IF ( @ind > 0 )
BEGIN
SET @strQ = SUBSTRING(@input, 1, @ind - 1)
SET @input = SUBSTRING(@input, @ind + 1, LEN(@input))
END
ELSE
BEGIN
SET @strQ = @input
END
INSERT INTO @Result
( Size, Quantity )
VALUES ( @str, @strQ )
SET @ind = CHARINDEX(',', @input)
SET @str = NULL
SET @strQ = NULL
END
END
SELECT *
FROM @Result
答案 2 :(得分:0)
使用XML和递归CTE的另一种方法:
var1 var2 var3 var4
1 site1 <NA> site1 site1
2 <NA> <NA> <NA> <NA>
3 <NA> <NA> Site2 Site2
4 <NA> site2 site2 site2
5 site3 <NA> site3 site3
6 site4 site4 <NA> site4
我们得到XML:
DECLARE @string nvarchar(max) = N'1,5,2,20,3,9',
@xml xml
;WITH cte AS (
SELECT STUFF(@string,CHARINDEX(',',@string),1,'</a><b>') s, 1 as LEV
UNION ALL
SELECT CASE WHEN LEV % 2 = 0 THEN STUFF(s,CHARINDEX(',',s),1,'</a><b>')
ELSE STUFF(s,CHARINDEX(',',s),1,'</b></s><s><a>') END, LEV + 1
FROM cte
WHERE LEV < (LEN(@string) - LEN(REPLACE(@string,',','')))
)
SELECT TOP 1 @xml = CAST('<s><a>' + s + '</b></s>' as xml)
FROM cte
ORDER BY LEV DESC
SELECT t.v.value('a[1]', 'int') as size,
t.v.value('b[1]', 'int') as quantity
FROM @xml.nodes('/s') as t(v)
输出:
<s>
<a>1</a>
<b>5</b>
</s>
<s>
<a>2</a>
<b>20</b>
</s>
<s>
<a>3</a>
<b>9</b>
</s>