Click here to Skip to main content
11,432,119 members (60,020 online)
Click here to Skip to main content

Tagged as

Split string into Rows / Columns using Delimiters

, 22 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This tip is to help anyone trying to split strings in SQL into Rows and Columns based on Row/Column Delimiters

Introduction

This small SQL snippet splits a String into Rows and Columns and returns a TABLE.

Background

5 years ago, I had developed a Hotel Management Application for one of my clients. Like all projects I did in those days, never really thought about the changes I was doing and the impact they would have on the application in future.

Anyways, recently the Hotel contacted me and asked me to show date wise Stock Update history Vs Items used.

The table I had designed back then was as follows:

Services Table
ServiceID Service Name Stock Stock Update History (Stock Added|Date)
1 TEA 14 4|22/05/13#5|04/06/13
2 MINERAL WATER 50 20|21/06/13#15|19/06/13#15|14/06/13

As you can see the Stock Update history column was stored a single string wherein line items were seperated by # and columns with a pipe sign. Every time stock was added, I would append #StockNo|Date to the Stock Update History column.

Since I now had to do some math on these values, it was essential to parse these values in a Table.

Using the code

I started by using a split function from SQLCentral.

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

To call the function you would simply write:

Select * from Split('20|21/06/13#15|19/06/13#15|14/06/13','#')

And what you would get is:

items
20|21/06/13
15|19/06/13
15|14/06/13

The function worked great, but it would only split the string into 1 column.

I looked up google and found a function shared by bvr on Stackoverflow which would split string into columns.

I merged these two functions and what I got was a Function that would split strings based on a Line delimiter (#) and a Column delimiter (pipe sign) and output to a Table.

 

DECLARE @SUH VARCHAR(2000);
SET @SUH=(Select [Stock Update History] from ServicesAvailable where ServiceID=1);
WITH Split_Names (Name, xmlname)
AS
(
    SELECT TA.items,
    CONVERT(XML,'<Names><name>'  
    + REPLACE(TA.items,'|', '</name><name>') + '</name></Names>') AS xmlname
      FROM (Select * from Split(@SUH,'#')) TA
)

 SELECT 
 xmlname.value('/Names[1]/name[1]','varchar(100)') AS Stock,    
 xmlname.value('/Names[1]/name[3]','varchar(100)') AS UpdatedOn
 FROM Split_Names

Points of Interest

As you can see the code is sourced from a couple of places. The reason I am sharing this is because it is difficult to find a single function that does that. I am sure people out there will have a better way of doing this and I acknowledge the fact that I am a noob when it comes to SQL.

Anyone with a better solution, please do share - we are all learners here (probably on different levels),

History

First version - no history.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

kasbaba

United States United States
No Biography provided

Comments and Discussions

 
SuggestionEasy way to split string Pin
Member 107271924-Jul-14 1:11
memberMember 107271924-Jul-14 1:11 
QuestionThe design of the tables Pin
Mika Wendelius20-Jul-14 2:50
mentorMika Wendelius20-Jul-14 2:50 
AnswerRe: The design of the tables Pin
kasbaba21-Jul-14 11:24
memberkasbaba21-Jul-14 11:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150428.2 | Last Updated 22 Jul 2014
Article Copyright 2014 by kasbaba
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid