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

, 9 Aug 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
This article will demonstrate how to split a string using Transact-SQL.

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)

Share

About the Author

Md. Marufuzzaman
CEO
Bangladesh Bangladesh
A highly experienced leader with successful track record of software development, product innovations, brand management and corporate communication etc. Some successful product innovations have also achieved and awards “Most Valuable Professional” (MVP) at 2010 and 2011 by codeproject.com and also selected as a mentor of codeproject.com. Published over 100 technical articles in various software development resource sites (i.e., codeprojetc.com, Microsoft MSDN, and IEEE & IBM (In progress)) and various IT Forums, Blogs etc.
 
Over ten years of professional experiences in ICT field having extensive experience in formulating corporate vision and long term strategy. Leading development related functions including design, development, services, data management and analytics, customer experience management, content services, digital analytics and optimization.
 
An individual with results-driven approach and relentless in pursuit of excellence from a business and organizational standpoint. Believes in transparency, commitment and teamwork.
 
Expertise: Software/Solution Architect, SaaS platform base application, Large scale win32/web based business software solutions, enterprise applications, integration, etc.
 
Technologies/Tools: Microsoft.Net version 05/08/10/12, Microsoft SQL Server version 7/2K/05/08/12 , Oracle version 10/11, MySql version 5.1, 5.5, PS2, Visual C#, R, VB.NET, ASP.NET, PHP, API, MVC, WebAPI , Add-In Visual Basic etc.,. I have also more than two years’ of strong experience in mobile-VAS (platform development).
 
Points of Interest: Technology and research & development especially focused on business functionalities and social business areas as well, few stuff including:
 
1.R&D on new techniques as required to increase business revenue.
2.Urban and rural sectors to improve people’s lifestyle, better medical facilities, education, social business etc., using innovative technical solutions.
3.Research and innovative product development.
4.Etc.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
QuestionGood but has a problem with long strings Pinmemberosperez16-Jun-14 8:03 
AnswerRe: Good but has a problem with long strings PinmentorMd. Marufuzzaman7-Aug-14 11:17 
QuestionMessage Automatically Removed Pinmemberrba12321-May-14 21:16 
GeneralMy vote of 5 Pinmembersam2222220-Nov-13 22:56 
GeneralRe: My vote of 5 PinmentorMd. Marufuzzaman7-Aug-14 11:18 
GeneralMy vote of 1 PinmemberKrishnendu Gupta13-Nov-13 23:45 
GeneralRe: My vote of 1 PinmentorMd. Marufuzzaman7-Aug-14 11:23 
GeneralMy vote of 5 Pinmemberom28-Mar-13 7:49 
GeneralRe: My vote of 5 PinmentorMd. Marufuzzaman28-Mar-13 8:53 
QuestionA simpler (faster?) Split function using XML PinmemberBamboozled21-Nov-12 11:14 
AnswerRe: A simpler (faster?) Split function using XML PinmentorMd. Marufuzzaman23-Nov-12 4:19 
Questionarticle: An Easy But Effective Way to Split a String using Transact-SQL PinmemberSupriya Srivastav8-Dec-11 19:37 
AnswerRe: article: An Easy But Effective Way to Split a String using Transact-SQL PinmvpMd. Marufuzzaman9-Dec-11 5:50 
GeneralGood PinmemberShahadat Alam20-Mar-10 21:17 
GeneralRe: Good PinmvpMd. Marufuzzaman20-Mar-10 21:19 
GeneralMy vote of 1 Pinmemberkookai9-Aug-09 16:58 
GeneralRe: My vote of 1 PingroupMd. Marufuzzaman9-Aug-09 17:36 
GeneralRe: My vote of 1 Pinmemberedobrzel10-Aug-09 6:10 
GeneralRe: My vote of 1 PingroupMd. Marufuzzaman10-Aug-09 6:28 
GeneralRe: My vote of 1 PinmemberRugbyLeague25-Apr-12 22:36 
GeneralRe: My vote of 1 PinmemberErion Pici9-Aug-12 2:14 
GeneralRe: My vote of 1 PinmemberRugbyLeague9-Aug-12 2:15 
GeneralRe: My vote of 1 PinmemberErion Pici9-Aug-12 2:42 

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
Web02 | 2.8.1411028.1 | Last Updated 9 Aug 2009
Article Copyright 2009 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid