Click here to Skip to main content
Click here to Skip to main content

An Easy But Effective Way to Split a String using Transact-SQL

By , 9 Aug 2009
 

Figure: Output

Introduction

In this article, I will demonstrate how to split a string using Transact-SQL.

Background

String manipulation is pretty interesting for most software developers. To split a string by using a user defined delimiter is nothing new for programmers. Even Microsoft .NET Frameworks provide us a huge "Standard Techniques" for doing this. But if we want to split a string using Transact -SQL, then how can we achieve this?

Using the Code

It is very simple to use. We just need some basic concepts on the following:

  • CHARINDEX
  • SUBSTRING
CHARINDEX

Returns the starting position of the specified expression in a character string.

Syntax
CHARINDEX ( expression1 , expression2 [ , start_location ] ) 
Arguments

expression1: An expression containing the sequence of characters to be found. expression1 is an expression of the short character data type category.

expression2: An expression, usually a column searched for the specified sequence. expression2 is of the character string data type category.

start_location: The character position to start searching for expression1 in expression2. If start_location is not given, is a negative number, or is zero, the search starts at the beginning of expression2.

Return Types: int

Example
USE pubs
GO
SELECT CHARINDEX('wonderful', notes)
FROM titles
WHERE title_id = 'TC3218'
GO

More details can be found at this link.

SUBSTRING

Returns part of a character, binary, text, or image expression for more information about the valid Microsoft® SQL Server™ data types that can be used with this function.

Syntax
SUBSTRING ( expression , start , length ) 
Arguments

Expression: A character string, binary string, text, image, a column, or an expression that includes a column. Do not use expressions that include aggregate functions.

Start: An integer that specifies where the SUBSTRING begins.

Length: An integer that specifies the length of the SUBSTRING (the number of characters or bytes to return).

Note: Because start and length specify the number of bytes when SUBSTRING is used on text data, DBCS data, such as Kanji, may result in split characters at the beginning or end of the result. This behavior is consistent with the way in which READTEXT handles DBCS. However, because of the occasional strange result, it is advisable to use ntext instead of text for DBCS characters.

Return Types: Returns character data if expression is one of the supported character data types. Returns binary data if expression is one of the supported binary data types.

Example
USE pubs
SELECT au_lname, SUBSTRING(au_fname, 1, 1)
FROM authors
ORDER BY au_lname

More details can be found at this link.

I wrote a simple function named SPLITE which will split an expression using CHARINDEX and SUBSTRING functions. A sample code example is given below:

Sample Example

            set QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Md. Marufuzzaman
-- Create date: 
-- Description: Split an expression. 
-- Note: If you are using SQL Server 2000, You need to change the 
-- length (MAX) to your maximum expression length of each datatype.
-- =============================================
/*
SELECT * FROM [dbo].[SPLIT] (';','I love codeProject;!!!;Your development resources')
*/
CREATE FUNCTION [dbo].[SPLIT] 
   (  @DELIMITER VARCHAR(5), 
      @LIST      VARCHAR(MAX) 
   ) 
   RETURNS @TABLEOFVALUES TABLE 
      (  ROWID   SMALLINT IDENTITY(1,1), 
         [VALUE] VARCHAR(MAX) 
      ) 
AS 
   BEGIN
    
      DECLARE @LENSTRING INT 
 
      WHILE LEN( @LIST ) > 0 
         BEGIN 
         
            SELECT @LENSTRING = 
               (CASE CHARINDEX( @DELIMITER, @LIST ) 
                   WHEN 0 THEN LEN( @LIST ) 
                   ELSE ( CHARINDEX( @DELIMITER, @LIST ) -1 )
                END
               ) 
                                
            INSERT INTO @TABLEOFVALUES 
               SELECT SUBSTRING( @LIST, 1, @LENSTRING )
                
            SELECT @LIST = 
               (CASE ( LEN( @LIST ) - @LENSTRING ) 
                   WHEN 0 THEN '' 
                   ELSE RIGHT( @LIST, LEN( @LIST ) - @LENSTRING - 1 ) 
                END
               ) 
         END
          
      RETURN 
      
   END

Note: I have used some other functions like LNE(), LEFT(), etc. which are very common and I hope that everyone is very much familiar with this. Hence, I did not include this. Actually I do not want to lose focus on the main objective of this article.

Conclusion

I hope that this article might be helpful to you. Enjoy!

History

  • 9th August 2009: Initial post

License

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

About the Author

Md. Marufuzzaman
CEO
Bangladesh Bangladesh
He is the founder & CEO of MNH Technologies and working for urban and rural sectors to improve people’s lifestyle, better medical facilities, education, social business etc. He has over ten years of professional experiences in design and developing Client-Server, Multi-Tier, Database, Web based business software solutions, Enterprise Applications, API, WebAPI, Google Analytics implementation, Add-In, Documentation & Technical Writing etc for Windows / Mac using Microsoft SQL Server, Oracle, MySql, PS, C#, VB.NET, ASP.NET, PHP, RoR, Visual Basic etc. He has also more than two years experience in Mobile-VAS (Platform Development).
 
He worked for various software development & technology consulting. His core focus on technologies to create dynamic data-driven systems that add value to your business and dynamic technology consulting that builds advanced solutions for the industries across the various vertices.
 
He also work as a Solution Architect at Dhrupadi Techno Consortium Limited (DTCL) and responsible for analyzing business requirements and offered optimum solutions (multiple options), which would address all current requirements, provide flexibility for future growth and allow smooth transition between old system and new system.
 
He graduated with honors from The University of Asia Pacific, in Computer Science and Engineering. He was awarded as “Most Valuable Professional” (MVP) at 2010 and 2011 by CodeProject.com and also selected as a Mentor of CodeProject.com
 
Specialties: Software Development Management, System Integration, Data Warehouse Architecture, Virtualization.
Follow on   Twitter

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberom28-Mar-13 6:49 
I like your Armani t-shirt!
GeneralRe: My vote of 5mentorMd. Marufuzzaman28-Mar-13 7:53 
Thanks, but I don't think this could help you anymore in transect sql.
 
Thanks
Md. <b style="color: #FF9900"> M</b>arufuzzaman
<hr></hr>
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.
QuestionA simpler (faster?) Split function using XMLmemberBamboozled21-Nov-12 10:14 
I really enjoy making utility functions like this - you invest a bit of time then find yourself re-using the tools again and again.
My own attempt at a split function led me into querying XML which was a bit of an eye-opener.
http://www.capricornexcel.co.uk/sql-split-function/[^]
 
I'm not sure if my way is faster (if anyone wants to test it, I'd be interested to hear), but it is certainly neater, and uses some cool functionality Smile | :)
AnswerRe: A simpler (faster?) Split function using XMLmentorMd. Marufuzzaman23-Nov-12 3:19 
Thanks Thumbs Up | :thumbsup:
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

Questionarticle: An Easy But Effective Way to Split a String using Transact-SQLmemberSupriya Srivastav8-Dec-11 18:37 
Nice Article!!!!!
AnswerRe: article: An Easy But Effective Way to Split a String using Transact-SQLmvpMd. Marufuzzaman9-Dec-11 4:50 
Thanks Smile | :)
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

GeneralGoodmemberShahadat Alam20-Mar-10 20:17 
Good work.
GeneralRe: GoodmvpMd. Marufuzzaman20-Mar-10 20:19 
Thanks.
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

GeneralMy vote of 1memberkookai9-Aug-09 15:58 
slow when split string has 1M length
when split large string should implement CLR assembly and deploy it to sql
GeneralRe: My vote of 1groupMd. Marufuzzaman9-Aug-09 16:36 
Thanks for your suggetion / comments.Smile | :)
 
Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

GeneralRe: My vote of 1memberedobrzel10-Aug-09 5:10 
For SQL 2005 and up, you can also use some of the XML features to split the string. I have not tested it on very large sets, but it can be a good compromise between manual string manipulation which is slow and implementing CLR code in SQL Server (not something all companies allow you to do).
 
http://www.sqlservercentral.com/articles/XML/66932/[^]
GeneralRe: My vote of 1groupMd. Marufuzzaman10-Aug-09 5:28 
Thanks for your suggetions.....Smile | :)
 
Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

GeneralRe: My vote of 1memberRugbyLeague25-Apr-12 21:36 
Hardly worth a 1 vote though.
GeneralRe: My vote of 1memberErion Pici9-Aug-12 1:14 
How about you give a better solution instead of ranting on a working one
GeneralRe: My vote of 1memberRugbyLeague9-Aug-12 1:15 
My post was in reply to the person who voted 1, not the actual article. I was saying the article is worth more than a 1 vote.
GeneralRe: My vote of 1memberErion Pici9-Aug-12 1:42 
I misunderstood.
Agreed. It's worth at least 3 Smile | :)

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130617.1 | Last Updated 9 Aug 2009
Article Copyright 2009 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid