locked
Split SQL RRS feed

  • Question

  • User-1740043572 posted

    How to split in  multiple row for sql query

    declare @Branded_Code varchar(3)='002|02|01|01'

    Wednesday, February 28, 2018 10:12 AM

All replies

  • User516094431 posted

    Thamu

    declare @Branded_Code varchar(3)='002|02|01|01'

    Create follow function in SQL:

    CREATE FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1))     

    returns @temptable TABLE (items varchar(8000))

    as     

    begin     

    declare @idx int     

    declare @slice varchar(8000)   

    select @idx = 1     

    if len(@String)<1 or @String is null  return     

    while @idx!= 0   

    begin     

    set @idx = charindex(@Delimiter,@String)     

    if @idx!=0 

    set @slice = left(@String,@idx - 1)     

    else   

    set @slice = @String   

    if(len(@slice)>0)

    insert into @temptable(Items) values(@slice)   

    set @String = right(@String,len(@String) - @idx)   

    if len(@String) = 0 break   

    end 

    return   

    end

    Call this function for split string as in rows:

    Select * from Split('002|02|01|01', '|')

    You will get required output.

    Refer From:

    https://www.codeproject.com/Tips/798671/Split-string-into-Rows-Columns-using-Delimiters

    Wednesday, February 28, 2018 10:50 AM
  • User753101303 posted

    Hi,

    If SQL Server 2016 or later you also have https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql

    Wednesday, February 28, 2018 12:00 PM
  • User77042963 posted
    --SQL Server 2016, 2017
    declare @Branded_Code varchar(30)='002|02|01|01'
    
    Select value from   string_split(@Branded_Code,'|')
    
    --if you cannot use string_split, you need a UDF split or some extra code
    
    --===== Create number table on-the-fly
    ;WITH Num1 (n) AS (
    SELECT 1 as n
    UNION ALL SELECT n+1 as n
    FROM Num1 Where n<101),
    Num2 (n) AS (SELECT 1 FROM Num1 AS X, Num1 AS Y),
    Nums (n) AS (SELECT ROW_NUMBER() OVER(ORDER BY n) FROM Num2)
     
    --load number table
    Select * into NumsTable
    from Nums
      
    ;with mycte as (
    select     
    substring(strCol, n, charindex('|', strCol + '|', n) - n)  splitData 
      
    from (select @Branded_Code as    strCol) t
    cross apply NumsTable
    Where n <= len(strCol) AND substring('|' + strCol, n, 1) = '|'
    )
    
    select splitData from mycte
    
    -- create a UDF split function search to find a sample code

    Wednesday, February 28, 2018 5:06 PM