Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a single string into two different columns sql

I have two columns and I want to create a splitting function that will accept a single string and put every two consecutive numbers into my columns.

for example:

If my string was (1,5,2,20,3,9).

The result should be:

size   quantity
 1   |  5
 2   |  20
 3   |  9

Here is the code that I have been trying with it:

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

I appreciate the help.

like image 599
Nysa Avatar asked Feb 24 '26 20:02

Nysa


1 Answers

Using 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
like image 195
Squirrel Avatar answered Feb 26 '26 10:02

Squirrel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!