Extract full name into different columns (First, Middle, Last) [duplicate] - sql

I have a table like this
Value String
-------------------
1 Cleo, Smith
I want to separate the comma delimited string into two columns
Value Name Surname
-------------------
1 Cleo Smith
I need only two fixed extra columns

Your purpose can be solved using following query -
Select Value , Substring(FullName, 1,Charindex(',', FullName)-1) as Name,
Substring(FullName, Charindex(',', FullName)+1, LEN(FullName)) as Surname
from Table1
There is no readymade Split function in sql server, so we need to create user defined function.
CREATE FUNCTION Split (
#InputString VARCHAR(8000),
#Delimiter VARCHAR(50)
)
RETURNS #Items TABLE (
Item VARCHAR(8000)
)
AS
BEGIN
IF #Delimiter = ' '
BEGIN
SET #Delimiter = ','
SET #InputString = REPLACE(#InputString, ' ', #Delimiter)
END
IF (#Delimiter IS NULL OR #Delimiter = '')
SET #Delimiter = ','
--INSERT INTO #Items VALUES (#Delimiter) -- Diagnostic
--INSERT INTO #Items VALUES (#InputString) -- Diagnostic
DECLARE #Item VARCHAR(8000)
DECLARE #ItemList VARCHAR(8000)
DECLARE #DelimIndex INT
SET #ItemList = #InputString
SET #DelimIndex = CHARINDEX(#Delimiter, #ItemList, 0)
WHILE (#DelimIndex != 0)
BEGIN
SET #Item = SUBSTRING(#ItemList, 0, #DelimIndex)
INSERT INTO #Items VALUES (#Item)
-- Set #ItemList = #ItemList minus one less item
SET #ItemList = SUBSTRING(#ItemList, #DelimIndex+1, LEN(#ItemList)-#DelimIndex)
SET #DelimIndex = CHARINDEX(#Delimiter, #ItemList, 0)
END -- End WHILE
IF #Item IS NOT NULL -- At least one delimiter was encountered in #InputString
BEGIN
SET #Item = #ItemList
INSERT INTO #Items VALUES (#Item)
END
-- No delimiters were encountered in #InputString, so just return #InputString
ELSE INSERT INTO #Items VALUES (#InputString)
RETURN
END -- End Function
GO
---- Set Permissions
--GRANT SELECT ON Split TO UserRole1
--GRANT SELECT ON Split TO UserRole2
--GO

;WITH Split_Names (Value,Name, xmlname)
AS
(
SELECT Value,
Name,
CONVERT(XML,'<Names><name>'
+ REPLACE(Name,',', '</name><name>') + '</name></Names>') AS xmlname
FROM tblnames
)
SELECT Value,
xmlname.value('/Names[1]/name[1]','varchar(100)') AS Name,
xmlname.value('/Names[1]/name[2]','varchar(100)') AS Surname
FROM Split_Names
and also check the link below for reference
http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html

xml based answer is simple and clean
refer this
DECLARE #S varchar(max),
#Split char(1),
#X xml
SELECT #S = 'ab,cd,ef,gh,ij',
#Split = ','
SELECT #X = CONVERT(xml,' <root> <myvalue>' +
REPLACE(#S,#Split,'</myvalue> <myvalue>') + '</myvalue> </root> ')
SELECT T.c.value('.','varchar(20)'), --retrieve ALL values at once
T.c.value('(/root/myvalue)[1]','VARCHAR(20)') , --retrieve index 1 only, which is the 'ab'
T.c.value('(/root/myvalue)[2]','VARCHAR(20)')
FROM #X.nodes('/root/myvalue') T(c)

I think this is cool
SELECT value,
PARSENAME(REPLACE(String,',','.'),2) 'Name' ,
PARSENAME(REPLACE(String,',','.'),1) 'Surname'
FROM table WITH (NOLOCK)

With CROSS APPLY
select ParsedData.*
from MyTable mt
cross apply ( select str = mt.String + ',,' ) f1
cross apply ( select p1 = charindex( ',', str ) ) ap1
cross apply ( select p2 = charindex( ',', str, p1 + 1 ) ) ap2
cross apply ( select Nmame = substring( str, 1, p1-1 )
, Surname = substring( str, p1+1, p2-p1-1 )
) ParsedData

There are multiple ways to solve this and many different ways have been proposed already. Simplest would be to use LEFT / SUBSTRING and other string functions to achieve the desired result.
Sample Data
DECLARE #tbl1 TABLE (Value INT,String VARCHAR(MAX))
INSERT INTO #tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO #tbl1 VALUES(2,'John, Mathew');
Using String Functions like LEFT
SELECT
Value,
LEFT(String,CHARINDEX(',',String)-1) as Fname,
LTRIM(RIGHT(String,LEN(String) - CHARINDEX(',',String) )) AS Lname
FROM #tbl1
This approach fails if there are more 2 items in a String.
In such a scenario, we can use a splitter and then use PIVOT or convert the string into an XML and use .nodes to get string items. XML based solution have been detailed out by aads and bvr in their solution.
The answers for this question which use splitter, all use WHILE which is inefficient for splitting. Check this performance comparison. One of the best splitters around is DelimitedSplit8K, created by Jeff Moden. You can read more about it here
Splitter with PIVOT
DECLARE #tbl1 TABLE (Value INT,String VARCHAR(MAX))
INSERT INTO #tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO #tbl1 VALUES(2,'John, Mathew');
SELECT t3.Value,[1] as Fname,[2] as Lname
FROM #tbl1 as t1
CROSS APPLY [dbo].[DelimitedSplit8K](String,',') as t2
PIVOT(MAX(Item) FOR ItemNumber IN ([1],[2])) as t3
Output
Value Fname Lname
1 Cleo Smith
2 John Mathew
DelimitedSplit8K by Jeff Moden
CREATE FUNCTION [dbo].[DelimitedSplit8K]
/**********************************************************************************************************************
Purpose:
Split a given string at a given delimiter and return a list of the split elements (items).
Notes:
1. Leading a trailing delimiters are treated as if an empty string element were present.
2. Consecutive delimiters are treated as if an empty string element were present between them.
3. Except when spaces are used as a delimiter, all spaces present in each element are preserved.
Returns:
iTVF containing the following:
ItemNumber = Element position of Item as a BIGINT (not converted to INT to eliminate a CAST)
Item = Element value as a VARCHAR(8000)
Statistics on this function may be found at the following URL:
http://www.sqlservercentral.com/Forums/Topic1101315-203-4.aspx
CROSS APPLY Usage Examples and Tests:
--=====================================================================================================================
-- TEST 1:
-- This tests for various possible conditions in a string using a comma as the delimiter. The expected results are
-- laid out in the comments
--=====================================================================================================================
--===== Conditionally drop the test tables to make reruns easier for testing.
-- (this is NOT a part of the solution)
IF OBJECT_ID('tempdb..#JBMTest') IS NOT NULL DROP TABLE #JBMTest
;
--===== Create and populate a test table on the fly (this is NOT a part of the solution).
-- In the following comments, "b" is a blank and "E" is an element in the left to right order.
-- Double Quotes are used to encapsulate the output of "Item" so that you can see that all blanks
-- are preserved no matter where they may appear.
SELECT *
INTO #JBMTest
FROM ( --# & type of Return Row(s)
SELECT 0, NULL UNION ALL --1 NULL
SELECT 1, SPACE(0) UNION ALL --1 b (Empty String)
SELECT 2, SPACE(1) UNION ALL --1 b (1 space)
SELECT 3, SPACE(5) UNION ALL --1 b (5 spaces)
SELECT 4, ',' UNION ALL --2 b b (both are empty strings)
SELECT 5, '55555' UNION ALL --1 E
SELECT 6, ',55555' UNION ALL --2 b E
SELECT 7, ',55555,' UNION ALL --3 b E b
SELECT 8, '55555,' UNION ALL --2 b B
SELECT 9, '55555,1' UNION ALL --2 E E
SELECT 10, '1,55555' UNION ALL --2 E E
SELECT 11, '55555,4444,333,22,1' UNION ALL --5 E E E E E
SELECT 12, '55555,4444,,333,22,1' UNION ALL --6 E E b E E E
SELECT 13, ',55555,4444,,333,22,1,' UNION ALL --8 b E E b E E E b
SELECT 14, ',55555,4444,,,333,22,1,' UNION ALL --9 b E E b b E E E b
SELECT 15, ' 4444,55555 ' UNION ALL --2 E (w/Leading Space) E (w/Trailing Space)
SELECT 16, 'This,is,a,test.' --E E E E
) d (SomeID, SomeValue)
;
--===== Split the CSV column for the whole table using CROSS APPLY (this is the solution)
SELECT test.SomeID, test.SomeValue, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
FROM #JBMTest test
CROSS APPLY dbo.DelimitedSplit8K(test.SomeValue,',') split
;
--=====================================================================================================================
-- TEST 2:
-- This tests for various "alpha" splits and COLLATION using all ASCII characters from 0 to 255 as a delimiter against
-- a given string. Note that not all of the delimiters will be visible and some will show up as tiny squares because
-- they are "control" characters. More specifically, this test will show you what happens to various non-accented
-- letters for your given collation depending on the delimiter you chose.
--=====================================================================================================================
WITH
cteBuildAllCharacters (String,Delimiter) AS
(
SELECT TOP 256
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
CHAR(ROW_NUMBER() OVER (ORDER BY (SELECT NULL))-1)
FROM master.sys.all_columns
)
SELECT ASCII_Value = ASCII(c.Delimiter), c.Delimiter, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
FROM cteBuildAllCharacters c
CROSS APPLY dbo.DelimitedSplit8K(c.String,c.Delimiter) split
ORDER BY ASCII_Value, split.ItemNumber
;
-----------------------------------------------------------------------------------------------------------------------
Other Notes:
1. Optimized for VARCHAR(8000) or less. No testing or error reporting for truncation at 8000 characters is done.
2. Optimized for single character delimiter. Multi-character delimiters should be resolvedexternally from this
function.
3. Optimized for use with CROSS APPLY.
4. Does not "trim" elements just in case leading or trailing blanks are intended.
5. If you don't know how a Tally table can be used to replace loops, please see the following...
http://www.sqlservercentral.com/articles/T-SQL/62867/
6. Changing this function to use NVARCHAR(MAX) will cause it to run twice as slow. It's just the nature of
VARCHAR(MAX) whether it fits in-row or not.
7. Multi-machine testing for the method of using UNPIVOT instead of 10 SELECT/UNION ALLs shows that the UNPIVOT method
is quite machine dependent and can slow things down quite a bit.
-----------------------------------------------------------------------------------------------------------------------
Credits:
This code is the product of many people's efforts including but not limited to the following:
cteTally concept originally by Iztek Ben Gan and "decimalized" by Lynn Pettis (and others) for a bit of extra speed
and finally redacted by Jeff Moden for a different slant on readability and compactness. Hat's off to Paul White for
his simple explanations of CROSS APPLY and for his detailed testing efforts. Last but not least, thanks to
Ron "BitBucket" McCullough and Wayne Sheffield for their extreme performance testing across multiple machines and
versions of SQL Server. The latest improvement brought an additional 15-20% improvement over Rev 05. Special thanks
to "Nadrek" and "peter-757102" (aka Peter de Heer) for bringing such improvements to light. Nadrek's original
improvement brought about a 10% performance gain and Peter followed that up with the content of Rev 07.
I also thank whoever wrote the first article I ever saw on "numbers tables" which is located at the following URL
and to Adam Machanic for leading me to it many years ago.
http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html
-----------------------------------------------------------------------------------------------------------------------
Revision History:
Rev 00 - 20 Jan 2010 - Concept for inline cteTally: Lynn Pettis and others.
Redaction/Implementation: Jeff Moden
- Base 10 redaction and reduction for CTE. (Total rewrite)
Rev 01 - 13 Mar 2010 - Jeff Moden
- Removed one additional concatenation and one subtraction from the SUBSTRING in the SELECT List for that tiny
bit of extra speed.
Rev 02 - 14 Apr 2010 - Jeff Moden
- No code changes. Added CROSS APPLY usage example to the header, some additional credits, and extra
documentation.
Rev 03 - 18 Apr 2010 - Jeff Moden
- No code changes. Added notes 7, 8, and 9 about certain "optimizations" that don't actually work for this
type of function.
Rev 04 - 29 Jun 2010 - Jeff Moden
- Added WITH SCHEMABINDING thanks to a note by Paul White. This prevents an unnecessary "Table Spool" when the
function is used in an UPDATE statement even though the function makes no external references.
Rev 05 - 02 Apr 2011 - Jeff Moden
- Rewritten for extreme performance improvement especially for larger strings approaching the 8K boundary and
for strings that have wider elements. The redaction of this code involved removing ALL concatenation of
delimiters, optimization of the maximum "N" value by using TOP instead of including it in the WHERE clause,
and the reduction of all previous calculations (thanks to the switch to a "zero based" cteTally) to just one
instance of one add and one instance of a subtract. The length calculation for the final element (not
followed by a delimiter) in the string to be split has been greatly simplified by using the ISNULL/NULLIF
combination to determine when the CHARINDEX returned a 0 which indicates there are no more delimiters to be
had or to start with. Depending on the width of the elements, this code is between 4 and 8 times faster on a
single CPU box than the original code especially near the 8K boundary.
- Modified comments to include more sanity checks on the usage example, etc.
- Removed "other" notes 8 and 9 as they were no longer applicable.
Rev 06 - 12 Apr 2011 - Jeff Moden
- Based on a suggestion by Ron "Bitbucket" McCullough, additional test rows were added to the sample code and
the code was changed to encapsulate the output in pipes so that spaces and empty strings could be perceived
in the output. The first "Notes" section was added. Finally, an extra test was added to the comments above.
Rev 07 - 06 May 2011 - Peter de Heer, a further 15-20% performance enhancement has been discovered and incorporated
into this code which also eliminated the need for a "zero" position in the cteTally table.
**********************************************************************************************************************/
--===== Define I/O parameters
(#pString VARCHAR(8000), #pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
-- enough to cover NVARCHAR(4000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(#pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(#pString,t.N,1) = #pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(#pDelimiter,#pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(#pString, l.N1, l.L1)
FROM cteLen l
;
GO

With SQL Server 2016 we can use string_split to accomplish this:
create table commasep (
id int identity(1,1)
,string nvarchar(100) )
insert into commasep (string) values ('John, Adam'), ('test1,test2,test3')
select id, [value] as String from commasep
cross apply string_split(string,',')

CREATE FUNCTION [dbo].[fn_split_string_to_column] (
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #out_put TABLE (
[column_id] INT IDENTITY(1, 1) NOT NULL,
[value] NVARCHAR(MAX)
)
AS
BEGIN
DECLARE #value NVARCHAR(MAX),
#pos INT = 0,
#len INT = 0
SET #string = CASE
WHEN RIGHT(#string, 1) != #delimiter
THEN #string + #delimiter
ELSE #string
END
WHILE CHARINDEX(#delimiter, #string, #pos + 1) > 0
BEGIN
SET #len = CHARINDEX(#delimiter, #string, #pos + 1) - #pos
SET #value = SUBSTRING(#string, #pos, #len)
INSERT INTO #out_put ([value])
SELECT LTRIM(RTRIM(#value)) AS [column]
SET #pos = CHARINDEX(#delimiter, #string, #pos + #len) + 1
END
RETURN
END

SELECT id,
Substring(NAME, 0, Charindex(',', NAME)) AS firstname,
Substring(NAME, Charindex(',', NAME), Len(NAME) + 1) AS lastname
FROM spilt

Try this (change instances of ' ' to ',' or whatever delimiter you want to use)
CREATE FUNCTION dbo.Wordparser
(
#multiwordstring VARCHAR(255),
#wordnumber NUMERIC
)
returns VARCHAR(255)
AS
BEGIN
DECLARE #remainingstring VARCHAR(255)
SET #remainingstring=#multiwordstring
DECLARE #numberofwords NUMERIC
SET #numberofwords=(LEN(#remainingstring) - LEN(REPLACE(#remainingstring, ' ', '')) + 1)
DECLARE #word VARCHAR(50)
DECLARE #parsedwords TABLE
(
line NUMERIC IDENTITY(1, 1),
word VARCHAR(255)
)
WHILE #numberofwords > 1
BEGIN
SET #word=LEFT(#remainingstring, CHARINDEX(' ', #remainingstring) - 1)
INSERT INTO #parsedwords(word)
SELECT #word
SET #remainingstring= REPLACE(#remainingstring, Concat(#word, ' '), '')
SET #numberofwords=(LEN(#remainingstring) - LEN(REPLACE(#remainingstring, ' ', '')) + 1)
IF #numberofwords = 1
BREAK
ELSE
CONTINUE
END
IF #numberofwords = 1
SELECT #word = #remainingstring
INSERT INTO #parsedwords(word)
SELECT #word
RETURN
(SELECT word
FROM #parsedwords
WHERE line = #wordnumber)
END
Example usage:
SELECT dbo.Wordparser(COLUMN, 1),
dbo.Wordparser(COLUMN, 2),
dbo.Wordparser(COLUMN, 3)
FROM TABLE

I think PARSENAME is the neat function to use for this example, as described in this article: http://www.sqlshack.com/parsing-and-rotating-delimited-data-in-sql-server-2012/
The PARSENAME function is logically designed to parse four-part object names. The nice thing about PARSENAME is that it’s not limited to parsing just SQL Server four-part object names – it will parse any function or string data that is delimited by dots.
The first parameter is the object to parse, and the second is the integer value of the object piece to return. The article is discussing parsing and rotating delimited data - company phone numbers, but it can be used to parse name/surname data also.
Example:
USE COMPANY;
SELECT PARSENAME('Whatever.you.want.parsed',3) AS 'ReturnValue';
The article also describes using a Common Table Expression (CTE) called ‘replaceChars’, to run PARSENAME against the delimiter-replaced values. A CTE is useful for returning a temporary view or result set.
After that, the UNPIVOT function has been used to convert some columns into rows; SUBSTRING and CHARINDEX functions have been used for cleaning up the inconsistencies in the data, and the LAG function (new for SQL Server 2012) has been used in the end, as it allows referencing of previous records.

We can create a function as this
CREATE Function [dbo].[fn_CSVToTable]
(
#CSVList Varchar(max)
)
RETURNS #Table TABLE (ColumnData VARCHAR(100))
AS
BEGIN
IF RIGHT(#CSVList, 1) <> ','
SELECT #CSVList = #CSVList + ','
DECLARE #Pos BIGINT,
#OldPos BIGINT
SELECT #Pos = 1,
#OldPos = 1
WHILE #Pos < LEN(#CSVList)
BEGIN
SELECT #Pos = CHARINDEX(',', #CSVList, #OldPos)
INSERT INTO #Table
SELECT LTRIM(RTRIM(SUBSTRING(#CSVList, #OldPos, #Pos - #OldPos))) Col001
SELECT #OldPos = #Pos + 1
END
RETURN
END
We can then seperate the CSV values into our respective columns using a SELECT statement

You can use a table-valued function STRING_SPLIT, which is available only under compatibility level 130. If your database compatibility level is lower than 130, SQL Server will not be able to find and execute the STRING_SPLIT function. You can change a compatibility level of the database using the following command:
ALTER DATABASE DatabaseName SET COMPATIBILITY_LEVEL = 130
Syntax
SELECT * FROM STRING_SPLIT ( string, separator )
see documentation here

I think following function will work for you:
You have to create a function in SQL first. Like this
CREATE FUNCTION [dbo].[fn_split](
#str VARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #returnTable TABLE (idx INT PRIMARY KEY IDENTITY, item VARCHAR(8000))
AS
BEGIN
DECLARE #pos INT
SELECT #str = #str + #delimiter
WHILE LEN(#str) > 0
BEGIN
SELECT #pos = CHARINDEX(#delimiter,#str)
IF #pos = 1
INSERT #returnTable (item)
VALUES (NULL)
ELSE
INSERT #returnTable (item)
VALUES (SUBSTRING(#str, 1, #pos-1))
SELECT #str = SUBSTRING(#str, #pos+1, LEN(#str)-#pos)
END
RETURN
END
You can call this function, like this:
select * from fn_split('1,24,5',',')
Implementation:
Declare #test TABLE (
ID VARCHAR(200),
Data VARCHAR(200)
)
insert into #test
(ID, Data)
Values
('1','Cleo,Smith')
insert into #test
(ID, Data)
Values
('2','Paul,Grim')
select ID,
(select item from fn_split(Data,',') where idx in (1)) as Name ,
(select item from fn_split(Data,',') where idx in (2)) as Surname
from #test
Result will like this:

Use Parsename() function
with cte as(
select 'Aria,Karimi' as FullName
Union
select 'Joe,Karimi' as FullName
Union
select 'Bab,Karimi' as FullName
)
SELECT PARSENAME(REPLACE(FullName,',','.'),2) as Name,
PARSENAME(REPLACE(FullName,',','.'),1) as Family
FROM cte
Result
Name Family
----- ------
Aria Karimi
Bab Karimi
Joe Karimi

Try this:
declare #csv varchar(100) ='aaa,bb,csda,daass';
set #csv = #csv+',';
with cte as
(
select SUBSTRING(#csv,1,charindex(',',#csv,1)-1) as val, SUBSTRING(#csv,charindex(',',#csv,1)+1,len(#csv)) as rem
UNION ALL
select SUBSTRING(a.rem,1,charindex(',',a.rem,1)-1)as val, SUBSTRING(a.rem,charindex(',',a.rem,1)+1,len(A.rem))
from cte a where LEN(a.rem)>=1
) select val from cte

This function is most fast:
CREATE FUNCTION dbo.F_ExtractSubString
(
#String VARCHAR(MAX),
#NroSubString INT,
#Separator VARCHAR(5)
)
RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE #St INT = 0, #End INT = 0, #Ret VARCHAR(MAX)
SET #String = #String + #Separator
WHILE CHARINDEX(#Separator, #String, #End + 1) > 0 AND #NroSubString > 0
BEGIN
SET #St = #End + 1
SET #End = CHARINDEX(#Separator, #String, #End + 1)
SET #NroSubString = #NroSubString - 1
END
IF #NroSubString > 0
SET #Ret = ''
ELSE
SET #Ret = SUBSTRING(#String, #St, #End - #St)
RETURN #Ret
END
GO
Example usage:
SELECT dbo.F_ExtractSubString(COLUMN, 1, ', '),
dbo.F_ExtractSubString(COLUMN, 2, ', '),
dbo.F_ExtractSubString(COLUMN, 3, ', ')
FROM TABLE

I encountered a similar problem but a complex one and since this is the first thread i found regarding that issue i decided to post my finding. i know it is complex solution to a simple problem but i hope that i could help other people who go to this thread looking for a more complex solution. i had to split a string containing 5 numbers (column name: levelsFeed) and to show each number in a separate column.
for example: 8,1,2,2,2
should be shown as :
1 2 3 4 5
-------------
8 1 2 2 2
Solution 1: using XML functions:
this solution for the slowest solution by far
SELECT Distinct FeedbackID,
, S.a.value('(/H/r)[1]', 'INT') AS level1
, S.a.value('(/H/r)[2]', 'INT') AS level2
, S.a.value('(/H/r)[3]', 'INT') AS level3
, S.a.value('(/H/r)[4]', 'INT') AS level4
, S.a.value('(/H/r)[5]', 'INT') AS level5
FROM (
SELECT *,CAST (N'<H><r>' + REPLACE(levelsFeed, ',', '</r><r>') + '</r> </H>' AS XML) AS [vals]
FROM Feedbacks
) as d
CROSS APPLY d.[vals].nodes('/H/r') S(a)
Solution 2: using Split function and pivot. (the split function split a string to rows with the column name Data)
SELECT FeedbackID, [1],[2],[3],[4],[5]
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY feedbackID ORDER BY (SELECT null)) as rn
FROM (
SELECT FeedbackID, levelsFeed
FROM Feedbacks
) as a
CROSS APPLY dbo.Split(levelsFeed, ',')
) as SourceTable
PIVOT
(
MAX(data)
FOR rn IN ([1],[2],[3],[4],[5])
)as pivotTable
Solution 3: using string manipulations functions - fastest by small margin over solution 2
SELECT FeedbackID,
SUBSTRING(levelsFeed,0,CHARINDEX(',',levelsFeed)) AS level1,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),4) AS level2,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),3) AS level3,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),2) AS level4,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),1) AS level5
FROM Feedbacks
since the levelsFeed contains 5 string values i needed to use the substring function for the first string.
i hope that my solution will help other that got to this thread looking for a more complex split to columns methods

Using instring function :)
select Value,
substring(String,1,instr(String," ") -1) Fname,
substring(String,instr(String,",") +1) Sname
from tablename;
Used two functions,
1. substring(string, position, length) ==> returns string from positon to length
2. instr(string,pattern) ==> returns position of pattern.
If we don’t provide length argument in substring it returns until end of string

This worked for me
CREATE FUNCTION [dbo].[SplitString](
#delimited NVARCHAR(MAX),
#delimiter NVARCHAR(100)
) RETURNS #t TABLE ( val NVARCHAR(MAX))
AS
BEGIN
DECLARE #xml XML
SET #xml = N'<t>' + REPLACE(#delimited,#delimiter,'</t><t>') + '</t>'
INSERT INTO #t(val)
SELECT r.value('.','varchar(MAX)') as item
FROM #xml.nodes('/t') as records(r)
RETURN
END

mytable:
Value ColOne
--------------------
1 Cleo, Smith
The following should work if there aren't too many columns
ALTER TABLE mytable ADD ColTwo nvarchar(256);
UPDATE mytable SET ColTwo = LEFT(ColOne, Charindex(',', ColOne) - 1);
--'Cleo' = LEFT('Cleo, Smith', Charindex(',', 'Cleo, Smith') - 1)
UPDATE mytable SET ColTwo = REPLACE(ColOne, ColTwo + ',', '');
--' Smith' = REPLACE('Cleo, Smith', 'Cleo' + ',')
UPDATE mytable SET ColOne = REPLACE(ColOne, ',' + ColTwo, ''), ColTwo = LTRIM(ColTwo);
--'Cleo' = REPLACE('Cleo, Smith', ',' + ' Smith', '')
Result:
Value ColOne ColTwo
--------------------
1 Cleo Smith

DECLARE #INPUT VARCHAR (MAX)='N,A,R,E,N,D,R,A'
DECLARE #ELIMINATE_CHAR CHAR (1)=','
DECLARE #L_START INT=1
DECLARE #L_END INT=(SELECT LEN (#INPUT))
DECLARE #OUTPUT CHAR (1)
WHILE #L_START <=#L_END
BEGIN
SET #OUTPUT=(SUBSTRING (#INPUT,#L_START,1))
IF #OUTPUT!=#ELIMINATE_CHAR
BEGIN
PRINT #OUTPUT
END
SET #L_START=#L_START+1
END

You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project).
This is the code part from this page:
CREATE FUNCTION [fn_ParseText2Table]
(#p_SourceText VARCHAR(MAX)
,#p_Delimeter VARCHAR(100)=',' --default to comma delimited.
)
RETURNS #retTable
TABLE([Position] INT IDENTITY(1,1)
,[Int_Value] INT
,[Num_Value] NUMERIC(18,3)
,[Txt_Value] VARCHAR(MAX)
,[Date_value] DATETIME
)
AS
/*
********************************************************************************
Purpose: Parse values from a delimited string
& return the result as an indexed table
Copyright 1996, 1997, 2000, 2003 Clayton Groom (Clayton_Groom#hotmail.com)
Posted to the public domain Aug, 2004
2003-06-17 Rewritten as SQL 2000 function.
Reworked to allow for delimiters > 1 character in length
and to convert Text values to numbers
2016-04-05 Added logic for date values based on "new" ISDATE() function, Updated to use XML approach, which is more efficient.
********************************************************************************
*/
BEGIN
DECLARE #w_xml xml;
SET #w_xml = N'<root><i>' + replace(#p_SourceText, #p_Delimeter,'</i><i>') + '</i></root>';
INSERT INTO #retTable
([Int_Value]
, [Num_Value]
, [Txt_Value]
, [Date_value]
)
SELECT CASE
WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST(CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC) AS INT)
END AS [Int_Value]
, CASE
WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC(18, 3))
END AS [Num_Value]
, [i].value('.', 'VARCHAR(MAX)') AS [txt_Value]
, CASE
WHEN ISDATE([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST([i].value('.', 'VARCHAR(MAX)') AS DATETIME)
END AS [Num_Value]
FROM #w_xml.nodes('//root/i') AS [Items]([i]);
RETURN;
END;
GO

ALTER function get_occurance_index(#delimiter varchar(1),#occurence int,#String varchar(100))
returns int
AS Begin
--Declare #delimiter varchar(1)=',',#occurence int=2,#String varchar(100)='a,b,c'
Declare #result int
;with T as (
select 1 Rno,0 as row, charindex(#delimiter, #String) pos,#String st
union all
select Rno+1,pos + 1, charindex(#delimiter, #String, pos + 1), #String
from T
where pos > 0
)
select #result=pos
from T
where pos > 0 and rno = #occurence
return isnull(#result,0)
ENd
declare #data as table (data varchar(100))
insert into #data values('1,2,3')
insert into #data values('aaa,bbbbb,cccc')
select top 3 Substring (data,0,dbo.get_occurance_index( ',',1,data)) ,--First Record always starts with 0
Substring (data,dbo.get_occurance_index( ',',1,data)+1,dbo.get_occurance_index( ',',2,data)-dbo.get_occurance_index( ',',1,data)-1) ,
Substring (data,dbo.get_occurance_index( ',',2,data)+1,len(data)) , -- Last record cant be more than len of actual data
data
From #data

I found that using PARSENAME as above caused any name with a period to get nulled.
So if there was an initial or a title in the name followed by a dot they return NULL.
I found this worked for me:
SELECT
REPLACE(SUBSTRING(FullName, 1,CHARINDEX(',', FullName)), ',','') as Name,
REPLACE(SUBSTRING(FullName, CHARINDEX(',', FullName), LEN(FullName)), ',', '') as Surname
FROM Table1

it is so easy, you can take it by below query:
DECLARE #str NVARCHAR(MAX)='ControlID_05436b78-04ba-9667-fa01-9ff8c1b7c235,3'
SELECT LEFT(#str, CHARINDEX(',',#str)-1),RIGHT(#str,LEN(#str)-(CHARINDEX(',',#str)))

select distinct modelFileId,F4.*
from contract
cross apply (select XmlList=convert(xml, '<x>'+replace(modelFileId,';','</x><x>')+'</x>').query('.')) F2
cross apply (select mfid1=XmlNode.value('/x[1]','varchar(512)')
,mfid2=XmlNode.value('/x[2]','varchar(512)')
,mfid3=XmlNode.value('/x[3]','varchar(512)')
,mfid4=XmlNode.value('/x[4]','varchar(512)') from XmlList.nodes('x') F3(XmlNode)) F4
where modelFileId like '%;%'
order by modelFileId

Select distinct PROJ_UID,PROJ_NAME,RES_UID from E2E_ProjectWiseTimesheetActuals
where CHARINDEX(','+cast(PROJ_UID as varchar(8000))+',', #params) > 0 and CHARINDEX(','+cast(RES_UID as varchar(8000))+',', #res) > 0

I re-wrote an answer above and made it better:
CREATE FUNCTION [dbo].[CSVParser]
(
#s VARCHAR(255),
#idx NUMERIC
)
RETURNS VARCHAR(12)
BEGIN
DECLARE #comma int
SET #comma = CHARINDEX(',', #s)
WHILE 1=1
BEGIN
IF #comma=0
IF #idx=1
RETURN #s
ELSE
RETURN ''
IF #idx=1
BEGIN
DECLARE #word VARCHAR(12)
SET #word=LEFT(#s, #comma - 1)
RETURN #word
END
SET #s = RIGHT(#s,LEN(#s)-#comma)
SET #comma = CHARINDEX(',', #s)
SET #idx = #idx - 1
END
RETURN 'not used'
END
Example usage:
SELECT dbo.CSVParser(COLUMN, 1),
dbo.CSVParser(COLUMN, 2),
dbo.CSVParser(COLUMN, 3)
FROM TABLE

question is simple, but problem is hot :)
So I create some wrapper for string_split() which pivot result in more generic way. It's table function which returns values (nn, value1, value2, ... , value50) - enough for most CSV lines. If there are more values, they will wrap to next line - nn indicate line number. Set third parameter #columnCnt = [yourNumber] to wrap at specific position:
alter FUNCTION fn_Split50
(
#str varchar(max),
#delim char(1),
#columnCnt int = 50
)
RETURNS TABLE
AS
RETURN
(
SELECT *
FROM (SELECT
nn = (nn - 1) / #columnCnt + 1,
nnn = 'value' + cast(((nn - 1) % #columnCnt) + 1 as varchar(10)),
value
FROM (SELECT
nn = ROW_NUMBER() over (order by (select null)),
value
FROM string_split(#str, #delim) aa
) aa
where nn > 0
) bb
PIVOT
(
max(value)
FOR nnn IN (
value1, value2, value3, value4, value5, value6, value7, value8, value9, value10,
value11, value12, value13, value14, value15, value16, value17, value18, value19, value20,
value21, value22, value23, value24, value25, value26, value27, value28, value29, value30,
value31, value32, value33, value34, value35, value36, value37, value38, value39, value40,
value41, value42, value43, value44, value45, value46, value47, value48, value49, value50
)
) AS PivotTable
)
Example of using:
select * from dbo.fn_split50('zz1,aa2,ss3,dd4,ff5', ',', DEFAULT)
select * from dbo.fn_split50('zz1,aa2,ss3,dd4,ff5,gg6,hh7,jj8,ww9,qq10', ',', 3)
select * from dbo.fn_split50('zz1,11,aa2,22,ss3,33,dd4,44,ff5,55,gg6,66,hh7,77,jj8,88,ww9,99,qq10,1010', ',',2)
Hope, it will helps :)

Related

Parse String With Hyphens As Separators in SQL [duplicate]

I have a table like this
Value String
-------------------
1 Cleo, Smith
I want to separate the comma delimited string into two columns
Value Name Surname
-------------------
1 Cleo Smith
I need only two fixed extra columns
Your purpose can be solved using following query -
Select Value , Substring(FullName, 1,Charindex(',', FullName)-1) as Name,
Substring(FullName, Charindex(',', FullName)+1, LEN(FullName)) as Surname
from Table1
There is no readymade Split function in sql server, so we need to create user defined function.
CREATE FUNCTION Split (
#InputString VARCHAR(8000),
#Delimiter VARCHAR(50)
)
RETURNS #Items TABLE (
Item VARCHAR(8000)
)
AS
BEGIN
IF #Delimiter = ' '
BEGIN
SET #Delimiter = ','
SET #InputString = REPLACE(#InputString, ' ', #Delimiter)
END
IF (#Delimiter IS NULL OR #Delimiter = '')
SET #Delimiter = ','
--INSERT INTO #Items VALUES (#Delimiter) -- Diagnostic
--INSERT INTO #Items VALUES (#InputString) -- Diagnostic
DECLARE #Item VARCHAR(8000)
DECLARE #ItemList VARCHAR(8000)
DECLARE #DelimIndex INT
SET #ItemList = #InputString
SET #DelimIndex = CHARINDEX(#Delimiter, #ItemList, 0)
WHILE (#DelimIndex != 0)
BEGIN
SET #Item = SUBSTRING(#ItemList, 0, #DelimIndex)
INSERT INTO #Items VALUES (#Item)
-- Set #ItemList = #ItemList minus one less item
SET #ItemList = SUBSTRING(#ItemList, #DelimIndex+1, LEN(#ItemList)-#DelimIndex)
SET #DelimIndex = CHARINDEX(#Delimiter, #ItemList, 0)
END -- End WHILE
IF #Item IS NOT NULL -- At least one delimiter was encountered in #InputString
BEGIN
SET #Item = #ItemList
INSERT INTO #Items VALUES (#Item)
END
-- No delimiters were encountered in #InputString, so just return #InputString
ELSE INSERT INTO #Items VALUES (#InputString)
RETURN
END -- End Function
GO
---- Set Permissions
--GRANT SELECT ON Split TO UserRole1
--GRANT SELECT ON Split TO UserRole2
--GO
;WITH Split_Names (Value,Name, xmlname)
AS
(
SELECT Value,
Name,
CONVERT(XML,'<Names><name>'
+ REPLACE(Name,',', '</name><name>') + '</name></Names>') AS xmlname
FROM tblnames
)
SELECT Value,
xmlname.value('/Names[1]/name[1]','varchar(100)') AS Name,
xmlname.value('/Names[1]/name[2]','varchar(100)') AS Surname
FROM Split_Names
and also check the link below for reference
http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html
xml based answer is simple and clean
refer this
DECLARE #S varchar(max),
#Split char(1),
#X xml
SELECT #S = 'ab,cd,ef,gh,ij',
#Split = ','
SELECT #X = CONVERT(xml,' <root> <myvalue>' +
REPLACE(#S,#Split,'</myvalue> <myvalue>') + '</myvalue> </root> ')
SELECT T.c.value('.','varchar(20)'), --retrieve ALL values at once
T.c.value('(/root/myvalue)[1]','VARCHAR(20)') , --retrieve index 1 only, which is the 'ab'
T.c.value('(/root/myvalue)[2]','VARCHAR(20)')
FROM #X.nodes('/root/myvalue') T(c)
I think this is cool
SELECT value,
PARSENAME(REPLACE(String,',','.'),2) 'Name' ,
PARSENAME(REPLACE(String,',','.'),1) 'Surname'
FROM table WITH (NOLOCK)
With CROSS APPLY
select ParsedData.*
from MyTable mt
cross apply ( select str = mt.String + ',,' ) f1
cross apply ( select p1 = charindex( ',', str ) ) ap1
cross apply ( select p2 = charindex( ',', str, p1 + 1 ) ) ap2
cross apply ( select Nmame = substring( str, 1, p1-1 )
, Surname = substring( str, p1+1, p2-p1-1 )
) ParsedData
There are multiple ways to solve this and many different ways have been proposed already. Simplest would be to use LEFT / SUBSTRING and other string functions to achieve the desired result.
Sample Data
DECLARE #tbl1 TABLE (Value INT,String VARCHAR(MAX))
INSERT INTO #tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO #tbl1 VALUES(2,'John, Mathew');
Using String Functions like LEFT
SELECT
Value,
LEFT(String,CHARINDEX(',',String)-1) as Fname,
LTRIM(RIGHT(String,LEN(String) - CHARINDEX(',',String) )) AS Lname
FROM #tbl1
This approach fails if there are more 2 items in a String.
In such a scenario, we can use a splitter and then use PIVOT or convert the string into an XML and use .nodes to get string items. XML based solution have been detailed out by aads and bvr in their solution.
The answers for this question which use splitter, all use WHILE which is inefficient for splitting. Check this performance comparison. One of the best splitters around is DelimitedSplit8K, created by Jeff Moden. You can read more about it here
Splitter with PIVOT
DECLARE #tbl1 TABLE (Value INT,String VARCHAR(MAX))
INSERT INTO #tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO #tbl1 VALUES(2,'John, Mathew');
SELECT t3.Value,[1] as Fname,[2] as Lname
FROM #tbl1 as t1
CROSS APPLY [dbo].[DelimitedSplit8K](String,',') as t2
PIVOT(MAX(Item) FOR ItemNumber IN ([1],[2])) as t3
Output
Value Fname Lname
1 Cleo Smith
2 John Mathew
DelimitedSplit8K by Jeff Moden
CREATE FUNCTION [dbo].[DelimitedSplit8K]
/**********************************************************************************************************************
Purpose:
Split a given string at a given delimiter and return a list of the split elements (items).
Notes:
1. Leading a trailing delimiters are treated as if an empty string element were present.
2. Consecutive delimiters are treated as if an empty string element were present between them.
3. Except when spaces are used as a delimiter, all spaces present in each element are preserved.
Returns:
iTVF containing the following:
ItemNumber = Element position of Item as a BIGINT (not converted to INT to eliminate a CAST)
Item = Element value as a VARCHAR(8000)
Statistics on this function may be found at the following URL:
http://www.sqlservercentral.com/Forums/Topic1101315-203-4.aspx
CROSS APPLY Usage Examples and Tests:
--=====================================================================================================================
-- TEST 1:
-- This tests for various possible conditions in a string using a comma as the delimiter. The expected results are
-- laid out in the comments
--=====================================================================================================================
--===== Conditionally drop the test tables to make reruns easier for testing.
-- (this is NOT a part of the solution)
IF OBJECT_ID('tempdb..#JBMTest') IS NOT NULL DROP TABLE #JBMTest
;
--===== Create and populate a test table on the fly (this is NOT a part of the solution).
-- In the following comments, "b" is a blank and "E" is an element in the left to right order.
-- Double Quotes are used to encapsulate the output of "Item" so that you can see that all blanks
-- are preserved no matter where they may appear.
SELECT *
INTO #JBMTest
FROM ( --# & type of Return Row(s)
SELECT 0, NULL UNION ALL --1 NULL
SELECT 1, SPACE(0) UNION ALL --1 b (Empty String)
SELECT 2, SPACE(1) UNION ALL --1 b (1 space)
SELECT 3, SPACE(5) UNION ALL --1 b (5 spaces)
SELECT 4, ',' UNION ALL --2 b b (both are empty strings)
SELECT 5, '55555' UNION ALL --1 E
SELECT 6, ',55555' UNION ALL --2 b E
SELECT 7, ',55555,' UNION ALL --3 b E b
SELECT 8, '55555,' UNION ALL --2 b B
SELECT 9, '55555,1' UNION ALL --2 E E
SELECT 10, '1,55555' UNION ALL --2 E E
SELECT 11, '55555,4444,333,22,1' UNION ALL --5 E E E E E
SELECT 12, '55555,4444,,333,22,1' UNION ALL --6 E E b E E E
SELECT 13, ',55555,4444,,333,22,1,' UNION ALL --8 b E E b E E E b
SELECT 14, ',55555,4444,,,333,22,1,' UNION ALL --9 b E E b b E E E b
SELECT 15, ' 4444,55555 ' UNION ALL --2 E (w/Leading Space) E (w/Trailing Space)
SELECT 16, 'This,is,a,test.' --E E E E
) d (SomeID, SomeValue)
;
--===== Split the CSV column for the whole table using CROSS APPLY (this is the solution)
SELECT test.SomeID, test.SomeValue, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
FROM #JBMTest test
CROSS APPLY dbo.DelimitedSplit8K(test.SomeValue,',') split
;
--=====================================================================================================================
-- TEST 2:
-- This tests for various "alpha" splits and COLLATION using all ASCII characters from 0 to 255 as a delimiter against
-- a given string. Note that not all of the delimiters will be visible and some will show up as tiny squares because
-- they are "control" characters. More specifically, this test will show you what happens to various non-accented
-- letters for your given collation depending on the delimiter you chose.
--=====================================================================================================================
WITH
cteBuildAllCharacters (String,Delimiter) AS
(
SELECT TOP 256
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
CHAR(ROW_NUMBER() OVER (ORDER BY (SELECT NULL))-1)
FROM master.sys.all_columns
)
SELECT ASCII_Value = ASCII(c.Delimiter), c.Delimiter, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
FROM cteBuildAllCharacters c
CROSS APPLY dbo.DelimitedSplit8K(c.String,c.Delimiter) split
ORDER BY ASCII_Value, split.ItemNumber
;
-----------------------------------------------------------------------------------------------------------------------
Other Notes:
1. Optimized for VARCHAR(8000) or less. No testing or error reporting for truncation at 8000 characters is done.
2. Optimized for single character delimiter. Multi-character delimiters should be resolvedexternally from this
function.
3. Optimized for use with CROSS APPLY.
4. Does not "trim" elements just in case leading or trailing blanks are intended.
5. If you don't know how a Tally table can be used to replace loops, please see the following...
http://www.sqlservercentral.com/articles/T-SQL/62867/
6. Changing this function to use NVARCHAR(MAX) will cause it to run twice as slow. It's just the nature of
VARCHAR(MAX) whether it fits in-row or not.
7. Multi-machine testing for the method of using UNPIVOT instead of 10 SELECT/UNION ALLs shows that the UNPIVOT method
is quite machine dependent and can slow things down quite a bit.
-----------------------------------------------------------------------------------------------------------------------
Credits:
This code is the product of many people's efforts including but not limited to the following:
cteTally concept originally by Iztek Ben Gan and "decimalized" by Lynn Pettis (and others) for a bit of extra speed
and finally redacted by Jeff Moden for a different slant on readability and compactness. Hat's off to Paul White for
his simple explanations of CROSS APPLY and for his detailed testing efforts. Last but not least, thanks to
Ron "BitBucket" McCullough and Wayne Sheffield for their extreme performance testing across multiple machines and
versions of SQL Server. The latest improvement brought an additional 15-20% improvement over Rev 05. Special thanks
to "Nadrek" and "peter-757102" (aka Peter de Heer) for bringing such improvements to light. Nadrek's original
improvement brought about a 10% performance gain and Peter followed that up with the content of Rev 07.
I also thank whoever wrote the first article I ever saw on "numbers tables" which is located at the following URL
and to Adam Machanic for leading me to it many years ago.
http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html
-----------------------------------------------------------------------------------------------------------------------
Revision History:
Rev 00 - 20 Jan 2010 - Concept for inline cteTally: Lynn Pettis and others.
Redaction/Implementation: Jeff Moden
- Base 10 redaction and reduction for CTE. (Total rewrite)
Rev 01 - 13 Mar 2010 - Jeff Moden
- Removed one additional concatenation and one subtraction from the SUBSTRING in the SELECT List for that tiny
bit of extra speed.
Rev 02 - 14 Apr 2010 - Jeff Moden
- No code changes. Added CROSS APPLY usage example to the header, some additional credits, and extra
documentation.
Rev 03 - 18 Apr 2010 - Jeff Moden
- No code changes. Added notes 7, 8, and 9 about certain "optimizations" that don't actually work for this
type of function.
Rev 04 - 29 Jun 2010 - Jeff Moden
- Added WITH SCHEMABINDING thanks to a note by Paul White. This prevents an unnecessary "Table Spool" when the
function is used in an UPDATE statement even though the function makes no external references.
Rev 05 - 02 Apr 2011 - Jeff Moden
- Rewritten for extreme performance improvement especially for larger strings approaching the 8K boundary and
for strings that have wider elements. The redaction of this code involved removing ALL concatenation of
delimiters, optimization of the maximum "N" value by using TOP instead of including it in the WHERE clause,
and the reduction of all previous calculations (thanks to the switch to a "zero based" cteTally) to just one
instance of one add and one instance of a subtract. The length calculation for the final element (not
followed by a delimiter) in the string to be split has been greatly simplified by using the ISNULL/NULLIF
combination to determine when the CHARINDEX returned a 0 which indicates there are no more delimiters to be
had or to start with. Depending on the width of the elements, this code is between 4 and 8 times faster on a
single CPU box than the original code especially near the 8K boundary.
- Modified comments to include more sanity checks on the usage example, etc.
- Removed "other" notes 8 and 9 as they were no longer applicable.
Rev 06 - 12 Apr 2011 - Jeff Moden
- Based on a suggestion by Ron "Bitbucket" McCullough, additional test rows were added to the sample code and
the code was changed to encapsulate the output in pipes so that spaces and empty strings could be perceived
in the output. The first "Notes" section was added. Finally, an extra test was added to the comments above.
Rev 07 - 06 May 2011 - Peter de Heer, a further 15-20% performance enhancement has been discovered and incorporated
into this code which also eliminated the need for a "zero" position in the cteTally table.
**********************************************************************************************************************/
--===== Define I/O parameters
(#pString VARCHAR(8000), #pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
-- enough to cover NVARCHAR(4000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(#pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(#pString,t.N,1) = #pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(#pDelimiter,#pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(#pString, l.N1, l.L1)
FROM cteLen l
;
GO
With SQL Server 2016 we can use string_split to accomplish this:
create table commasep (
id int identity(1,1)
,string nvarchar(100) )
insert into commasep (string) values ('John, Adam'), ('test1,test2,test3')
select id, [value] as String from commasep
cross apply string_split(string,',')
CREATE FUNCTION [dbo].[fn_split_string_to_column] (
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #out_put TABLE (
[column_id] INT IDENTITY(1, 1) NOT NULL,
[value] NVARCHAR(MAX)
)
AS
BEGIN
DECLARE #value NVARCHAR(MAX),
#pos INT = 0,
#len INT = 0
SET #string = CASE
WHEN RIGHT(#string, 1) != #delimiter
THEN #string + #delimiter
ELSE #string
END
WHILE CHARINDEX(#delimiter, #string, #pos + 1) > 0
BEGIN
SET #len = CHARINDEX(#delimiter, #string, #pos + 1) - #pos
SET #value = SUBSTRING(#string, #pos, #len)
INSERT INTO #out_put ([value])
SELECT LTRIM(RTRIM(#value)) AS [column]
SET #pos = CHARINDEX(#delimiter, #string, #pos + #len) + 1
END
RETURN
END
SELECT id,
Substring(NAME, 0, Charindex(',', NAME)) AS firstname,
Substring(NAME, Charindex(',', NAME), Len(NAME) + 1) AS lastname
FROM spilt
Try this (change instances of ' ' to ',' or whatever delimiter you want to use)
CREATE FUNCTION dbo.Wordparser
(
#multiwordstring VARCHAR(255),
#wordnumber NUMERIC
)
returns VARCHAR(255)
AS
BEGIN
DECLARE #remainingstring VARCHAR(255)
SET #remainingstring=#multiwordstring
DECLARE #numberofwords NUMERIC
SET #numberofwords=(LEN(#remainingstring) - LEN(REPLACE(#remainingstring, ' ', '')) + 1)
DECLARE #word VARCHAR(50)
DECLARE #parsedwords TABLE
(
line NUMERIC IDENTITY(1, 1),
word VARCHAR(255)
)
WHILE #numberofwords > 1
BEGIN
SET #word=LEFT(#remainingstring, CHARINDEX(' ', #remainingstring) - 1)
INSERT INTO #parsedwords(word)
SELECT #word
SET #remainingstring= REPLACE(#remainingstring, Concat(#word, ' '), '')
SET #numberofwords=(LEN(#remainingstring) - LEN(REPLACE(#remainingstring, ' ', '')) + 1)
IF #numberofwords = 1
BREAK
ELSE
CONTINUE
END
IF #numberofwords = 1
SELECT #word = #remainingstring
INSERT INTO #parsedwords(word)
SELECT #word
RETURN
(SELECT word
FROM #parsedwords
WHERE line = #wordnumber)
END
Example usage:
SELECT dbo.Wordparser(COLUMN, 1),
dbo.Wordparser(COLUMN, 2),
dbo.Wordparser(COLUMN, 3)
FROM TABLE
I think PARSENAME is the neat function to use for this example, as described in this article: http://www.sqlshack.com/parsing-and-rotating-delimited-data-in-sql-server-2012/
The PARSENAME function is logically designed to parse four-part object names. The nice thing about PARSENAME is that it’s not limited to parsing just SQL Server four-part object names – it will parse any function or string data that is delimited by dots.
The first parameter is the object to parse, and the second is the integer value of the object piece to return. The article is discussing parsing and rotating delimited data - company phone numbers, but it can be used to parse name/surname data also.
Example:
USE COMPANY;
SELECT PARSENAME('Whatever.you.want.parsed',3) AS 'ReturnValue';
The article also describes using a Common Table Expression (CTE) called ‘replaceChars’, to run PARSENAME against the delimiter-replaced values. A CTE is useful for returning a temporary view or result set.
After that, the UNPIVOT function has been used to convert some columns into rows; SUBSTRING and CHARINDEX functions have been used for cleaning up the inconsistencies in the data, and the LAG function (new for SQL Server 2012) has been used in the end, as it allows referencing of previous records.
We can create a function as this
CREATE Function [dbo].[fn_CSVToTable]
(
#CSVList Varchar(max)
)
RETURNS #Table TABLE (ColumnData VARCHAR(100))
AS
BEGIN
IF RIGHT(#CSVList, 1) <> ','
SELECT #CSVList = #CSVList + ','
DECLARE #Pos BIGINT,
#OldPos BIGINT
SELECT #Pos = 1,
#OldPos = 1
WHILE #Pos < LEN(#CSVList)
BEGIN
SELECT #Pos = CHARINDEX(',', #CSVList, #OldPos)
INSERT INTO #Table
SELECT LTRIM(RTRIM(SUBSTRING(#CSVList, #OldPos, #Pos - #OldPos))) Col001
SELECT #OldPos = #Pos + 1
END
RETURN
END
We can then seperate the CSV values into our respective columns using a SELECT statement
You can use a table-valued function STRING_SPLIT, which is available only under compatibility level 130. If your database compatibility level is lower than 130, SQL Server will not be able to find and execute the STRING_SPLIT function. You can change a compatibility level of the database using the following command:
ALTER DATABASE DatabaseName SET COMPATIBILITY_LEVEL = 130
Syntax
SELECT * FROM STRING_SPLIT ( string, separator )
see documentation here
I think following function will work for you:
You have to create a function in SQL first. Like this
CREATE FUNCTION [dbo].[fn_split](
#str VARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #returnTable TABLE (idx INT PRIMARY KEY IDENTITY, item VARCHAR(8000))
AS
BEGIN
DECLARE #pos INT
SELECT #str = #str + #delimiter
WHILE LEN(#str) > 0
BEGIN
SELECT #pos = CHARINDEX(#delimiter,#str)
IF #pos = 1
INSERT #returnTable (item)
VALUES (NULL)
ELSE
INSERT #returnTable (item)
VALUES (SUBSTRING(#str, 1, #pos-1))
SELECT #str = SUBSTRING(#str, #pos+1, LEN(#str)-#pos)
END
RETURN
END
You can call this function, like this:
select * from fn_split('1,24,5',',')
Implementation:
Declare #test TABLE (
ID VARCHAR(200),
Data VARCHAR(200)
)
insert into #test
(ID, Data)
Values
('1','Cleo,Smith')
insert into #test
(ID, Data)
Values
('2','Paul,Grim')
select ID,
(select item from fn_split(Data,',') where idx in (1)) as Name ,
(select item from fn_split(Data,',') where idx in (2)) as Surname
from #test
Result will like this:
Use Parsename() function
with cte as(
select 'Aria,Karimi' as FullName
Union
select 'Joe,Karimi' as FullName
Union
select 'Bab,Karimi' as FullName
)
SELECT PARSENAME(REPLACE(FullName,',','.'),2) as Name,
PARSENAME(REPLACE(FullName,',','.'),1) as Family
FROM cte
Result
Name Family
----- ------
Aria Karimi
Bab Karimi
Joe Karimi
Try this:
declare #csv varchar(100) ='aaa,bb,csda,daass';
set #csv = #csv+',';
with cte as
(
select SUBSTRING(#csv,1,charindex(',',#csv,1)-1) as val, SUBSTRING(#csv,charindex(',',#csv,1)+1,len(#csv)) as rem
UNION ALL
select SUBSTRING(a.rem,1,charindex(',',a.rem,1)-1)as val, SUBSTRING(a.rem,charindex(',',a.rem,1)+1,len(A.rem))
from cte a where LEN(a.rem)>=1
) select val from cte
This function is most fast:
CREATE FUNCTION dbo.F_ExtractSubString
(
#String VARCHAR(MAX),
#NroSubString INT,
#Separator VARCHAR(5)
)
RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE #St INT = 0, #End INT = 0, #Ret VARCHAR(MAX)
SET #String = #String + #Separator
WHILE CHARINDEX(#Separator, #String, #End + 1) > 0 AND #NroSubString > 0
BEGIN
SET #St = #End + 1
SET #End = CHARINDEX(#Separator, #String, #End + 1)
SET #NroSubString = #NroSubString - 1
END
IF #NroSubString > 0
SET #Ret = ''
ELSE
SET #Ret = SUBSTRING(#String, #St, #End - #St)
RETURN #Ret
END
GO
Example usage:
SELECT dbo.F_ExtractSubString(COLUMN, 1, ', '),
dbo.F_ExtractSubString(COLUMN, 2, ', '),
dbo.F_ExtractSubString(COLUMN, 3, ', ')
FROM TABLE
I encountered a similar problem but a complex one and since this is the first thread i found regarding that issue i decided to post my finding. i know it is complex solution to a simple problem but i hope that i could help other people who go to this thread looking for a more complex solution. i had to split a string containing 5 numbers (column name: levelsFeed) and to show each number in a separate column.
for example: 8,1,2,2,2
should be shown as :
1 2 3 4 5
-------------
8 1 2 2 2
Solution 1: using XML functions:
this solution for the slowest solution by far
SELECT Distinct FeedbackID,
, S.a.value('(/H/r)[1]', 'INT') AS level1
, S.a.value('(/H/r)[2]', 'INT') AS level2
, S.a.value('(/H/r)[3]', 'INT') AS level3
, S.a.value('(/H/r)[4]', 'INT') AS level4
, S.a.value('(/H/r)[5]', 'INT') AS level5
FROM (
SELECT *,CAST (N'<H><r>' + REPLACE(levelsFeed, ',', '</r><r>') + '</r> </H>' AS XML) AS [vals]
FROM Feedbacks
) as d
CROSS APPLY d.[vals].nodes('/H/r') S(a)
Solution 2: using Split function and pivot. (the split function split a string to rows with the column name Data)
SELECT FeedbackID, [1],[2],[3],[4],[5]
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY feedbackID ORDER BY (SELECT null)) as rn
FROM (
SELECT FeedbackID, levelsFeed
FROM Feedbacks
) as a
CROSS APPLY dbo.Split(levelsFeed, ',')
) as SourceTable
PIVOT
(
MAX(data)
FOR rn IN ([1],[2],[3],[4],[5])
)as pivotTable
Solution 3: using string manipulations functions - fastest by small margin over solution 2
SELECT FeedbackID,
SUBSTRING(levelsFeed,0,CHARINDEX(',',levelsFeed)) AS level1,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),4) AS level2,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),3) AS level3,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),2) AS level4,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),1) AS level5
FROM Feedbacks
since the levelsFeed contains 5 string values i needed to use the substring function for the first string.
i hope that my solution will help other that got to this thread looking for a more complex split to columns methods
Using instring function :)
select Value,
substring(String,1,instr(String," ") -1) Fname,
substring(String,instr(String,",") +1) Sname
from tablename;
Used two functions,
1. substring(string, position, length) ==> returns string from positon to length
2. instr(string,pattern) ==> returns position of pattern.
If we don’t provide length argument in substring it returns until end of string
This worked for me
CREATE FUNCTION [dbo].[SplitString](
#delimited NVARCHAR(MAX),
#delimiter NVARCHAR(100)
) RETURNS #t TABLE ( val NVARCHAR(MAX))
AS
BEGIN
DECLARE #xml XML
SET #xml = N'<t>' + REPLACE(#delimited,#delimiter,'</t><t>') + '</t>'
INSERT INTO #t(val)
SELECT r.value('.','varchar(MAX)') as item
FROM #xml.nodes('/t') as records(r)
RETURN
END
mytable:
Value ColOne
--------------------
1 Cleo, Smith
The following should work if there aren't too many columns
ALTER TABLE mytable ADD ColTwo nvarchar(256);
UPDATE mytable SET ColTwo = LEFT(ColOne, Charindex(',', ColOne) - 1);
--'Cleo' = LEFT('Cleo, Smith', Charindex(',', 'Cleo, Smith') - 1)
UPDATE mytable SET ColTwo = REPLACE(ColOne, ColTwo + ',', '');
--' Smith' = REPLACE('Cleo, Smith', 'Cleo' + ',')
UPDATE mytable SET ColOne = REPLACE(ColOne, ',' + ColTwo, ''), ColTwo = LTRIM(ColTwo);
--'Cleo' = REPLACE('Cleo, Smith', ',' + ' Smith', '')
Result:
Value ColOne ColTwo
--------------------
1 Cleo Smith
DECLARE #INPUT VARCHAR (MAX)='N,A,R,E,N,D,R,A'
DECLARE #ELIMINATE_CHAR CHAR (1)=','
DECLARE #L_START INT=1
DECLARE #L_END INT=(SELECT LEN (#INPUT))
DECLARE #OUTPUT CHAR (1)
WHILE #L_START <=#L_END
BEGIN
SET #OUTPUT=(SUBSTRING (#INPUT,#L_START,1))
IF #OUTPUT!=#ELIMINATE_CHAR
BEGIN
PRINT #OUTPUT
END
SET #L_START=#L_START+1
END
You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project).
This is the code part from this page:
CREATE FUNCTION [fn_ParseText2Table]
(#p_SourceText VARCHAR(MAX)
,#p_Delimeter VARCHAR(100)=',' --default to comma delimited.
)
RETURNS #retTable
TABLE([Position] INT IDENTITY(1,1)
,[Int_Value] INT
,[Num_Value] NUMERIC(18,3)
,[Txt_Value] VARCHAR(MAX)
,[Date_value] DATETIME
)
AS
/*
********************************************************************************
Purpose: Parse values from a delimited string
& return the result as an indexed table
Copyright 1996, 1997, 2000, 2003 Clayton Groom (Clayton_Groom#hotmail.com)
Posted to the public domain Aug, 2004
2003-06-17 Rewritten as SQL 2000 function.
Reworked to allow for delimiters > 1 character in length
and to convert Text values to numbers
2016-04-05 Added logic for date values based on "new" ISDATE() function, Updated to use XML approach, which is more efficient.
********************************************************************************
*/
BEGIN
DECLARE #w_xml xml;
SET #w_xml = N'<root><i>' + replace(#p_SourceText, #p_Delimeter,'</i><i>') + '</i></root>';
INSERT INTO #retTable
([Int_Value]
, [Num_Value]
, [Txt_Value]
, [Date_value]
)
SELECT CASE
WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST(CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC) AS INT)
END AS [Int_Value]
, CASE
WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC(18, 3))
END AS [Num_Value]
, [i].value('.', 'VARCHAR(MAX)') AS [txt_Value]
, CASE
WHEN ISDATE([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST([i].value('.', 'VARCHAR(MAX)') AS DATETIME)
END AS [Num_Value]
FROM #w_xml.nodes('//root/i') AS [Items]([i]);
RETURN;
END;
GO
ALTER function get_occurance_index(#delimiter varchar(1),#occurence int,#String varchar(100))
returns int
AS Begin
--Declare #delimiter varchar(1)=',',#occurence int=2,#String varchar(100)='a,b,c'
Declare #result int
;with T as (
select 1 Rno,0 as row, charindex(#delimiter, #String) pos,#String st
union all
select Rno+1,pos + 1, charindex(#delimiter, #String, pos + 1), #String
from T
where pos > 0
)
select #result=pos
from T
where pos > 0 and rno = #occurence
return isnull(#result,0)
ENd
declare #data as table (data varchar(100))
insert into #data values('1,2,3')
insert into #data values('aaa,bbbbb,cccc')
select top 3 Substring (data,0,dbo.get_occurance_index( ',',1,data)) ,--First Record always starts with 0
Substring (data,dbo.get_occurance_index( ',',1,data)+1,dbo.get_occurance_index( ',',2,data)-dbo.get_occurance_index( ',',1,data)-1) ,
Substring (data,dbo.get_occurance_index( ',',2,data)+1,len(data)) , -- Last record cant be more than len of actual data
data
From #data
I found that using PARSENAME as above caused any name with a period to get nulled.
So if there was an initial or a title in the name followed by a dot they return NULL.
I found this worked for me:
SELECT
REPLACE(SUBSTRING(FullName, 1,CHARINDEX(',', FullName)), ',','') as Name,
REPLACE(SUBSTRING(FullName, CHARINDEX(',', FullName), LEN(FullName)), ',', '') as Surname
FROM Table1
it is so easy, you can take it by below query:
DECLARE #str NVARCHAR(MAX)='ControlID_05436b78-04ba-9667-fa01-9ff8c1b7c235,3'
SELECT LEFT(#str, CHARINDEX(',',#str)-1),RIGHT(#str,LEN(#str)-(CHARINDEX(',',#str)))
select distinct modelFileId,F4.*
from contract
cross apply (select XmlList=convert(xml, '<x>'+replace(modelFileId,';','</x><x>')+'</x>').query('.')) F2
cross apply (select mfid1=XmlNode.value('/x[1]','varchar(512)')
,mfid2=XmlNode.value('/x[2]','varchar(512)')
,mfid3=XmlNode.value('/x[3]','varchar(512)')
,mfid4=XmlNode.value('/x[4]','varchar(512)') from XmlList.nodes('x') F3(XmlNode)) F4
where modelFileId like '%;%'
order by modelFileId
Select distinct PROJ_UID,PROJ_NAME,RES_UID from E2E_ProjectWiseTimesheetActuals
where CHARINDEX(','+cast(PROJ_UID as varchar(8000))+',', #params) > 0 and CHARINDEX(','+cast(RES_UID as varchar(8000))+',', #res) > 0
I re-wrote an answer above and made it better:
CREATE FUNCTION [dbo].[CSVParser]
(
#s VARCHAR(255),
#idx NUMERIC
)
RETURNS VARCHAR(12)
BEGIN
DECLARE #comma int
SET #comma = CHARINDEX(',', #s)
WHILE 1=1
BEGIN
IF #comma=0
IF #idx=1
RETURN #s
ELSE
RETURN ''
IF #idx=1
BEGIN
DECLARE #word VARCHAR(12)
SET #word=LEFT(#s, #comma - 1)
RETURN #word
END
SET #s = RIGHT(#s,LEN(#s)-#comma)
SET #comma = CHARINDEX(',', #s)
SET #idx = #idx - 1
END
RETURN 'not used'
END
Example usage:
SELECT dbo.CSVParser(COLUMN, 1),
dbo.CSVParser(COLUMN, 2),
dbo.CSVParser(COLUMN, 3)
FROM TABLE
question is simple, but problem is hot :)
So I create some wrapper for string_split() which pivot result in more generic way. It's table function which returns values (nn, value1, value2, ... , value50) - enough for most CSV lines. If there are more values, they will wrap to next line - nn indicate line number. Set third parameter #columnCnt = [yourNumber] to wrap at specific position:
alter FUNCTION fn_Split50
(
#str varchar(max),
#delim char(1),
#columnCnt int = 50
)
RETURNS TABLE
AS
RETURN
(
SELECT *
FROM (SELECT
nn = (nn - 1) / #columnCnt + 1,
nnn = 'value' + cast(((nn - 1) % #columnCnt) + 1 as varchar(10)),
value
FROM (SELECT
nn = ROW_NUMBER() over (order by (select null)),
value
FROM string_split(#str, #delim) aa
) aa
where nn > 0
) bb
PIVOT
(
max(value)
FOR nnn IN (
value1, value2, value3, value4, value5, value6, value7, value8, value9, value10,
value11, value12, value13, value14, value15, value16, value17, value18, value19, value20,
value21, value22, value23, value24, value25, value26, value27, value28, value29, value30,
value31, value32, value33, value34, value35, value36, value37, value38, value39, value40,
value41, value42, value43, value44, value45, value46, value47, value48, value49, value50
)
) AS PivotTable
)
Example of using:
select * from dbo.fn_split50('zz1,aa2,ss3,dd4,ff5', ',', DEFAULT)
select * from dbo.fn_split50('zz1,aa2,ss3,dd4,ff5,gg6,hh7,jj8,ww9,qq10', ',', 3)
select * from dbo.fn_split50('zz1,11,aa2,22,ss3,33,dd4,44,ff5,55,gg6,66,hh7,77,jj8,88,ww9,99,qq10,1010', ',',2)
Hope, it will helps :)

Splitting SQL columns by delimiter in SQL Server 12 [duplicate]

I have a table like this
Value String
-------------------
1 Cleo, Smith
I want to separate the comma delimited string into two columns
Value Name Surname
-------------------
1 Cleo Smith
I need only two fixed extra columns
Your purpose can be solved using following query -
Select Value , Substring(FullName, 1,Charindex(',', FullName)-1) as Name,
Substring(FullName, Charindex(',', FullName)+1, LEN(FullName)) as Surname
from Table1
There is no readymade Split function in sql server, so we need to create user defined function.
CREATE FUNCTION Split (
#InputString VARCHAR(8000),
#Delimiter VARCHAR(50)
)
RETURNS #Items TABLE (
Item VARCHAR(8000)
)
AS
BEGIN
IF #Delimiter = ' '
BEGIN
SET #Delimiter = ','
SET #InputString = REPLACE(#InputString, ' ', #Delimiter)
END
IF (#Delimiter IS NULL OR #Delimiter = '')
SET #Delimiter = ','
--INSERT INTO #Items VALUES (#Delimiter) -- Diagnostic
--INSERT INTO #Items VALUES (#InputString) -- Diagnostic
DECLARE #Item VARCHAR(8000)
DECLARE #ItemList VARCHAR(8000)
DECLARE #DelimIndex INT
SET #ItemList = #InputString
SET #DelimIndex = CHARINDEX(#Delimiter, #ItemList, 0)
WHILE (#DelimIndex != 0)
BEGIN
SET #Item = SUBSTRING(#ItemList, 0, #DelimIndex)
INSERT INTO #Items VALUES (#Item)
-- Set #ItemList = #ItemList minus one less item
SET #ItemList = SUBSTRING(#ItemList, #DelimIndex+1, LEN(#ItemList)-#DelimIndex)
SET #DelimIndex = CHARINDEX(#Delimiter, #ItemList, 0)
END -- End WHILE
IF #Item IS NOT NULL -- At least one delimiter was encountered in #InputString
BEGIN
SET #Item = #ItemList
INSERT INTO #Items VALUES (#Item)
END
-- No delimiters were encountered in #InputString, so just return #InputString
ELSE INSERT INTO #Items VALUES (#InputString)
RETURN
END -- End Function
GO
---- Set Permissions
--GRANT SELECT ON Split TO UserRole1
--GRANT SELECT ON Split TO UserRole2
--GO
;WITH Split_Names (Value,Name, xmlname)
AS
(
SELECT Value,
Name,
CONVERT(XML,'<Names><name>'
+ REPLACE(Name,',', '</name><name>') + '</name></Names>') AS xmlname
FROM tblnames
)
SELECT Value,
xmlname.value('/Names[1]/name[1]','varchar(100)') AS Name,
xmlname.value('/Names[1]/name[2]','varchar(100)') AS Surname
FROM Split_Names
and also check the link below for reference
http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html
xml based answer is simple and clean
refer this
DECLARE #S varchar(max),
#Split char(1),
#X xml
SELECT #S = 'ab,cd,ef,gh,ij',
#Split = ','
SELECT #X = CONVERT(xml,' <root> <myvalue>' +
REPLACE(#S,#Split,'</myvalue> <myvalue>') + '</myvalue> </root> ')
SELECT T.c.value('.','varchar(20)'), --retrieve ALL values at once
T.c.value('(/root/myvalue)[1]','VARCHAR(20)') , --retrieve index 1 only, which is the 'ab'
T.c.value('(/root/myvalue)[2]','VARCHAR(20)')
FROM #X.nodes('/root/myvalue') T(c)
I think this is cool
SELECT value,
PARSENAME(REPLACE(String,',','.'),2) 'Name' ,
PARSENAME(REPLACE(String,',','.'),1) 'Surname'
FROM table WITH (NOLOCK)
With CROSS APPLY
select ParsedData.*
from MyTable mt
cross apply ( select str = mt.String + ',,' ) f1
cross apply ( select p1 = charindex( ',', str ) ) ap1
cross apply ( select p2 = charindex( ',', str, p1 + 1 ) ) ap2
cross apply ( select Nmame = substring( str, 1, p1-1 )
, Surname = substring( str, p1+1, p2-p1-1 )
) ParsedData
There are multiple ways to solve this and many different ways have been proposed already. Simplest would be to use LEFT / SUBSTRING and other string functions to achieve the desired result.
Sample Data
DECLARE #tbl1 TABLE (Value INT,String VARCHAR(MAX))
INSERT INTO #tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO #tbl1 VALUES(2,'John, Mathew');
Using String Functions like LEFT
SELECT
Value,
LEFT(String,CHARINDEX(',',String)-1) as Fname,
LTRIM(RIGHT(String,LEN(String) - CHARINDEX(',',String) )) AS Lname
FROM #tbl1
This approach fails if there are more 2 items in a String.
In such a scenario, we can use a splitter and then use PIVOT or convert the string into an XML and use .nodes to get string items. XML based solution have been detailed out by aads and bvr in their solution.
The answers for this question which use splitter, all use WHILE which is inefficient for splitting. Check this performance comparison. One of the best splitters around is DelimitedSplit8K, created by Jeff Moden. You can read more about it here
Splitter with PIVOT
DECLARE #tbl1 TABLE (Value INT,String VARCHAR(MAX))
INSERT INTO #tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO #tbl1 VALUES(2,'John, Mathew');
SELECT t3.Value,[1] as Fname,[2] as Lname
FROM #tbl1 as t1
CROSS APPLY [dbo].[DelimitedSplit8K](String,',') as t2
PIVOT(MAX(Item) FOR ItemNumber IN ([1],[2])) as t3
Output
Value Fname Lname
1 Cleo Smith
2 John Mathew
DelimitedSplit8K by Jeff Moden
CREATE FUNCTION [dbo].[DelimitedSplit8K]
/**********************************************************************************************************************
Purpose:
Split a given string at a given delimiter and return a list of the split elements (items).
Notes:
1. Leading a trailing delimiters are treated as if an empty string element were present.
2. Consecutive delimiters are treated as if an empty string element were present between them.
3. Except when spaces are used as a delimiter, all spaces present in each element are preserved.
Returns:
iTVF containing the following:
ItemNumber = Element position of Item as a BIGINT (not converted to INT to eliminate a CAST)
Item = Element value as a VARCHAR(8000)
Statistics on this function may be found at the following URL:
http://www.sqlservercentral.com/Forums/Topic1101315-203-4.aspx
CROSS APPLY Usage Examples and Tests:
--=====================================================================================================================
-- TEST 1:
-- This tests for various possible conditions in a string using a comma as the delimiter. The expected results are
-- laid out in the comments
--=====================================================================================================================
--===== Conditionally drop the test tables to make reruns easier for testing.
-- (this is NOT a part of the solution)
IF OBJECT_ID('tempdb..#JBMTest') IS NOT NULL DROP TABLE #JBMTest
;
--===== Create and populate a test table on the fly (this is NOT a part of the solution).
-- In the following comments, "b" is a blank and "E" is an element in the left to right order.
-- Double Quotes are used to encapsulate the output of "Item" so that you can see that all blanks
-- are preserved no matter where they may appear.
SELECT *
INTO #JBMTest
FROM ( --# & type of Return Row(s)
SELECT 0, NULL UNION ALL --1 NULL
SELECT 1, SPACE(0) UNION ALL --1 b (Empty String)
SELECT 2, SPACE(1) UNION ALL --1 b (1 space)
SELECT 3, SPACE(5) UNION ALL --1 b (5 spaces)
SELECT 4, ',' UNION ALL --2 b b (both are empty strings)
SELECT 5, '55555' UNION ALL --1 E
SELECT 6, ',55555' UNION ALL --2 b E
SELECT 7, ',55555,' UNION ALL --3 b E b
SELECT 8, '55555,' UNION ALL --2 b B
SELECT 9, '55555,1' UNION ALL --2 E E
SELECT 10, '1,55555' UNION ALL --2 E E
SELECT 11, '55555,4444,333,22,1' UNION ALL --5 E E E E E
SELECT 12, '55555,4444,,333,22,1' UNION ALL --6 E E b E E E
SELECT 13, ',55555,4444,,333,22,1,' UNION ALL --8 b E E b E E E b
SELECT 14, ',55555,4444,,,333,22,1,' UNION ALL --9 b E E b b E E E b
SELECT 15, ' 4444,55555 ' UNION ALL --2 E (w/Leading Space) E (w/Trailing Space)
SELECT 16, 'This,is,a,test.' --E E E E
) d (SomeID, SomeValue)
;
--===== Split the CSV column for the whole table using CROSS APPLY (this is the solution)
SELECT test.SomeID, test.SomeValue, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
FROM #JBMTest test
CROSS APPLY dbo.DelimitedSplit8K(test.SomeValue,',') split
;
--=====================================================================================================================
-- TEST 2:
-- This tests for various "alpha" splits and COLLATION using all ASCII characters from 0 to 255 as a delimiter against
-- a given string. Note that not all of the delimiters will be visible and some will show up as tiny squares because
-- they are "control" characters. More specifically, this test will show you what happens to various non-accented
-- letters for your given collation depending on the delimiter you chose.
--=====================================================================================================================
WITH
cteBuildAllCharacters (String,Delimiter) AS
(
SELECT TOP 256
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
CHAR(ROW_NUMBER() OVER (ORDER BY (SELECT NULL))-1)
FROM master.sys.all_columns
)
SELECT ASCII_Value = ASCII(c.Delimiter), c.Delimiter, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
FROM cteBuildAllCharacters c
CROSS APPLY dbo.DelimitedSplit8K(c.String,c.Delimiter) split
ORDER BY ASCII_Value, split.ItemNumber
;
-----------------------------------------------------------------------------------------------------------------------
Other Notes:
1. Optimized for VARCHAR(8000) or less. No testing or error reporting for truncation at 8000 characters is done.
2. Optimized for single character delimiter. Multi-character delimiters should be resolvedexternally from this
function.
3. Optimized for use with CROSS APPLY.
4. Does not "trim" elements just in case leading or trailing blanks are intended.
5. If you don't know how a Tally table can be used to replace loops, please see the following...
http://www.sqlservercentral.com/articles/T-SQL/62867/
6. Changing this function to use NVARCHAR(MAX) will cause it to run twice as slow. It's just the nature of
VARCHAR(MAX) whether it fits in-row or not.
7. Multi-machine testing for the method of using UNPIVOT instead of 10 SELECT/UNION ALLs shows that the UNPIVOT method
is quite machine dependent and can slow things down quite a bit.
-----------------------------------------------------------------------------------------------------------------------
Credits:
This code is the product of many people's efforts including but not limited to the following:
cteTally concept originally by Iztek Ben Gan and "decimalized" by Lynn Pettis (and others) for a bit of extra speed
and finally redacted by Jeff Moden for a different slant on readability and compactness. Hat's off to Paul White for
his simple explanations of CROSS APPLY and for his detailed testing efforts. Last but not least, thanks to
Ron "BitBucket" McCullough and Wayne Sheffield for their extreme performance testing across multiple machines and
versions of SQL Server. The latest improvement brought an additional 15-20% improvement over Rev 05. Special thanks
to "Nadrek" and "peter-757102" (aka Peter de Heer) for bringing such improvements to light. Nadrek's original
improvement brought about a 10% performance gain and Peter followed that up with the content of Rev 07.
I also thank whoever wrote the first article I ever saw on "numbers tables" which is located at the following URL
and to Adam Machanic for leading me to it many years ago.
http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html
-----------------------------------------------------------------------------------------------------------------------
Revision History:
Rev 00 - 20 Jan 2010 - Concept for inline cteTally: Lynn Pettis and others.
Redaction/Implementation: Jeff Moden
- Base 10 redaction and reduction for CTE. (Total rewrite)
Rev 01 - 13 Mar 2010 - Jeff Moden
- Removed one additional concatenation and one subtraction from the SUBSTRING in the SELECT List for that tiny
bit of extra speed.
Rev 02 - 14 Apr 2010 - Jeff Moden
- No code changes. Added CROSS APPLY usage example to the header, some additional credits, and extra
documentation.
Rev 03 - 18 Apr 2010 - Jeff Moden
- No code changes. Added notes 7, 8, and 9 about certain "optimizations" that don't actually work for this
type of function.
Rev 04 - 29 Jun 2010 - Jeff Moden
- Added WITH SCHEMABINDING thanks to a note by Paul White. This prevents an unnecessary "Table Spool" when the
function is used in an UPDATE statement even though the function makes no external references.
Rev 05 - 02 Apr 2011 - Jeff Moden
- Rewritten for extreme performance improvement especially for larger strings approaching the 8K boundary and
for strings that have wider elements. The redaction of this code involved removing ALL concatenation of
delimiters, optimization of the maximum "N" value by using TOP instead of including it in the WHERE clause,
and the reduction of all previous calculations (thanks to the switch to a "zero based" cteTally) to just one
instance of one add and one instance of a subtract. The length calculation for the final element (not
followed by a delimiter) in the string to be split has been greatly simplified by using the ISNULL/NULLIF
combination to determine when the CHARINDEX returned a 0 which indicates there are no more delimiters to be
had or to start with. Depending on the width of the elements, this code is between 4 and 8 times faster on a
single CPU box than the original code especially near the 8K boundary.
- Modified comments to include more sanity checks on the usage example, etc.
- Removed "other" notes 8 and 9 as they were no longer applicable.
Rev 06 - 12 Apr 2011 - Jeff Moden
- Based on a suggestion by Ron "Bitbucket" McCullough, additional test rows were added to the sample code and
the code was changed to encapsulate the output in pipes so that spaces and empty strings could be perceived
in the output. The first "Notes" section was added. Finally, an extra test was added to the comments above.
Rev 07 - 06 May 2011 - Peter de Heer, a further 15-20% performance enhancement has been discovered and incorporated
into this code which also eliminated the need for a "zero" position in the cteTally table.
**********************************************************************************************************************/
--===== Define I/O parameters
(#pString VARCHAR(8000), #pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
-- enough to cover NVARCHAR(4000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(#pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(#pString,t.N,1) = #pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(#pDelimiter,#pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(#pString, l.N1, l.L1)
FROM cteLen l
;
GO
With SQL Server 2016 we can use string_split to accomplish this:
create table commasep (
id int identity(1,1)
,string nvarchar(100) )
insert into commasep (string) values ('John, Adam'), ('test1,test2,test3')
select id, [value] as String from commasep
cross apply string_split(string,',')
CREATE FUNCTION [dbo].[fn_split_string_to_column] (
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #out_put TABLE (
[column_id] INT IDENTITY(1, 1) NOT NULL,
[value] NVARCHAR(MAX)
)
AS
BEGIN
DECLARE #value NVARCHAR(MAX),
#pos INT = 0,
#len INT = 0
SET #string = CASE
WHEN RIGHT(#string, 1) != #delimiter
THEN #string + #delimiter
ELSE #string
END
WHILE CHARINDEX(#delimiter, #string, #pos + 1) > 0
BEGIN
SET #len = CHARINDEX(#delimiter, #string, #pos + 1) - #pos
SET #value = SUBSTRING(#string, #pos, #len)
INSERT INTO #out_put ([value])
SELECT LTRIM(RTRIM(#value)) AS [column]
SET #pos = CHARINDEX(#delimiter, #string, #pos + #len) + 1
END
RETURN
END
SELECT id,
Substring(NAME, 0, Charindex(',', NAME)) AS firstname,
Substring(NAME, Charindex(',', NAME), Len(NAME) + 1) AS lastname
FROM spilt
Try this (change instances of ' ' to ',' or whatever delimiter you want to use)
CREATE FUNCTION dbo.Wordparser
(
#multiwordstring VARCHAR(255),
#wordnumber NUMERIC
)
returns VARCHAR(255)
AS
BEGIN
DECLARE #remainingstring VARCHAR(255)
SET #remainingstring=#multiwordstring
DECLARE #numberofwords NUMERIC
SET #numberofwords=(LEN(#remainingstring) - LEN(REPLACE(#remainingstring, ' ', '')) + 1)
DECLARE #word VARCHAR(50)
DECLARE #parsedwords TABLE
(
line NUMERIC IDENTITY(1, 1),
word VARCHAR(255)
)
WHILE #numberofwords > 1
BEGIN
SET #word=LEFT(#remainingstring, CHARINDEX(' ', #remainingstring) - 1)
INSERT INTO #parsedwords(word)
SELECT #word
SET #remainingstring= REPLACE(#remainingstring, Concat(#word, ' '), '')
SET #numberofwords=(LEN(#remainingstring) - LEN(REPLACE(#remainingstring, ' ', '')) + 1)
IF #numberofwords = 1
BREAK
ELSE
CONTINUE
END
IF #numberofwords = 1
SELECT #word = #remainingstring
INSERT INTO #parsedwords(word)
SELECT #word
RETURN
(SELECT word
FROM #parsedwords
WHERE line = #wordnumber)
END
Example usage:
SELECT dbo.Wordparser(COLUMN, 1),
dbo.Wordparser(COLUMN, 2),
dbo.Wordparser(COLUMN, 3)
FROM TABLE
I think PARSENAME is the neat function to use for this example, as described in this article: http://www.sqlshack.com/parsing-and-rotating-delimited-data-in-sql-server-2012/
The PARSENAME function is logically designed to parse four-part object names. The nice thing about PARSENAME is that it’s not limited to parsing just SQL Server four-part object names – it will parse any function or string data that is delimited by dots.
The first parameter is the object to parse, and the second is the integer value of the object piece to return. The article is discussing parsing and rotating delimited data - company phone numbers, but it can be used to parse name/surname data also.
Example:
USE COMPANY;
SELECT PARSENAME('Whatever.you.want.parsed',3) AS 'ReturnValue';
The article also describes using a Common Table Expression (CTE) called ‘replaceChars’, to run PARSENAME against the delimiter-replaced values. A CTE is useful for returning a temporary view or result set.
After that, the UNPIVOT function has been used to convert some columns into rows; SUBSTRING and CHARINDEX functions have been used for cleaning up the inconsistencies in the data, and the LAG function (new for SQL Server 2012) has been used in the end, as it allows referencing of previous records.
We can create a function as this
CREATE Function [dbo].[fn_CSVToTable]
(
#CSVList Varchar(max)
)
RETURNS #Table TABLE (ColumnData VARCHAR(100))
AS
BEGIN
IF RIGHT(#CSVList, 1) <> ','
SELECT #CSVList = #CSVList + ','
DECLARE #Pos BIGINT,
#OldPos BIGINT
SELECT #Pos = 1,
#OldPos = 1
WHILE #Pos < LEN(#CSVList)
BEGIN
SELECT #Pos = CHARINDEX(',', #CSVList, #OldPos)
INSERT INTO #Table
SELECT LTRIM(RTRIM(SUBSTRING(#CSVList, #OldPos, #Pos - #OldPos))) Col001
SELECT #OldPos = #Pos + 1
END
RETURN
END
We can then seperate the CSV values into our respective columns using a SELECT statement
You can use a table-valued function STRING_SPLIT, which is available only under compatibility level 130. If your database compatibility level is lower than 130, SQL Server will not be able to find and execute the STRING_SPLIT function. You can change a compatibility level of the database using the following command:
ALTER DATABASE DatabaseName SET COMPATIBILITY_LEVEL = 130
Syntax
SELECT * FROM STRING_SPLIT ( string, separator )
see documentation here
I think following function will work for you:
You have to create a function in SQL first. Like this
CREATE FUNCTION [dbo].[fn_split](
#str VARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #returnTable TABLE (idx INT PRIMARY KEY IDENTITY, item VARCHAR(8000))
AS
BEGIN
DECLARE #pos INT
SELECT #str = #str + #delimiter
WHILE LEN(#str) > 0
BEGIN
SELECT #pos = CHARINDEX(#delimiter,#str)
IF #pos = 1
INSERT #returnTable (item)
VALUES (NULL)
ELSE
INSERT #returnTable (item)
VALUES (SUBSTRING(#str, 1, #pos-1))
SELECT #str = SUBSTRING(#str, #pos+1, LEN(#str)-#pos)
END
RETURN
END
You can call this function, like this:
select * from fn_split('1,24,5',',')
Implementation:
Declare #test TABLE (
ID VARCHAR(200),
Data VARCHAR(200)
)
insert into #test
(ID, Data)
Values
('1','Cleo,Smith')
insert into #test
(ID, Data)
Values
('2','Paul,Grim')
select ID,
(select item from fn_split(Data,',') where idx in (1)) as Name ,
(select item from fn_split(Data,',') where idx in (2)) as Surname
from #test
Result will like this:
Use Parsename() function
with cte as(
select 'Aria,Karimi' as FullName
Union
select 'Joe,Karimi' as FullName
Union
select 'Bab,Karimi' as FullName
)
SELECT PARSENAME(REPLACE(FullName,',','.'),2) as Name,
PARSENAME(REPLACE(FullName,',','.'),1) as Family
FROM cte
Result
Name Family
----- ------
Aria Karimi
Bab Karimi
Joe Karimi
Try this:
declare #csv varchar(100) ='aaa,bb,csda,daass';
set #csv = #csv+',';
with cte as
(
select SUBSTRING(#csv,1,charindex(',',#csv,1)-1) as val, SUBSTRING(#csv,charindex(',',#csv,1)+1,len(#csv)) as rem
UNION ALL
select SUBSTRING(a.rem,1,charindex(',',a.rem,1)-1)as val, SUBSTRING(a.rem,charindex(',',a.rem,1)+1,len(A.rem))
from cte a where LEN(a.rem)>=1
) select val from cte
This function is most fast:
CREATE FUNCTION dbo.F_ExtractSubString
(
#String VARCHAR(MAX),
#NroSubString INT,
#Separator VARCHAR(5)
)
RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE #St INT = 0, #End INT = 0, #Ret VARCHAR(MAX)
SET #String = #String + #Separator
WHILE CHARINDEX(#Separator, #String, #End + 1) > 0 AND #NroSubString > 0
BEGIN
SET #St = #End + 1
SET #End = CHARINDEX(#Separator, #String, #End + 1)
SET #NroSubString = #NroSubString - 1
END
IF #NroSubString > 0
SET #Ret = ''
ELSE
SET #Ret = SUBSTRING(#String, #St, #End - #St)
RETURN #Ret
END
GO
Example usage:
SELECT dbo.F_ExtractSubString(COLUMN, 1, ', '),
dbo.F_ExtractSubString(COLUMN, 2, ', '),
dbo.F_ExtractSubString(COLUMN, 3, ', ')
FROM TABLE
I encountered a similar problem but a complex one and since this is the first thread i found regarding that issue i decided to post my finding. i know it is complex solution to a simple problem but i hope that i could help other people who go to this thread looking for a more complex solution. i had to split a string containing 5 numbers (column name: levelsFeed) and to show each number in a separate column.
for example: 8,1,2,2,2
should be shown as :
1 2 3 4 5
-------------
8 1 2 2 2
Solution 1: using XML functions:
this solution for the slowest solution by far
SELECT Distinct FeedbackID,
, S.a.value('(/H/r)[1]', 'INT') AS level1
, S.a.value('(/H/r)[2]', 'INT') AS level2
, S.a.value('(/H/r)[3]', 'INT') AS level3
, S.a.value('(/H/r)[4]', 'INT') AS level4
, S.a.value('(/H/r)[5]', 'INT') AS level5
FROM (
SELECT *,CAST (N'<H><r>' + REPLACE(levelsFeed, ',', '</r><r>') + '</r> </H>' AS XML) AS [vals]
FROM Feedbacks
) as d
CROSS APPLY d.[vals].nodes('/H/r') S(a)
Solution 2: using Split function and pivot. (the split function split a string to rows with the column name Data)
SELECT FeedbackID, [1],[2],[3],[4],[5]
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY feedbackID ORDER BY (SELECT null)) as rn
FROM (
SELECT FeedbackID, levelsFeed
FROM Feedbacks
) as a
CROSS APPLY dbo.Split(levelsFeed, ',')
) as SourceTable
PIVOT
(
MAX(data)
FOR rn IN ([1],[2],[3],[4],[5])
)as pivotTable
Solution 3: using string manipulations functions - fastest by small margin over solution 2
SELECT FeedbackID,
SUBSTRING(levelsFeed,0,CHARINDEX(',',levelsFeed)) AS level1,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),4) AS level2,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),3) AS level3,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),2) AS level4,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),1) AS level5
FROM Feedbacks
since the levelsFeed contains 5 string values i needed to use the substring function for the first string.
i hope that my solution will help other that got to this thread looking for a more complex split to columns methods
Using instring function :)
select Value,
substring(String,1,instr(String," ") -1) Fname,
substring(String,instr(String,",") +1) Sname
from tablename;
Used two functions,
1. substring(string, position, length) ==> returns string from positon to length
2. instr(string,pattern) ==> returns position of pattern.
If we don’t provide length argument in substring it returns until end of string
This worked for me
CREATE FUNCTION [dbo].[SplitString](
#delimited NVARCHAR(MAX),
#delimiter NVARCHAR(100)
) RETURNS #t TABLE ( val NVARCHAR(MAX))
AS
BEGIN
DECLARE #xml XML
SET #xml = N'<t>' + REPLACE(#delimited,#delimiter,'</t><t>') + '</t>'
INSERT INTO #t(val)
SELECT r.value('.','varchar(MAX)') as item
FROM #xml.nodes('/t') as records(r)
RETURN
END
mytable:
Value ColOne
--------------------
1 Cleo, Smith
The following should work if there aren't too many columns
ALTER TABLE mytable ADD ColTwo nvarchar(256);
UPDATE mytable SET ColTwo = LEFT(ColOne, Charindex(',', ColOne) - 1);
--'Cleo' = LEFT('Cleo, Smith', Charindex(',', 'Cleo, Smith') - 1)
UPDATE mytable SET ColTwo = REPLACE(ColOne, ColTwo + ',', '');
--' Smith' = REPLACE('Cleo, Smith', 'Cleo' + ',')
UPDATE mytable SET ColOne = REPLACE(ColOne, ',' + ColTwo, ''), ColTwo = LTRIM(ColTwo);
--'Cleo' = REPLACE('Cleo, Smith', ',' + ' Smith', '')
Result:
Value ColOne ColTwo
--------------------
1 Cleo Smith
DECLARE #INPUT VARCHAR (MAX)='N,A,R,E,N,D,R,A'
DECLARE #ELIMINATE_CHAR CHAR (1)=','
DECLARE #L_START INT=1
DECLARE #L_END INT=(SELECT LEN (#INPUT))
DECLARE #OUTPUT CHAR (1)
WHILE #L_START <=#L_END
BEGIN
SET #OUTPUT=(SUBSTRING (#INPUT,#L_START,1))
IF #OUTPUT!=#ELIMINATE_CHAR
BEGIN
PRINT #OUTPUT
END
SET #L_START=#L_START+1
END
You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project).
This is the code part from this page:
CREATE FUNCTION [fn_ParseText2Table]
(#p_SourceText VARCHAR(MAX)
,#p_Delimeter VARCHAR(100)=',' --default to comma delimited.
)
RETURNS #retTable
TABLE([Position] INT IDENTITY(1,1)
,[Int_Value] INT
,[Num_Value] NUMERIC(18,3)
,[Txt_Value] VARCHAR(MAX)
,[Date_value] DATETIME
)
AS
/*
********************************************************************************
Purpose: Parse values from a delimited string
& return the result as an indexed table
Copyright 1996, 1997, 2000, 2003 Clayton Groom (Clayton_Groom#hotmail.com)
Posted to the public domain Aug, 2004
2003-06-17 Rewritten as SQL 2000 function.
Reworked to allow for delimiters > 1 character in length
and to convert Text values to numbers
2016-04-05 Added logic for date values based on "new" ISDATE() function, Updated to use XML approach, which is more efficient.
********************************************************************************
*/
BEGIN
DECLARE #w_xml xml;
SET #w_xml = N'<root><i>' + replace(#p_SourceText, #p_Delimeter,'</i><i>') + '</i></root>';
INSERT INTO #retTable
([Int_Value]
, [Num_Value]
, [Txt_Value]
, [Date_value]
)
SELECT CASE
WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST(CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC) AS INT)
END AS [Int_Value]
, CASE
WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC(18, 3))
END AS [Num_Value]
, [i].value('.', 'VARCHAR(MAX)') AS [txt_Value]
, CASE
WHEN ISDATE([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST([i].value('.', 'VARCHAR(MAX)') AS DATETIME)
END AS [Num_Value]
FROM #w_xml.nodes('//root/i') AS [Items]([i]);
RETURN;
END;
GO
ALTER function get_occurance_index(#delimiter varchar(1),#occurence int,#String varchar(100))
returns int
AS Begin
--Declare #delimiter varchar(1)=',',#occurence int=2,#String varchar(100)='a,b,c'
Declare #result int
;with T as (
select 1 Rno,0 as row, charindex(#delimiter, #String) pos,#String st
union all
select Rno+1,pos + 1, charindex(#delimiter, #String, pos + 1), #String
from T
where pos > 0
)
select #result=pos
from T
where pos > 0 and rno = #occurence
return isnull(#result,0)
ENd
declare #data as table (data varchar(100))
insert into #data values('1,2,3')
insert into #data values('aaa,bbbbb,cccc')
select top 3 Substring (data,0,dbo.get_occurance_index( ',',1,data)) ,--First Record always starts with 0
Substring (data,dbo.get_occurance_index( ',',1,data)+1,dbo.get_occurance_index( ',',2,data)-dbo.get_occurance_index( ',',1,data)-1) ,
Substring (data,dbo.get_occurance_index( ',',2,data)+1,len(data)) , -- Last record cant be more than len of actual data
data
From #data
I found that using PARSENAME as above caused any name with a period to get nulled.
So if there was an initial or a title in the name followed by a dot they return NULL.
I found this worked for me:
SELECT
REPLACE(SUBSTRING(FullName, 1,CHARINDEX(',', FullName)), ',','') as Name,
REPLACE(SUBSTRING(FullName, CHARINDEX(',', FullName), LEN(FullName)), ',', '') as Surname
FROM Table1
it is so easy, you can take it by below query:
DECLARE #str NVARCHAR(MAX)='ControlID_05436b78-04ba-9667-fa01-9ff8c1b7c235,3'
SELECT LEFT(#str, CHARINDEX(',',#str)-1),RIGHT(#str,LEN(#str)-(CHARINDEX(',',#str)))
select distinct modelFileId,F4.*
from contract
cross apply (select XmlList=convert(xml, '<x>'+replace(modelFileId,';','</x><x>')+'</x>').query('.')) F2
cross apply (select mfid1=XmlNode.value('/x[1]','varchar(512)')
,mfid2=XmlNode.value('/x[2]','varchar(512)')
,mfid3=XmlNode.value('/x[3]','varchar(512)')
,mfid4=XmlNode.value('/x[4]','varchar(512)') from XmlList.nodes('x') F3(XmlNode)) F4
where modelFileId like '%;%'
order by modelFileId
Select distinct PROJ_UID,PROJ_NAME,RES_UID from E2E_ProjectWiseTimesheetActuals
where CHARINDEX(','+cast(PROJ_UID as varchar(8000))+',', #params) > 0 and CHARINDEX(','+cast(RES_UID as varchar(8000))+',', #res) > 0
I re-wrote an answer above and made it better:
CREATE FUNCTION [dbo].[CSVParser]
(
#s VARCHAR(255),
#idx NUMERIC
)
RETURNS VARCHAR(12)
BEGIN
DECLARE #comma int
SET #comma = CHARINDEX(',', #s)
WHILE 1=1
BEGIN
IF #comma=0
IF #idx=1
RETURN #s
ELSE
RETURN ''
IF #idx=1
BEGIN
DECLARE #word VARCHAR(12)
SET #word=LEFT(#s, #comma - 1)
RETURN #word
END
SET #s = RIGHT(#s,LEN(#s)-#comma)
SET #comma = CHARINDEX(',', #s)
SET #idx = #idx - 1
END
RETURN 'not used'
END
Example usage:
SELECT dbo.CSVParser(COLUMN, 1),
dbo.CSVParser(COLUMN, 2),
dbo.CSVParser(COLUMN, 3)
FROM TABLE
question is simple, but problem is hot :)
So I create some wrapper for string_split() which pivot result in more generic way. It's table function which returns values (nn, value1, value2, ... , value50) - enough for most CSV lines. If there are more values, they will wrap to next line - nn indicate line number. Set third parameter #columnCnt = [yourNumber] to wrap at specific position:
alter FUNCTION fn_Split50
(
#str varchar(max),
#delim char(1),
#columnCnt int = 50
)
RETURNS TABLE
AS
RETURN
(
SELECT *
FROM (SELECT
nn = (nn - 1) / #columnCnt + 1,
nnn = 'value' + cast(((nn - 1) % #columnCnt) + 1 as varchar(10)),
value
FROM (SELECT
nn = ROW_NUMBER() over (order by (select null)),
value
FROM string_split(#str, #delim) aa
) aa
where nn > 0
) bb
PIVOT
(
max(value)
FOR nnn IN (
value1, value2, value3, value4, value5, value6, value7, value8, value9, value10,
value11, value12, value13, value14, value15, value16, value17, value18, value19, value20,
value21, value22, value23, value24, value25, value26, value27, value28, value29, value30,
value31, value32, value33, value34, value35, value36, value37, value38, value39, value40,
value41, value42, value43, value44, value45, value46, value47, value48, value49, value50
)
) AS PivotTable
)
Example of using:
select * from dbo.fn_split50('zz1,aa2,ss3,dd4,ff5', ',', DEFAULT)
select * from dbo.fn_split50('zz1,aa2,ss3,dd4,ff5,gg6,hh7,jj8,ww9,qq10', ',', 3)
select * from dbo.fn_split50('zz1,11,aa2,22,ss3,33,dd4,44,ff5,55,gg6,66,hh7,77,jj8,88,ww9,99,qq10,1010', ',',2)
Hope, it will helps :)

Regular Expression to split a field into two [duplicate]

I have a table like this
Value String
-------------------
1 Cleo, Smith
I want to separate the comma delimited string into two columns
Value Name Surname
-------------------
1 Cleo Smith
I need only two fixed extra columns
Your purpose can be solved using following query -
Select Value , Substring(FullName, 1,Charindex(',', FullName)-1) as Name,
Substring(FullName, Charindex(',', FullName)+1, LEN(FullName)) as Surname
from Table1
There is no readymade Split function in sql server, so we need to create user defined function.
CREATE FUNCTION Split (
#InputString VARCHAR(8000),
#Delimiter VARCHAR(50)
)
RETURNS #Items TABLE (
Item VARCHAR(8000)
)
AS
BEGIN
IF #Delimiter = ' '
BEGIN
SET #Delimiter = ','
SET #InputString = REPLACE(#InputString, ' ', #Delimiter)
END
IF (#Delimiter IS NULL OR #Delimiter = '')
SET #Delimiter = ','
--INSERT INTO #Items VALUES (#Delimiter) -- Diagnostic
--INSERT INTO #Items VALUES (#InputString) -- Diagnostic
DECLARE #Item VARCHAR(8000)
DECLARE #ItemList VARCHAR(8000)
DECLARE #DelimIndex INT
SET #ItemList = #InputString
SET #DelimIndex = CHARINDEX(#Delimiter, #ItemList, 0)
WHILE (#DelimIndex != 0)
BEGIN
SET #Item = SUBSTRING(#ItemList, 0, #DelimIndex)
INSERT INTO #Items VALUES (#Item)
-- Set #ItemList = #ItemList minus one less item
SET #ItemList = SUBSTRING(#ItemList, #DelimIndex+1, LEN(#ItemList)-#DelimIndex)
SET #DelimIndex = CHARINDEX(#Delimiter, #ItemList, 0)
END -- End WHILE
IF #Item IS NOT NULL -- At least one delimiter was encountered in #InputString
BEGIN
SET #Item = #ItemList
INSERT INTO #Items VALUES (#Item)
END
-- No delimiters were encountered in #InputString, so just return #InputString
ELSE INSERT INTO #Items VALUES (#InputString)
RETURN
END -- End Function
GO
---- Set Permissions
--GRANT SELECT ON Split TO UserRole1
--GRANT SELECT ON Split TO UserRole2
--GO
;WITH Split_Names (Value,Name, xmlname)
AS
(
SELECT Value,
Name,
CONVERT(XML,'<Names><name>'
+ REPLACE(Name,',', '</name><name>') + '</name></Names>') AS xmlname
FROM tblnames
)
SELECT Value,
xmlname.value('/Names[1]/name[1]','varchar(100)') AS Name,
xmlname.value('/Names[1]/name[2]','varchar(100)') AS Surname
FROM Split_Names
and also check the link below for reference
http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html
xml based answer is simple and clean
refer this
DECLARE #S varchar(max),
#Split char(1),
#X xml
SELECT #S = 'ab,cd,ef,gh,ij',
#Split = ','
SELECT #X = CONVERT(xml,' <root> <myvalue>' +
REPLACE(#S,#Split,'</myvalue> <myvalue>') + '</myvalue> </root> ')
SELECT T.c.value('.','varchar(20)'), --retrieve ALL values at once
T.c.value('(/root/myvalue)[1]','VARCHAR(20)') , --retrieve index 1 only, which is the 'ab'
T.c.value('(/root/myvalue)[2]','VARCHAR(20)')
FROM #X.nodes('/root/myvalue') T(c)
I think this is cool
SELECT value,
PARSENAME(REPLACE(String,',','.'),2) 'Name' ,
PARSENAME(REPLACE(String,',','.'),1) 'Surname'
FROM table WITH (NOLOCK)
With CROSS APPLY
select ParsedData.*
from MyTable mt
cross apply ( select str = mt.String + ',,' ) f1
cross apply ( select p1 = charindex( ',', str ) ) ap1
cross apply ( select p2 = charindex( ',', str, p1 + 1 ) ) ap2
cross apply ( select Nmame = substring( str, 1, p1-1 )
, Surname = substring( str, p1+1, p2-p1-1 )
) ParsedData
There are multiple ways to solve this and many different ways have been proposed already. Simplest would be to use LEFT / SUBSTRING and other string functions to achieve the desired result.
Sample Data
DECLARE #tbl1 TABLE (Value INT,String VARCHAR(MAX))
INSERT INTO #tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO #tbl1 VALUES(2,'John, Mathew');
Using String Functions like LEFT
SELECT
Value,
LEFT(String,CHARINDEX(',',String)-1) as Fname,
LTRIM(RIGHT(String,LEN(String) - CHARINDEX(',',String) )) AS Lname
FROM #tbl1
This approach fails if there are more 2 items in a String.
In such a scenario, we can use a splitter and then use PIVOT or convert the string into an XML and use .nodes to get string items. XML based solution have been detailed out by aads and bvr in their solution.
The answers for this question which use splitter, all use WHILE which is inefficient for splitting. Check this performance comparison. One of the best splitters around is DelimitedSplit8K, created by Jeff Moden. You can read more about it here
Splitter with PIVOT
DECLARE #tbl1 TABLE (Value INT,String VARCHAR(MAX))
INSERT INTO #tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO #tbl1 VALUES(2,'John, Mathew');
SELECT t3.Value,[1] as Fname,[2] as Lname
FROM #tbl1 as t1
CROSS APPLY [dbo].[DelimitedSplit8K](String,',') as t2
PIVOT(MAX(Item) FOR ItemNumber IN ([1],[2])) as t3
Output
Value Fname Lname
1 Cleo Smith
2 John Mathew
DelimitedSplit8K by Jeff Moden
CREATE FUNCTION [dbo].[DelimitedSplit8K]
/**********************************************************************************************************************
Purpose:
Split a given string at a given delimiter and return a list of the split elements (items).
Notes:
1. Leading a trailing delimiters are treated as if an empty string element were present.
2. Consecutive delimiters are treated as if an empty string element were present between them.
3. Except when spaces are used as a delimiter, all spaces present in each element are preserved.
Returns:
iTVF containing the following:
ItemNumber = Element position of Item as a BIGINT (not converted to INT to eliminate a CAST)
Item = Element value as a VARCHAR(8000)
Statistics on this function may be found at the following URL:
http://www.sqlservercentral.com/Forums/Topic1101315-203-4.aspx
CROSS APPLY Usage Examples and Tests:
--=====================================================================================================================
-- TEST 1:
-- This tests for various possible conditions in a string using a comma as the delimiter. The expected results are
-- laid out in the comments
--=====================================================================================================================
--===== Conditionally drop the test tables to make reruns easier for testing.
-- (this is NOT a part of the solution)
IF OBJECT_ID('tempdb..#JBMTest') IS NOT NULL DROP TABLE #JBMTest
;
--===== Create and populate a test table on the fly (this is NOT a part of the solution).
-- In the following comments, "b" is a blank and "E" is an element in the left to right order.
-- Double Quotes are used to encapsulate the output of "Item" so that you can see that all blanks
-- are preserved no matter where they may appear.
SELECT *
INTO #JBMTest
FROM ( --# & type of Return Row(s)
SELECT 0, NULL UNION ALL --1 NULL
SELECT 1, SPACE(0) UNION ALL --1 b (Empty String)
SELECT 2, SPACE(1) UNION ALL --1 b (1 space)
SELECT 3, SPACE(5) UNION ALL --1 b (5 spaces)
SELECT 4, ',' UNION ALL --2 b b (both are empty strings)
SELECT 5, '55555' UNION ALL --1 E
SELECT 6, ',55555' UNION ALL --2 b E
SELECT 7, ',55555,' UNION ALL --3 b E b
SELECT 8, '55555,' UNION ALL --2 b B
SELECT 9, '55555,1' UNION ALL --2 E E
SELECT 10, '1,55555' UNION ALL --2 E E
SELECT 11, '55555,4444,333,22,1' UNION ALL --5 E E E E E
SELECT 12, '55555,4444,,333,22,1' UNION ALL --6 E E b E E E
SELECT 13, ',55555,4444,,333,22,1,' UNION ALL --8 b E E b E E E b
SELECT 14, ',55555,4444,,,333,22,1,' UNION ALL --9 b E E b b E E E b
SELECT 15, ' 4444,55555 ' UNION ALL --2 E (w/Leading Space) E (w/Trailing Space)
SELECT 16, 'This,is,a,test.' --E E E E
) d (SomeID, SomeValue)
;
--===== Split the CSV column for the whole table using CROSS APPLY (this is the solution)
SELECT test.SomeID, test.SomeValue, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
FROM #JBMTest test
CROSS APPLY dbo.DelimitedSplit8K(test.SomeValue,',') split
;
--=====================================================================================================================
-- TEST 2:
-- This tests for various "alpha" splits and COLLATION using all ASCII characters from 0 to 255 as a delimiter against
-- a given string. Note that not all of the delimiters will be visible and some will show up as tiny squares because
-- they are "control" characters. More specifically, this test will show you what happens to various non-accented
-- letters for your given collation depending on the delimiter you chose.
--=====================================================================================================================
WITH
cteBuildAllCharacters (String,Delimiter) AS
(
SELECT TOP 256
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
CHAR(ROW_NUMBER() OVER (ORDER BY (SELECT NULL))-1)
FROM master.sys.all_columns
)
SELECT ASCII_Value = ASCII(c.Delimiter), c.Delimiter, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
FROM cteBuildAllCharacters c
CROSS APPLY dbo.DelimitedSplit8K(c.String,c.Delimiter) split
ORDER BY ASCII_Value, split.ItemNumber
;
-----------------------------------------------------------------------------------------------------------------------
Other Notes:
1. Optimized for VARCHAR(8000) or less. No testing or error reporting for truncation at 8000 characters is done.
2. Optimized for single character delimiter. Multi-character delimiters should be resolvedexternally from this
function.
3. Optimized for use with CROSS APPLY.
4. Does not "trim" elements just in case leading or trailing blanks are intended.
5. If you don't know how a Tally table can be used to replace loops, please see the following...
http://www.sqlservercentral.com/articles/T-SQL/62867/
6. Changing this function to use NVARCHAR(MAX) will cause it to run twice as slow. It's just the nature of
VARCHAR(MAX) whether it fits in-row or not.
7. Multi-machine testing for the method of using UNPIVOT instead of 10 SELECT/UNION ALLs shows that the UNPIVOT method
is quite machine dependent and can slow things down quite a bit.
-----------------------------------------------------------------------------------------------------------------------
Credits:
This code is the product of many people's efforts including but not limited to the following:
cteTally concept originally by Iztek Ben Gan and "decimalized" by Lynn Pettis (and others) for a bit of extra speed
and finally redacted by Jeff Moden for a different slant on readability and compactness. Hat's off to Paul White for
his simple explanations of CROSS APPLY and for his detailed testing efforts. Last but not least, thanks to
Ron "BitBucket" McCullough and Wayne Sheffield for their extreme performance testing across multiple machines and
versions of SQL Server. The latest improvement brought an additional 15-20% improvement over Rev 05. Special thanks
to "Nadrek" and "peter-757102" (aka Peter de Heer) for bringing such improvements to light. Nadrek's original
improvement brought about a 10% performance gain and Peter followed that up with the content of Rev 07.
I also thank whoever wrote the first article I ever saw on "numbers tables" which is located at the following URL
and to Adam Machanic for leading me to it many years ago.
http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html
-----------------------------------------------------------------------------------------------------------------------
Revision History:
Rev 00 - 20 Jan 2010 - Concept for inline cteTally: Lynn Pettis and others.
Redaction/Implementation: Jeff Moden
- Base 10 redaction and reduction for CTE. (Total rewrite)
Rev 01 - 13 Mar 2010 - Jeff Moden
- Removed one additional concatenation and one subtraction from the SUBSTRING in the SELECT List for that tiny
bit of extra speed.
Rev 02 - 14 Apr 2010 - Jeff Moden
- No code changes. Added CROSS APPLY usage example to the header, some additional credits, and extra
documentation.
Rev 03 - 18 Apr 2010 - Jeff Moden
- No code changes. Added notes 7, 8, and 9 about certain "optimizations" that don't actually work for this
type of function.
Rev 04 - 29 Jun 2010 - Jeff Moden
- Added WITH SCHEMABINDING thanks to a note by Paul White. This prevents an unnecessary "Table Spool" when the
function is used in an UPDATE statement even though the function makes no external references.
Rev 05 - 02 Apr 2011 - Jeff Moden
- Rewritten for extreme performance improvement especially for larger strings approaching the 8K boundary and
for strings that have wider elements. The redaction of this code involved removing ALL concatenation of
delimiters, optimization of the maximum "N" value by using TOP instead of including it in the WHERE clause,
and the reduction of all previous calculations (thanks to the switch to a "zero based" cteTally) to just one
instance of one add and one instance of a subtract. The length calculation for the final element (not
followed by a delimiter) in the string to be split has been greatly simplified by using the ISNULL/NULLIF
combination to determine when the CHARINDEX returned a 0 which indicates there are no more delimiters to be
had or to start with. Depending on the width of the elements, this code is between 4 and 8 times faster on a
single CPU box than the original code especially near the 8K boundary.
- Modified comments to include more sanity checks on the usage example, etc.
- Removed "other" notes 8 and 9 as they were no longer applicable.
Rev 06 - 12 Apr 2011 - Jeff Moden
- Based on a suggestion by Ron "Bitbucket" McCullough, additional test rows were added to the sample code and
the code was changed to encapsulate the output in pipes so that spaces and empty strings could be perceived
in the output. The first "Notes" section was added. Finally, an extra test was added to the comments above.
Rev 07 - 06 May 2011 - Peter de Heer, a further 15-20% performance enhancement has been discovered and incorporated
into this code which also eliminated the need for a "zero" position in the cteTally table.
**********************************************************************************************************************/
--===== Define I/O parameters
(#pString VARCHAR(8000), #pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
-- enough to cover NVARCHAR(4000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(#pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(#pString,t.N,1) = #pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(#pDelimiter,#pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(#pString, l.N1, l.L1)
FROM cteLen l
;
GO
With SQL Server 2016 we can use string_split to accomplish this:
create table commasep (
id int identity(1,1)
,string nvarchar(100) )
insert into commasep (string) values ('John, Adam'), ('test1,test2,test3')
select id, [value] as String from commasep
cross apply string_split(string,',')
CREATE FUNCTION [dbo].[fn_split_string_to_column] (
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #out_put TABLE (
[column_id] INT IDENTITY(1, 1) NOT NULL,
[value] NVARCHAR(MAX)
)
AS
BEGIN
DECLARE #value NVARCHAR(MAX),
#pos INT = 0,
#len INT = 0
SET #string = CASE
WHEN RIGHT(#string, 1) != #delimiter
THEN #string + #delimiter
ELSE #string
END
WHILE CHARINDEX(#delimiter, #string, #pos + 1) > 0
BEGIN
SET #len = CHARINDEX(#delimiter, #string, #pos + 1) - #pos
SET #value = SUBSTRING(#string, #pos, #len)
INSERT INTO #out_put ([value])
SELECT LTRIM(RTRIM(#value)) AS [column]
SET #pos = CHARINDEX(#delimiter, #string, #pos + #len) + 1
END
RETURN
END
SELECT id,
Substring(NAME, 0, Charindex(',', NAME)) AS firstname,
Substring(NAME, Charindex(',', NAME), Len(NAME) + 1) AS lastname
FROM spilt
Try this (change instances of ' ' to ',' or whatever delimiter you want to use)
CREATE FUNCTION dbo.Wordparser
(
#multiwordstring VARCHAR(255),
#wordnumber NUMERIC
)
returns VARCHAR(255)
AS
BEGIN
DECLARE #remainingstring VARCHAR(255)
SET #remainingstring=#multiwordstring
DECLARE #numberofwords NUMERIC
SET #numberofwords=(LEN(#remainingstring) - LEN(REPLACE(#remainingstring, ' ', '')) + 1)
DECLARE #word VARCHAR(50)
DECLARE #parsedwords TABLE
(
line NUMERIC IDENTITY(1, 1),
word VARCHAR(255)
)
WHILE #numberofwords > 1
BEGIN
SET #word=LEFT(#remainingstring, CHARINDEX(' ', #remainingstring) - 1)
INSERT INTO #parsedwords(word)
SELECT #word
SET #remainingstring= REPLACE(#remainingstring, Concat(#word, ' '), '')
SET #numberofwords=(LEN(#remainingstring) - LEN(REPLACE(#remainingstring, ' ', '')) + 1)
IF #numberofwords = 1
BREAK
ELSE
CONTINUE
END
IF #numberofwords = 1
SELECT #word = #remainingstring
INSERT INTO #parsedwords(word)
SELECT #word
RETURN
(SELECT word
FROM #parsedwords
WHERE line = #wordnumber)
END
Example usage:
SELECT dbo.Wordparser(COLUMN, 1),
dbo.Wordparser(COLUMN, 2),
dbo.Wordparser(COLUMN, 3)
FROM TABLE
I think PARSENAME is the neat function to use for this example, as described in this article: http://www.sqlshack.com/parsing-and-rotating-delimited-data-in-sql-server-2012/
The PARSENAME function is logically designed to parse four-part object names. The nice thing about PARSENAME is that it’s not limited to parsing just SQL Server four-part object names – it will parse any function or string data that is delimited by dots.
The first parameter is the object to parse, and the second is the integer value of the object piece to return. The article is discussing parsing and rotating delimited data - company phone numbers, but it can be used to parse name/surname data also.
Example:
USE COMPANY;
SELECT PARSENAME('Whatever.you.want.parsed',3) AS 'ReturnValue';
The article also describes using a Common Table Expression (CTE) called ‘replaceChars’, to run PARSENAME against the delimiter-replaced values. A CTE is useful for returning a temporary view or result set.
After that, the UNPIVOT function has been used to convert some columns into rows; SUBSTRING and CHARINDEX functions have been used for cleaning up the inconsistencies in the data, and the LAG function (new for SQL Server 2012) has been used in the end, as it allows referencing of previous records.
We can create a function as this
CREATE Function [dbo].[fn_CSVToTable]
(
#CSVList Varchar(max)
)
RETURNS #Table TABLE (ColumnData VARCHAR(100))
AS
BEGIN
IF RIGHT(#CSVList, 1) <> ','
SELECT #CSVList = #CSVList + ','
DECLARE #Pos BIGINT,
#OldPos BIGINT
SELECT #Pos = 1,
#OldPos = 1
WHILE #Pos < LEN(#CSVList)
BEGIN
SELECT #Pos = CHARINDEX(',', #CSVList, #OldPos)
INSERT INTO #Table
SELECT LTRIM(RTRIM(SUBSTRING(#CSVList, #OldPos, #Pos - #OldPos))) Col001
SELECT #OldPos = #Pos + 1
END
RETURN
END
We can then seperate the CSV values into our respective columns using a SELECT statement
You can use a table-valued function STRING_SPLIT, which is available only under compatibility level 130. If your database compatibility level is lower than 130, SQL Server will not be able to find and execute the STRING_SPLIT function. You can change a compatibility level of the database using the following command:
ALTER DATABASE DatabaseName SET COMPATIBILITY_LEVEL = 130
Syntax
SELECT * FROM STRING_SPLIT ( string, separator )
see documentation here
I think following function will work for you:
You have to create a function in SQL first. Like this
CREATE FUNCTION [dbo].[fn_split](
#str VARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #returnTable TABLE (idx INT PRIMARY KEY IDENTITY, item VARCHAR(8000))
AS
BEGIN
DECLARE #pos INT
SELECT #str = #str + #delimiter
WHILE LEN(#str) > 0
BEGIN
SELECT #pos = CHARINDEX(#delimiter,#str)
IF #pos = 1
INSERT #returnTable (item)
VALUES (NULL)
ELSE
INSERT #returnTable (item)
VALUES (SUBSTRING(#str, 1, #pos-1))
SELECT #str = SUBSTRING(#str, #pos+1, LEN(#str)-#pos)
END
RETURN
END
You can call this function, like this:
select * from fn_split('1,24,5',',')
Implementation:
Declare #test TABLE (
ID VARCHAR(200),
Data VARCHAR(200)
)
insert into #test
(ID, Data)
Values
('1','Cleo,Smith')
insert into #test
(ID, Data)
Values
('2','Paul,Grim')
select ID,
(select item from fn_split(Data,',') where idx in (1)) as Name ,
(select item from fn_split(Data,',') where idx in (2)) as Surname
from #test
Result will like this:
Use Parsename() function
with cte as(
select 'Aria,Karimi' as FullName
Union
select 'Joe,Karimi' as FullName
Union
select 'Bab,Karimi' as FullName
)
SELECT PARSENAME(REPLACE(FullName,',','.'),2) as Name,
PARSENAME(REPLACE(FullName,',','.'),1) as Family
FROM cte
Result
Name Family
----- ------
Aria Karimi
Bab Karimi
Joe Karimi
Try this:
declare #csv varchar(100) ='aaa,bb,csda,daass';
set #csv = #csv+',';
with cte as
(
select SUBSTRING(#csv,1,charindex(',',#csv,1)-1) as val, SUBSTRING(#csv,charindex(',',#csv,1)+1,len(#csv)) as rem
UNION ALL
select SUBSTRING(a.rem,1,charindex(',',a.rem,1)-1)as val, SUBSTRING(a.rem,charindex(',',a.rem,1)+1,len(A.rem))
from cte a where LEN(a.rem)>=1
) select val from cte
This function is most fast:
CREATE FUNCTION dbo.F_ExtractSubString
(
#String VARCHAR(MAX),
#NroSubString INT,
#Separator VARCHAR(5)
)
RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE #St INT = 0, #End INT = 0, #Ret VARCHAR(MAX)
SET #String = #String + #Separator
WHILE CHARINDEX(#Separator, #String, #End + 1) > 0 AND #NroSubString > 0
BEGIN
SET #St = #End + 1
SET #End = CHARINDEX(#Separator, #String, #End + 1)
SET #NroSubString = #NroSubString - 1
END
IF #NroSubString > 0
SET #Ret = ''
ELSE
SET #Ret = SUBSTRING(#String, #St, #End - #St)
RETURN #Ret
END
GO
Example usage:
SELECT dbo.F_ExtractSubString(COLUMN, 1, ', '),
dbo.F_ExtractSubString(COLUMN, 2, ', '),
dbo.F_ExtractSubString(COLUMN, 3, ', ')
FROM TABLE
I encountered a similar problem but a complex one and since this is the first thread i found regarding that issue i decided to post my finding. i know it is complex solution to a simple problem but i hope that i could help other people who go to this thread looking for a more complex solution. i had to split a string containing 5 numbers (column name: levelsFeed) and to show each number in a separate column.
for example: 8,1,2,2,2
should be shown as :
1 2 3 4 5
-------------
8 1 2 2 2
Solution 1: using XML functions:
this solution for the slowest solution by far
SELECT Distinct FeedbackID,
, S.a.value('(/H/r)[1]', 'INT') AS level1
, S.a.value('(/H/r)[2]', 'INT') AS level2
, S.a.value('(/H/r)[3]', 'INT') AS level3
, S.a.value('(/H/r)[4]', 'INT') AS level4
, S.a.value('(/H/r)[5]', 'INT') AS level5
FROM (
SELECT *,CAST (N'<H><r>' + REPLACE(levelsFeed, ',', '</r><r>') + '</r> </H>' AS XML) AS [vals]
FROM Feedbacks
) as d
CROSS APPLY d.[vals].nodes('/H/r') S(a)
Solution 2: using Split function and pivot. (the split function split a string to rows with the column name Data)
SELECT FeedbackID, [1],[2],[3],[4],[5]
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY feedbackID ORDER BY (SELECT null)) as rn
FROM (
SELECT FeedbackID, levelsFeed
FROM Feedbacks
) as a
CROSS APPLY dbo.Split(levelsFeed, ',')
) as SourceTable
PIVOT
(
MAX(data)
FOR rn IN ([1],[2],[3],[4],[5])
)as pivotTable
Solution 3: using string manipulations functions - fastest by small margin over solution 2
SELECT FeedbackID,
SUBSTRING(levelsFeed,0,CHARINDEX(',',levelsFeed)) AS level1,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),4) AS level2,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),3) AS level3,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),2) AS level4,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),1) AS level5
FROM Feedbacks
since the levelsFeed contains 5 string values i needed to use the substring function for the first string.
i hope that my solution will help other that got to this thread looking for a more complex split to columns methods
Using instring function :)
select Value,
substring(String,1,instr(String," ") -1) Fname,
substring(String,instr(String,",") +1) Sname
from tablename;
Used two functions,
1. substring(string, position, length) ==> returns string from positon to length
2. instr(string,pattern) ==> returns position of pattern.
If we don’t provide length argument in substring it returns until end of string
This worked for me
CREATE FUNCTION [dbo].[SplitString](
#delimited NVARCHAR(MAX),
#delimiter NVARCHAR(100)
) RETURNS #t TABLE ( val NVARCHAR(MAX))
AS
BEGIN
DECLARE #xml XML
SET #xml = N'<t>' + REPLACE(#delimited,#delimiter,'</t><t>') + '</t>'
INSERT INTO #t(val)
SELECT r.value('.','varchar(MAX)') as item
FROM #xml.nodes('/t') as records(r)
RETURN
END
mytable:
Value ColOne
--------------------
1 Cleo, Smith
The following should work if there aren't too many columns
ALTER TABLE mytable ADD ColTwo nvarchar(256);
UPDATE mytable SET ColTwo = LEFT(ColOne, Charindex(',', ColOne) - 1);
--'Cleo' = LEFT('Cleo, Smith', Charindex(',', 'Cleo, Smith') - 1)
UPDATE mytable SET ColTwo = REPLACE(ColOne, ColTwo + ',', '');
--' Smith' = REPLACE('Cleo, Smith', 'Cleo' + ',')
UPDATE mytable SET ColOne = REPLACE(ColOne, ',' + ColTwo, ''), ColTwo = LTRIM(ColTwo);
--'Cleo' = REPLACE('Cleo, Smith', ',' + ' Smith', '')
Result:
Value ColOne ColTwo
--------------------
1 Cleo Smith
DECLARE #INPUT VARCHAR (MAX)='N,A,R,E,N,D,R,A'
DECLARE #ELIMINATE_CHAR CHAR (1)=','
DECLARE #L_START INT=1
DECLARE #L_END INT=(SELECT LEN (#INPUT))
DECLARE #OUTPUT CHAR (1)
WHILE #L_START <=#L_END
BEGIN
SET #OUTPUT=(SUBSTRING (#INPUT,#L_START,1))
IF #OUTPUT!=#ELIMINATE_CHAR
BEGIN
PRINT #OUTPUT
END
SET #L_START=#L_START+1
END
You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project).
This is the code part from this page:
CREATE FUNCTION [fn_ParseText2Table]
(#p_SourceText VARCHAR(MAX)
,#p_Delimeter VARCHAR(100)=',' --default to comma delimited.
)
RETURNS #retTable
TABLE([Position] INT IDENTITY(1,1)
,[Int_Value] INT
,[Num_Value] NUMERIC(18,3)
,[Txt_Value] VARCHAR(MAX)
,[Date_value] DATETIME
)
AS
/*
********************************************************************************
Purpose: Parse values from a delimited string
& return the result as an indexed table
Copyright 1996, 1997, 2000, 2003 Clayton Groom (Clayton_Groom#hotmail.com)
Posted to the public domain Aug, 2004
2003-06-17 Rewritten as SQL 2000 function.
Reworked to allow for delimiters > 1 character in length
and to convert Text values to numbers
2016-04-05 Added logic for date values based on "new" ISDATE() function, Updated to use XML approach, which is more efficient.
********************************************************************************
*/
BEGIN
DECLARE #w_xml xml;
SET #w_xml = N'<root><i>' + replace(#p_SourceText, #p_Delimeter,'</i><i>') + '</i></root>';
INSERT INTO #retTable
([Int_Value]
, [Num_Value]
, [Txt_Value]
, [Date_value]
)
SELECT CASE
WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST(CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC) AS INT)
END AS [Int_Value]
, CASE
WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC(18, 3))
END AS [Num_Value]
, [i].value('.', 'VARCHAR(MAX)') AS [txt_Value]
, CASE
WHEN ISDATE([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST([i].value('.', 'VARCHAR(MAX)') AS DATETIME)
END AS [Num_Value]
FROM #w_xml.nodes('//root/i') AS [Items]([i]);
RETURN;
END;
GO
ALTER function get_occurance_index(#delimiter varchar(1),#occurence int,#String varchar(100))
returns int
AS Begin
--Declare #delimiter varchar(1)=',',#occurence int=2,#String varchar(100)='a,b,c'
Declare #result int
;with T as (
select 1 Rno,0 as row, charindex(#delimiter, #String) pos,#String st
union all
select Rno+1,pos + 1, charindex(#delimiter, #String, pos + 1), #String
from T
where pos > 0
)
select #result=pos
from T
where pos > 0 and rno = #occurence
return isnull(#result,0)
ENd
declare #data as table (data varchar(100))
insert into #data values('1,2,3')
insert into #data values('aaa,bbbbb,cccc')
select top 3 Substring (data,0,dbo.get_occurance_index( ',',1,data)) ,--First Record always starts with 0
Substring (data,dbo.get_occurance_index( ',',1,data)+1,dbo.get_occurance_index( ',',2,data)-dbo.get_occurance_index( ',',1,data)-1) ,
Substring (data,dbo.get_occurance_index( ',',2,data)+1,len(data)) , -- Last record cant be more than len of actual data
data
From #data
I found that using PARSENAME as above caused any name with a period to get nulled.
So if there was an initial or a title in the name followed by a dot they return NULL.
I found this worked for me:
SELECT
REPLACE(SUBSTRING(FullName, 1,CHARINDEX(',', FullName)), ',','') as Name,
REPLACE(SUBSTRING(FullName, CHARINDEX(',', FullName), LEN(FullName)), ',', '') as Surname
FROM Table1
it is so easy, you can take it by below query:
DECLARE #str NVARCHAR(MAX)='ControlID_05436b78-04ba-9667-fa01-9ff8c1b7c235,3'
SELECT LEFT(#str, CHARINDEX(',',#str)-1),RIGHT(#str,LEN(#str)-(CHARINDEX(',',#str)))
select distinct modelFileId,F4.*
from contract
cross apply (select XmlList=convert(xml, '<x>'+replace(modelFileId,';','</x><x>')+'</x>').query('.')) F2
cross apply (select mfid1=XmlNode.value('/x[1]','varchar(512)')
,mfid2=XmlNode.value('/x[2]','varchar(512)')
,mfid3=XmlNode.value('/x[3]','varchar(512)')
,mfid4=XmlNode.value('/x[4]','varchar(512)') from XmlList.nodes('x') F3(XmlNode)) F4
where modelFileId like '%;%'
order by modelFileId
Select distinct PROJ_UID,PROJ_NAME,RES_UID from E2E_ProjectWiseTimesheetActuals
where CHARINDEX(','+cast(PROJ_UID as varchar(8000))+',', #params) > 0 and CHARINDEX(','+cast(RES_UID as varchar(8000))+',', #res) > 0
I re-wrote an answer above and made it better:
CREATE FUNCTION [dbo].[CSVParser]
(
#s VARCHAR(255),
#idx NUMERIC
)
RETURNS VARCHAR(12)
BEGIN
DECLARE #comma int
SET #comma = CHARINDEX(',', #s)
WHILE 1=1
BEGIN
IF #comma=0
IF #idx=1
RETURN #s
ELSE
RETURN ''
IF #idx=1
BEGIN
DECLARE #word VARCHAR(12)
SET #word=LEFT(#s, #comma - 1)
RETURN #word
END
SET #s = RIGHT(#s,LEN(#s)-#comma)
SET #comma = CHARINDEX(',', #s)
SET #idx = #idx - 1
END
RETURN 'not used'
END
Example usage:
SELECT dbo.CSVParser(COLUMN, 1),
dbo.CSVParser(COLUMN, 2),
dbo.CSVParser(COLUMN, 3)
FROM TABLE
question is simple, but problem is hot :)
So I create some wrapper for string_split() which pivot result in more generic way. It's table function which returns values (nn, value1, value2, ... , value50) - enough for most CSV lines. If there are more values, they will wrap to next line - nn indicate line number. Set third parameter #columnCnt = [yourNumber] to wrap at specific position:
alter FUNCTION fn_Split50
(
#str varchar(max),
#delim char(1),
#columnCnt int = 50
)
RETURNS TABLE
AS
RETURN
(
SELECT *
FROM (SELECT
nn = (nn - 1) / #columnCnt + 1,
nnn = 'value' + cast(((nn - 1) % #columnCnt) + 1 as varchar(10)),
value
FROM (SELECT
nn = ROW_NUMBER() over (order by (select null)),
value
FROM string_split(#str, #delim) aa
) aa
where nn > 0
) bb
PIVOT
(
max(value)
FOR nnn IN (
value1, value2, value3, value4, value5, value6, value7, value8, value9, value10,
value11, value12, value13, value14, value15, value16, value17, value18, value19, value20,
value21, value22, value23, value24, value25, value26, value27, value28, value29, value30,
value31, value32, value33, value34, value35, value36, value37, value38, value39, value40,
value41, value42, value43, value44, value45, value46, value47, value48, value49, value50
)
) AS PivotTable
)
Example of using:
select * from dbo.fn_split50('zz1,aa2,ss3,dd4,ff5', ',', DEFAULT)
select * from dbo.fn_split50('zz1,aa2,ss3,dd4,ff5,gg6,hh7,jj8,ww9,qq10', ',', 3)
select * from dbo.fn_split50('zz1,11,aa2,22,ss3,33,dd4,44,ff5,55,gg6,66,hh7,77,jj8,88,ww9,99,qq10,1010', ',',2)
Hope, it will helps :)

Replace with wildcard, in SQL

I know MS T-SQL does not support regular expression, but I need similar functionality. Here's what I'm trying to do:
I have a varchar table field which stores a breadcrumb, like this:
/ID1:Category1/ID2:Category2/ID3:Category3/
Each Category name is preceded by its Category ID, separated by a colon. I'd like to select and display these breadcrumbs but I want to remove the Category IDs and colons, like this:
/Category1/Category2/Category3/
Everything between the leading slash (/) up to and including the colon (:) should be stripped out.
I don't have the option of extracting the data, manipulating it externally, and re-inserting back into the table; so I'm trying to accomplish this in a SELECT statement.
I also can't resort to using a cursor to loop through each row and clean each field with a nested loop, due to the number of rows returned in the SELECT.
Can this be done?
Thanks all - Jay
I think your best bet is going to be to use a recursive user-defined function (UDF). I've included some code here that you can use to pass in a string to achieve the results you're looking for.
CREATE FUNCTION ufn_StripIDsFromBreadcrumb (#cIndex int, #breadcrumb varchar(max), #theString varchar(max))
RETURNS varchar(max)
AS
BEGIN
DECLARE #nextColon int
DECLARE #nextSlash int
SET #nextColon = CHARINDEX(':', #theString, #cIndex)
SET #nextSlash = CHARINDEX('/', #theString, #nextColon)
SET #breadcrumb = #breadcrumb + SUBSTRING(#theString, #nextColon + 1, #nextSlash - #nextColon)
IF #nextSlash != LEN(#theString)
BEGIN
exec #breadcrumb = ufn_StripIDsFromBreadcrumb #cIndex = #nextSlash, #breadcrumb = #breadcrumb, #theString = #theString
END
RETURN #breadcrumb
END
You could then execute it with:
DECLARE #myString varchar(max)
EXEC #myString = ufn_StripIDsFromBreadcrumb 1, '/', '/ID1:Category1/ID2:Category2/ID3:Category3/'
PRINT #myString
This works for SQL Server 2005 and up.
create table strings (
string varchar(1000)
)
insert into strings values( '/ID1:Category1/ID2:Category2/ID3:Category3/' )
insert into strings values( '/ID4:Category4/ID5:Category5/ID8:Category6/' )
insert into strings values( '/ID7:Category7/ID8:Category8/ID9:Category9/' )
go
with
replace_with_wildcard ( restrung ) as
(
select replace( string, '', '' )
from strings
union all
select
replace( restrung, substring( restrung, patindex( '%ID%', restrung ), 4 ), '' )
from replace_with_wildcard
where patindex( '%ID%', restrung ) > 0
)
select restrung
from replace_with_wildcard
where charindex( ':', restrung ) = 0
order by restrung
drop table strings
You might be able to do this using a Split function. The following split function relies on the existence of a Numbers table which literally contains a sequential list of numbers like so:
Create Table dbo.Numbers( Value int not null primary key clustered )
GO
With Nums As
(
Select ROW_NUMBER() OVER( Order By o.object_id ) As Num
From sys.objects as o
cross join sys.objects as o2
)
Insert dbo.Numbers( Value )
Select Num
From Nums
Where Num Between 1 And 10000
GO
Create Function [dbo].[udf_Split] (#DelimitedList nvarchar(max), #Delimiter nvarchar(2) = ',')
Returns #SplitResults TABLE (Position int NOT NULL PRIMARY KEY, Value nvarchar(max))
AS
/*
PURPOSE: to split the #DelimitedList based on the #Delimter
DESIGN NOTES:
1. In general the contents of the next item is: NextDelimiterPosition - CurrentStartPosition
2. CurrentStartPosition =
CharIndex(#Delimiter, A.list, N.Value) = Current Delimiter position
+ Len(#Delimiter) + The number of delimiter characters
+ 1 + 1 since the text of the item starts after the delimiter
3. We need to calculate the delimiter length because the LEN function excludes trailing spaces. Thus
if a delimiter of ", " (a comma followed by a space) is used, the LEN function will return 1.
4. The DataLength function returns the number of bytes in the string. However, since we're using
an nvarchar for the delimiter, the number of bytes will double the number of characters.
*/
Begin
Declare #DelimiterLength int
Set #DelimiterLength = DataLength(#Delimiter) / 2
If Left(#DelimitedList, #DelimiterLength) <> #Delimiter
Set #DelimitedList = #Delimiter + #DelimitedList
If Right(#DelimitedList, #DelimiterLength) <> #Delimiter
Set #DelimitedList = #DelimitedList + #Delimiter
Insert #SplitResults(Position, Value)
Select CharIndex(#Delimiter, A.list, N.Value) + #DelimiterLength
, Substring (
A.List
, CharIndex(#Delimiter, A.list, N.Value) + #DelimiterLength
, CharIndex(#Delimiter, A.list, N.Value + 1)
- ( CharIndex(#Delimiter, A.list, N.Value) + #DelimiterLength )
)
From dbo.Numbers As N
Cross Join (Select #DelimitedList As list) As A
Where N.Value > 0
And N.Value < LEN(A.list)
And Substring(A.list, N.Value, #DelimiterLength) = #Delimiter
Order By N.Value
Return
End
You then might be able to run a query like so where you strip out the prefixes:
Select Table, Substring(S.Value, CharIndex(':', S.Value) + 1, Len(S.Value))
From Table
Cross Apply dbo.udf_Split(Table.ListColumn, '/') As S
This would give you values like:
Category1
Category2
Category3
You could then use FOR XML PATH to combine them again:
Select Table.PK
, Stuff( (
Select '/' + Substring(S.Value, CharIndex(':', S.Value) + 1, Len(S.Value))
From Table As Table1
Cross Apply dbo.udf_Split(Table.ListColumn, '/') As S1
Where Table1.PK = Table.PK
Order By S1.Position
For Xml Path('')
), 1, 1, '') As BreadCrumb
From Table
For SQL Server 2005+, you can get regex support by:
Enabling CLR (doesn't require instance restart)
Uploading your CLR functionality (in this case, regex replace)
Using native TSQL, you'll need to define REPLACE statements for everything you want to remove:
SELECT REPLACE(
REPLACE(
REPLACE(''/ID1:Category1/ID2:Category2/ID3:Category3/'', 'ID1:', ''),
'ID2:', ''),
'ID3:', '')
Regex or otherwise, you need to be sure these patterns don't appear in the actual data.
You can use SQL CLR. Here's an MSDN article:
declare #test1 nvarchar(max)
set #test1='/ID1:Category1/ID2:Category2/ID3:Category3/'
while(CHARINDEX('ID',#test1)<>0)
Begin
select #test1=REPLACE(#test1,SUBSTRING(#test1,CHARINDEX('ID',#test1),CHARINDEX(':',#test1)-
CHARINDEX('ID',#test1)+1),'')
End
select #test1

How do I split a delimited string so I can access individual items?

Using SQL Server, how do I split a string so I can access item x?
Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?
I don't believe SQL Server has a built-in split function, so other than a UDF, the only other answer I know is to hijack the PARSENAME function:
SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 2)
PARSENAME takes a string and splits it on the period character. It takes a number as its second argument, and that number specifies which segment of the string to return (working from back to front).
SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 3) --return Hello
Obvious problem is when the string already contains a period. I still think using a UDF is the best way...any other suggestions?
You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project).
You can use this simple logic:
Declare #products varchar(200) = '1|20|3|343|44|6|8765'
Declare #individual varchar(20) = null
WHILE LEN(#products) > 0
BEGIN
IF PATINDEX('%|%', #products) > 0
BEGIN
SET #individual = SUBSTRING(#products,
0,
PATINDEX('%|%', #products))
SELECT #individual
SET #products = SUBSTRING(#products,
LEN(#individual + '|') + 1,
LEN(#products))
END
ELSE
BEGIN
SET #individual = #products
SET #products = NULL
SELECT #individual
END
END
First, create a function (using CTE, common table expression does away with the need for a temp table)
create function dbo.SplitString
(
#str nvarchar(4000),
#separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
1,
1,
charindex(#separator, #str)
union all
select
p + 1,
b + 1,
charindex(#separator, #str, b + 1)
from tokens
where b > 0
)
select
p-1 zeroBasedOccurance,
substring(
#str,
a,
case when b > 0 then b-a ELSE 4000 end)
AS s
from tokens
)
GO
Then, use it as any table (or modify it to fit within your existing stored proc) like this.
select s
from dbo.SplitString('Hello John Smith', ' ')
where zeroBasedOccurance=1
Update
Previous version would fail for input string longer than 4000 chars. This version takes care of the limitation:
create function dbo.SplitString
(
#str nvarchar(max),
#separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
cast(1 as bigint),
cast(1 as bigint),
charindex(#separator, #str)
union all
select
p + 1,
b + 1,
charindex(#separator, #str, b + 1)
from tokens
where b > 0
)
select
p-1 ItemIndex,
substring(
#str,
a,
case when b > 0 then b-a ELSE LEN(#str) end)
AS s
from tokens
);
GO
Usage remains the same.
Most of the solutions here use while loops or recursive CTEs. A set-based approach will be superior, I promise, if you can use a delimiter other than a space:
CREATE FUNCTION [dbo].[SplitString]
(
#List NVARCHAR(MAX),
#Delim VARCHAR(255)
)
RETURNS TABLE
AS
RETURN ( SELECT [Value], idx = RANK() OVER (ORDER BY n) FROM
(
SELECT n = Number,
[Value] = LTRIM(RTRIM(SUBSTRING(#List, [Number],
CHARINDEX(#Delim, #List + #Delim, [Number]) - [Number])))
FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
FROM sys.all_objects) AS x
WHERE Number <= LEN(#List)
AND SUBSTRING(#Delim + #List, [Number], LEN(#Delim)) = #Delim
) AS y
);
Sample usage:
SELECT Value FROM dbo.SplitString('foo,bar,blat,foo,splunge',',')
WHERE idx = 3;
Results:
----
blat
You could also add the idx you want as an argument to the function, but I'll leave that as an exercise to the reader.
You can't do this with just the native STRING_SPLIT function added in SQL Server 2016, because there is no guarantee that the output will be rendered in the order of the original list. In other words, if you pass in 3,6,1 the result will likely be in that order, but it could be 1,3,6. I have asked for the community's help in improving the built-in function here:
Please help with STRING_SPLIT improvements
With enough qualitative feedback, they may actually consider making some of these enhancements:
STRING_SPLIT is not feature complete
More on split functions, why (and proof that) while loops and recursive CTEs don't scale, and better alternatives, if splitting strings coming from the application layer:
Split strings the right way – or the next best way
Splitting Strings : A Follow-Up
Splitting Strings : Now with less T-SQL
Comparing string splitting / concatenation methods
Processing a list of integers : my approach
Splitting a list of integers : another roundup
More on splitting lists : custom delimiters, preventing duplicates, and maintaining order
Removing Duplicates from Strings in SQL Server
On SQL Server 2016 or above, though, you should look at STRING_SPLIT() and STRING_AGG():
Performance Surprises and Assumptions : STRING_SPLIT()
STRING_SPLIT() in SQL Server 2016 : Follow-Up #1
STRING_SPLIT() in SQL Server 2016 : Follow-Up #2
SQL Server v.Next : STRING_AGG() performance
Solve old problems with SQL Server’s new STRING_AGG and STRING_SPLIT functions
You can leverage a Number table to do the string parsing.
Create a physical numbers table:
create table dbo.Numbers (N int primary key);
insert into dbo.Numbers
select top 1000 row_number() over(order by number) from master..spt_values
go
Create test table with 1000000 rows
create table #yak (i int identity(1,1) primary key, array varchar(50))
insert into #yak(array)
select 'a,b,c' from dbo.Numbers n cross join dbo.Numbers nn
go
Create the function
create function [dbo].[ufn_ParseArray]
( #Input nvarchar(4000),
#Delimiter char(1) = ',',
#BaseIdent int
)
returns table as
return
( select row_number() over (order by n asc) + (#BaseIdent - 1) [i],
substring(#Input, n, charindex(#Delimiter, #Input + #Delimiter, n) - n) s
from dbo.Numbers
where n <= convert(int, len(#Input)) and
substring(#Delimiter + #Input, n, 1) = #Delimiter
)
go
Usage (outputs 3mil rows in 40s on my laptop)
select *
from #yak
cross apply dbo.ufn_ParseArray(array, ',', 1)
cleanup
drop table dbo.Numbers;
drop function [dbo].[ufn_ParseArray]
Performance here is not amazing, but calling a function over a million row table is not the best idea. If performing a string split over many rows I would avoid the function.
This question is not about a string split approach, but about how to get the nth element.
All answers here are doing some kind of string splitting using recursion, CTEs, multiple CHARINDEX, REVERSE and PATINDEX, inventing functions, call for CLR methods, number tables, CROSS APPLYs ... Most answers cover many lines of code.
But - if you really want nothing more than an approach to get the nth element - this can be done as real one-liner, no UDF, not even a sub-select... And as an extra benefit: type safe
Get part 2 delimited by a space:
DECLARE #input NVARCHAR(100)=N'part1 part2 part3';
SELECT CAST(N'<x>' + REPLACE(#input,N' ',N'</x><x>') + N'</x>' AS XML).value('/x[2]','nvarchar(max)')
Of course you can use variables for delimiter and position (use sql:column to retrieve the position directly from a query's value):
DECLARE #dlmt NVARCHAR(10)=N' ';
DECLARE #pos INT = 2;
SELECT CAST(N'<x>' + REPLACE(#input,#dlmt,N'</x><x>') + N'</x>' AS XML).value('/x[sql:variable("#pos")][1]','nvarchar(max)')
If your string might include forbidden characters (especially one among &><), you still can do it this way. Just use FOR XML PATH on your string first to replace all forbidden characters with the fitting escape sequence implicitly.
It's a very special case if - additionally - your delimiter is the semicolon. In this case I replace the delimiter first to '#DLMT#', and replace this to the XML tags finally:
SET #input=N'Some <, > and &;Other äöü#€;One more';
SET #dlmt=N';';
SELECT CAST(N'<x>' + REPLACE((SELECT REPLACE(#input,#dlmt,'#DLMT#') AS [*] FOR XML PATH('')),N'#DLMT#',N'</x><x>') + N'</x>' AS XML).value('/x[sql:variable("#pos")][1]','nvarchar(max)');
UPDATE for SQL-Server 2016+
Regretfully the developers forgot to return the part's index with STRING_SPLIT. But, using SQL-Server 2016+, there is JSON_VALUE and OPENJSON.
With JSON_VALUE we can pass in the position as the index' array.
For OPENJSON the documentation states clearly:
When OPENJSON parses a JSON array, the function returns the indexes of the elements in the JSON text as keys.
A string like 1,2,3 needs nothing more than brackets: [1,2,3].
A string of words like this is an example needs to be ["this","is","an","example"].
These are very easy string operations. Just try it out:
DECLARE #str VARCHAR(100)='Hello John Smith';
DECLARE #position INT = 2;
--We can build the json-path '$[1]' using CONCAT
SELECT JSON_VALUE('["' + REPLACE(#str,' ','","') + '"]',CONCAT('$[',#position-1,']'));
--See this for a position safe string-splitter (zero-based):
SELECT JsonArray.[key] AS [Position]
,JsonArray.[value] AS [Part]
FROM OPENJSON('["' + REPLACE(#str,' ','","') + '"]') JsonArray
In this post I tested various approaches and found, that OPENJSON is really fast. Even much faster than the famous "delimitedSplit8k()" method...
UPDATE 2 - Get the values type-safe
We can use an array within an array simply by using doubled [[]]. This allows for a typed WITH-clause:
DECLARE #SomeDelimitedString VARCHAR(100)='part1|1|20190920';
DECLARE #JsonArray NVARCHAR(MAX)=CONCAT('[["',REPLACE(#SomeDelimitedString,'|','","'),'"]]');
SELECT #SomeDelimitedString AS TheOriginal
,#JsonArray AS TransformedToJSON
,ValuesFromTheArray.*
FROM OPENJSON(#JsonArray)
WITH(TheFirstFragment VARCHAR(100) '$[0]'
,TheSecondFragment INT '$[1]'
,TheThirdFragment DATE '$[2]') ValuesFromTheArray
Here is a UDF which will do it. It will return a table of the delimited values, haven't tried all scenarios on it but your example works fine.
CREATE FUNCTION SplitString
(
-- Add the parameters for the function here
#myString varchar(500),
#deliminator varchar(10)
)
RETURNS
#ReturnTable TABLE
(
-- Add the column definitions for the TABLE variable here
[id] [int] IDENTITY(1,1) NOT NULL,
[part] [varchar](50) NULL
)
AS
BEGIN
Declare #iSpaces int
Declare #part varchar(50)
--initialize spaces
Select #iSpaces = charindex(#deliminator,#myString,0)
While #iSpaces > 0
Begin
Select #part = substring(#myString,0,charindex(#deliminator,#myString,0))
Insert Into #ReturnTable(part)
Select #part
Select #myString = substring(#mystring,charindex(#deliminator,#myString,0)+ len(#deliminator),len(#myString) - charindex(' ',#myString,0))
Select #iSpaces = charindex(#deliminator,#myString,0)
end
If len(#myString) > 0
Insert Into #ReturnTable
Select #myString
RETURN
END
GO
You would call it like this:
Select * From SplitString('Hello John Smith',' ')
Edit: Updated solution to handle delimters with a len>1 as in :
select * From SplitString('Hello**John**Smith','**')
Here I post a simple way of solution
CREATE FUNCTION [dbo].[split](
#delimited NVARCHAR(MAX),
#delimiter NVARCHAR(100)
) RETURNS #t TABLE (id INT IDENTITY(1,1), val NVARCHAR(MAX))
AS
BEGIN
DECLARE #xml XML
SET #xml = N'<t>' + REPLACE(#delimited,#delimiter,'</t><t>') + '</t>'
INSERT INTO #t(val)
SELECT r.value('.','varchar(MAX)') as item
FROM #xml.nodes('/t') as records(r)
RETURN
END
Execute the function like this
select * from dbo.split('Hello John Smith',' ')
In my opinion you guys are making it way too complicated. Just create a CLR UDF and be done with it.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections.Generic;
public partial class UserDefinedFunctions {
[SqlFunction]
public static SqlString SearchString(string Search) {
List<string> SearchWords = new List<string>();
foreach (string s in Search.Split(new char[] { ' ' })) {
if (!s.ToLower().Equals("or") && !s.ToLower().Equals("and")) {
SearchWords.Add(s);
}
}
return new SqlString(string.Join(" OR ", SearchWords.ToArray()));
}
};
What about using string and values() statement?
DECLARE #str varchar(max)
SET #str = 'Hello John Smith'
DECLARE #separator varchar(max)
SET #separator = ' '
DECLARE #Splited TABLE(id int IDENTITY(1,1), item varchar(max))
SET #str = REPLACE(#str, #separator, '''),(''')
SET #str = 'SELECT * FROM (VALUES(''' + #str + ''')) AS V(A)'
INSERT INTO #Splited
EXEC(#str)
SELECT * FROM #Splited
Result-set achieved.
id item
1 Hello
2 John
3 Smith
I use the answer of frederic but this did not work in SQL Server 2005
I modified it and I'm using select with union all and it works
DECLARE #str varchar(max)
SET #str = 'Hello John Smith how are you'
DECLARE #separator varchar(max)
SET #separator = ' '
DECLARE #Splited table(id int IDENTITY(1,1), item varchar(max))
SET #str = REPLACE(#str, #separator, ''' UNION ALL SELECT ''')
SET #str = ' SELECT ''' + #str + ''' '
INSERT INTO #Splited
EXEC(#str)
SELECT * FROM #Splited
And the result-set is:
id item
1 Hello
2 John
3 Smith
4 how
5 are
6 you
This pattern works fine and you can generalize
Convert(xml,'<n>'+Replace(FIELD,'.','</n><n>')+'</n>').value('(/n[INDEX])','TYPE')
^^^^^ ^^^^^ ^^^^
note FIELD, INDEX and TYPE.
Let some table with identifiers like
sys.message.1234.warning.A45
sys.message.1235.error.O98
....
Then, you can write
SELECT Source = q.value('(/n[1])', 'varchar(10)'),
RecordType = q.value('(/n[2])', 'varchar(20)'),
RecordNumber = q.value('(/n[3])', 'int'),
Status = q.value('(/n[4])', 'varchar(5)')
FROM (
SELECT q = Convert(xml,'<n>'+Replace(fieldName,'.','</n><n>')+'</n>')
FROM some_TABLE
) Q
splitting and casting all parts.
Yet another get n'th part of string by delimeter function:
create function GetStringPartByDelimeter (
#value as nvarchar(max),
#delimeter as nvarchar(max),
#position as int
) returns NVARCHAR(MAX)
AS BEGIN
declare #startPos as int
declare #endPos as int
set #endPos = -1
while (#position > 0 and #endPos != 0) begin
set #startPos = #endPos + 1
set #endPos = charindex(#delimeter, #value, #startPos)
if(#position = 1) begin
if(#endPos = 0)
set #endPos = len(#value) + 1
return substring(#value, #startPos, #endPos - #startPos)
end
set #position = #position - 1
end
return null
end
and the usage:
select dbo.GetStringPartByDelimeter ('a;b;c;d;e', ';', 3)
which returns:
c
If your database has compatibility level of 130 or higher then you can use the STRING_SPLIT function along with OFFSET FETCH clauses to get the specific item by index.
To get the item at index N (zero based), you can use the following code
SELECT value
FROM STRING_SPLIT('Hello John Smith',' ')
ORDER BY (SELECT NULL)
OFFSET N ROWS
FETCH NEXT 1 ROWS ONLY
To check the compatibility level of your database, execute this code:
SELECT compatibility_level
FROM sys.databases WHERE name = 'YourDBName';
Try this:
CREATE function [SplitWordList]
(
#list varchar(8000)
)
returns #t table
(
Word varchar(50) not null,
Position int identity(1,1) not null
)
as begin
declare
#pos int,
#lpos int,
#item varchar(100),
#ignore varchar(100),
#dl int,
#a1 int,
#a2 int,
#z1 int,
#z2 int,
#n1 int,
#n2 int,
#c varchar(1),
#a smallint
select
#a1 = ascii('a'),
#a2 = ascii('A'),
#z1 = ascii('z'),
#z2 = ascii('Z'),
#n1 = ascii('0'),
#n2 = ascii('9')
set #ignore = '''"'
set #pos = 1
set #dl = datalength(#list)
set #lpos = 1
set #item = ''
while (#pos <= #dl) begin
set #c = substring(#list, #pos, 1)
if (#ignore not like '%' + #c + '%') begin
set #a = ascii(#c)
if ((#a >= #a1) and (#a <= #z1))
or ((#a >= #a2) and (#a <= #z2))
or ((#a >= #n1) and (#a <= #n2))
begin
set #item = #item + #c
end else if (#item > '') begin
insert into #t values (#item)
set #item = ''
end
end
set #pos = #pos + 1
end
if (#item > '') begin
insert into #t values (#item)
end
return
end
Test it like this:
select * from SplitWordList('Hello John Smith')
I was looking for the solution on net and the below works for me.
Ref.
And you call the function like this :
SELECT * FROM dbo.split('ram shyam hari gopal',' ')
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
The following example uses a recursive CTE
Update 18.09.2013
CREATE FUNCTION dbo.SplitStrings_CTE(#List nvarchar(max), #Delimiter nvarchar(1))
RETURNS #returns TABLE (val nvarchar(max), [level] int, PRIMARY KEY CLUSTERED([level]))
AS
BEGIN
;WITH cte AS
(
SELECT SUBSTRING(#List, 0, CHARINDEX(#Delimiter, #List + #Delimiter)) AS val,
CAST(STUFF(#List + #Delimiter, 1, CHARINDEX(#Delimiter, #List + #Delimiter), '') AS nvarchar(max)) AS stval,
1 AS [level]
UNION ALL
SELECT SUBSTRING(stval, 0, CHARINDEX(#Delimiter, stval)),
CAST(STUFF(stval, 1, CHARINDEX(#Delimiter, stval), '') AS nvarchar(max)),
[level] + 1
FROM cte
WHERE stval != ''
)
INSERT #returns
SELECT REPLACE(val, ' ','' ) AS val, [level]
FROM cte
WHERE val > ''
RETURN
END
Demo on SQLFiddle
Alter Function dbo.fn_Split
(
#Expression nvarchar(max),
#Delimiter nvarchar(20) = ',',
#Qualifier char(1) = Null
)
RETURNS #Results TABLE (id int IDENTITY(1,1), value nvarchar(max))
AS
BEGIN
/* USAGE
Select * From dbo.fn_Split('apple pear grape banana orange honeydew cantalope 3 2 1 4', ' ', Null)
Select * From dbo.fn_Split('1,abc,"Doe, John",4', ',', '"')
Select * From dbo.fn_Split('Hello 0,"&""&&&&', ',', '"')
*/
-- Declare Variables
DECLARE
#X xml,
#Temp nvarchar(max),
#Temp2 nvarchar(max),
#Start int,
#End int
-- HTML Encode #Expression
Select #Expression = (Select #Expression For XML Path(''))
-- Find all occurences of #Delimiter within #Qualifier and replace with |||***|||
While PATINDEX('%' + #Qualifier + '%', #Expression) > 0 AND Len(IsNull(#Qualifier, '')) > 0
BEGIN
Select
-- Starting character position of #Qualifier
#Start = PATINDEX('%' + #Qualifier + '%', #Expression),
-- #Expression starting at the #Start position
#Temp = SubString(#Expression, #Start + 1, LEN(#Expression)-#Start+1),
-- Next position of #Qualifier within #Expression
#End = PATINDEX('%' + #Qualifier + '%', #Temp) - 1,
-- The part of Expression found between the #Qualifiers
#Temp2 = Case When #End &LT 0 Then #Temp Else Left(#Temp, #End) End,
-- New #Expression
#Expression = REPLACE(#Expression,
#Qualifier + #Temp2 + Case When #End &LT 0 Then '' Else #Qualifier End,
Replace(#Temp2, #Delimiter, '|||***|||')
)
END
-- Replace all occurences of #Delimiter within #Expression with '&lt/fn_Split&gt&ltfn_Split&gt'
-- And convert it to XML so we can select from it
SET
#X = Cast('&ltfn_Split&gt' +
Replace(#Expression, #Delimiter, '&lt/fn_Split&gt&ltfn_Split&gt') +
'&lt/fn_Split&gt' as xml)
-- Insert into our returnable table replacing '|||***|||' back to #Delimiter
INSERT #Results
SELECT
"Value" = LTRIM(RTrim(Replace(C.value('.', 'nvarchar(max)'), '|||***|||', #Delimiter)))
FROM
#X.nodes('fn_Split') as X(C)
-- Return our temp table
RETURN
END
You can split a string in SQL without needing a function:
DECLARE #bla varchar(MAX)
SET #bla = 'BED40DFC-F468-46DD-8017-00EF2FA3E4A4,64B59FC5-3F4D-4B0E-9A48-01F3D4F220B0,A611A108-97CA-42F3-A2E1-057165339719,E72D95EA-578F-45FC-88E5-075F66FD726C'
-- http://stackoverflow.com/questions/14712864/how-to-query-values-from-xml-nodes
SELECT
x.XmlCol.value('.', 'varchar(36)') AS val
FROM
(
SELECT
CAST('<e>' + REPLACE(#bla, ',', '</e><e>') + '</e>' AS xml) AS RawXml
) AS b
CROSS APPLY b.RawXml.nodes('e') x(XmlCol);
If you need to support arbitrary strings (with xml special characters)
DECLARE #bla NVARCHAR(MAX)
SET #bla = '<html>unsafe & safe Utf8CharsDon''tGetEncoded ÄöÜ - "Conex"<html>,Barnes & Noble,abc,def,ghi'
-- http://stackoverflow.com/questions/14712864/how-to-query-values-from-xml-nodes
SELECT
x.XmlCol.value('.', 'nvarchar(MAX)') AS val
FROM
(
SELECT
CAST('<e>' + REPLACE((SELECT #bla FOR XML PATH('')), ',', '</e><e>') + '</e>' AS xml) AS RawXml
) AS b
CROSS APPLY b.RawXml.nodes('e') x(XmlCol);
In Azure SQL Database (based on Microsoft SQL Server but not exactly the same thing) the signature of STRING_SPLIT function looks like:
STRING_SPLIT ( string , separator [ , enable_ordinal ] )
When enable_ordinal flag is set to 1 the result will include a column named ordinal that consists of the 1‑based position of the substring within the input string:
SELECT *
FROM STRING_SPLIT('hello john smith', ' ', 1)
| value | ordinal |
|-------|---------|
| hello | 1 |
| john | 2 |
| smith | 3 |
This allows us to do this:
SELECT value
FROM STRING_SPLIT('hello john smith', ' ', 1)
WHERE ordinal = 2
| value |
|-------|
| john |
If enable_ordinal is not available then there is a trick which assumes that the substrings within the input string are unique. In this scenario, CHAR_INDEX could be used to find the position of the substring within the input string:
SELECT value, ROW_NUMBER() OVER (ORDER BY CHARINDEX(value, input_str)) AS ord_pos
FROM (VALUES
('hello john smith')
) AS x(input_str)
CROSS APPLY STRING_SPLIT(input_str, ' ')
| value | ord_pos |
|-------+---------|
| hello | 1 |
| john | 2 |
| smith | 3 |
I know it's an old Question, but i think some one can benefit from my solution.
select
SUBSTRING(column_name,1,CHARINDEX(' ',column_name,1)-1)
,SUBSTRING(SUBSTRING(column_name,CHARINDEX(' ',column_name,1)+1,LEN(column_name))
,1
,CHARINDEX(' ',SUBSTRING(column_name,CHARINDEX(' ',column_name,1)+1,LEN(column_name)),1)-1)
,SUBSTRING(SUBSTRING(column_name,CHARINDEX(' ',column_name,1)+1,LEN(column_name))
,CHARINDEX(' ',SUBSTRING(column_name,CHARINDEX(' ',column_name,1)+1,LEN(column_name)),1)+1
,LEN(column_name))
from table_name
SQL FIDDLE
Advantages:
It separates all the 3 sub-strings deliminator by ' '.
One must not use while loop, as it decreases the performance.
No need to Pivot as all the resultant sub-string will be displayed in
one Row
Limitations:
One must know the total no. of spaces (sub-string).
Note: the solution can give sub-string up to to N.
To overcame the limitation we can use the following ref.
But again the above solution can't be use in a table (Actaully i wasn't able to use it).
Again i hope this solution can help some-one.
Update: In case of Records > 50000 it is not advisable to use LOOPS as it will degrade the Performance
Pure set-based solution using TVF with recursive CTE. You can JOIN and APPLY this function to any dataset.
create function [dbo].[SplitStringToResultSet] (#value varchar(max), #separator char(1))
returns table
as return
with r as (
select value, cast(null as varchar(max)) [x], -1 [no] from (select rtrim(cast(#value as varchar(max))) [value]) as j
union all
select right(value, len(value)-case charindex(#separator, value) when 0 then len(value) else charindex(#separator, value) end) [value]
, left(r.[value], case charindex(#separator, r.value) when 0 then len(r.value) else abs(charindex(#separator, r.[value])-1) end ) [x]
, [no] + 1 [no]
from r where value > '')
select ltrim(x) [value], [no] [index] from r where x is not null;
go
Usage:
select *
from [dbo].[SplitStringToResultSet]('Hello John Smith', ' ')
where [index] = 1;
Result:
value index
-------------
John 1
Almost all the other answers are replacing the string being split which wastes CPU cycles and performs unnecessary memory allocations.
I cover a much better way to do a string split here: http://www.digitalruby.com/split-string-sql-server/
Here is the code:
SET NOCOUNT ON
-- You will want to change nvarchar(MAX) to nvarchar(50), varchar(50) or whatever matches exactly with the string column you will be searching against
DECLARE #SplitStringTable TABLE (Value nvarchar(MAX) NOT NULL)
DECLARE #StringToSplit nvarchar(MAX) = 'your|string|to|split|here'
DECLARE #SplitEndPos int
DECLARE #SplitValue nvarchar(MAX)
DECLARE #SplitDelim nvarchar(1) = '|'
DECLARE #SplitStartPos int = 1
SET #SplitEndPos = CHARINDEX(#SplitDelim, #StringToSplit, #SplitStartPos)
WHILE #SplitEndPos > 0
BEGIN
SET #SplitValue = SUBSTRING(#StringToSplit, #SplitStartPos, (#SplitEndPos - #SplitStartPos))
INSERT #SplitStringTable (Value) VALUES (#SplitValue)
SET #SplitStartPos = #SplitEndPos + 1
SET #SplitEndPos = CHARINDEX(#SplitDelim, #StringToSplit, #SplitStartPos)
END
SET #SplitValue = SUBSTRING(#StringToSplit, #SplitStartPos, 2147483647)
INSERT #SplitStringTable (Value) VALUES(#SplitValue)
SET NOCOUNT OFF
-- You can select or join with the values in #SplitStringTable at this point.
Recursive CTE solution with server pain, test it
MS SQL Server 2008 Schema Setup:
create table Course( Courses varchar(100) );
insert into Course values ('Hello John Smith');
Query 1:
with cte as
( select
left( Courses, charindex( ' ' , Courses) ) as a_l,
cast( substring( Courses,
charindex( ' ' , Courses) + 1 ,
len(Courses ) ) + ' '
as varchar(100) ) as a_r,
Courses as a,
0 as n
from Course t
union all
select
left(a_r, charindex( ' ' , a_r) ) as a_l,
substring( a_r, charindex( ' ' , a_r) + 1 , len(a_R ) ) as a_r,
cte.a,
cte.n + 1 as n
from Course t inner join cte
on t.Courses = cte.a and len( a_r ) > 0
)
select a_l, n from cte
--where N = 1
Results:
| A_L | N |
|--------|---|
| Hello | 0 |
| John | 1 |
| Smith | 2 |
while similar to the xml based answer by josejuan, i found that processing the xml path only once, then pivoting was moderately more efficient:
select ID,
[3] as PathProvidingID,
[4] as PathProvider,
[5] as ComponentProvidingID,
[6] as ComponentProviding,
[7] as InputRecievingID,
[8] as InputRecieving,
[9] as RowsPassed,
[10] as InputRecieving2
from
(
select id,message,d.* from sysssislog cross apply (
SELECT Item = y.i.value('(./text())[1]', 'varchar(200)'),
row_number() over(order by y.i) as rn
FROM
(
SELECT x = CONVERT(XML, '<i>' + REPLACE(Message, ':', '</i><i>') + '</i>').query('.')
) AS a CROSS APPLY x.nodes('i') AS y(i)
) d
WHERE event
=
'OnPipelineRowsSent'
) as tokens
pivot
( max(item) for [rn] in ([3],[4],[5],[6],[7],[8],[9],[10])
) as data
ran in 8:30
select id,
tokens.value('(/n[3])', 'varchar(100)')as PathProvidingID,
tokens.value('(/n[4])', 'varchar(100)') as PathProvider,
tokens.value('(/n[5])', 'varchar(100)') as ComponentProvidingID,
tokens.value('(/n[6])', 'varchar(100)') as ComponentProviding,
tokens.value('(/n[7])', 'varchar(100)') as InputRecievingID,
tokens.value('(/n[8])', 'varchar(100)') as InputRecieving,
tokens.value('(/n[9])', 'varchar(100)') as RowsPassed
from
(
select id, Convert(xml,'<n>'+Replace(message,'.','</n><n>')+'</n>') tokens
from sysssislog
WHERE event
=
'OnPipelineRowsSent'
) as data
ran in 9:20
CREATE FUNCTION [dbo].[fnSplitString]
(
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
DECLARE #start INT, #end INT
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
INSERT INTO #output (splitdata)
VALUES(SUBSTRING(#string, #start, #end - #start))
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
RETURN
END
AND USE IT
select *from dbo.fnSplitString('Querying SQL Server','')
if anyone wants to get only one part of the seperatured text can use this
select * from fromSplitStringSep('Word1 wordr2 word3',' ')
CREATE function [dbo].[SplitStringSep]
(
#str nvarchar(4000),
#separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
1,
1,
charindex(#separator, #str)
union all
select
p + 1,
b + 1,
charindex(#separator, #str, b + 1)
from tokens
where b > 0
)
select
p-1 zeroBasedOccurance,
substring(
#str,
a,
case when b > 0 then b-a ELSE 4000 end)
AS s
from tokens
)
I devoloped this,
declare #x nvarchar(Max) = 'ali.veli.deli.';
declare #item nvarchar(Max);
declare #splitter char='.';
while CHARINDEX(#splitter,#x) != 0
begin
set #item = LEFT(#x,CHARINDEX(#splitter,#x))
set #x = RIGHT(#x,len(#x)-len(#item) )
select #item as item, #x as x;
end
the only attention you should is dot '.' that end of the #x is always should be there.
building on #NothingsImpossible solution, or, rather, comment on the most voted answer (just below the accepted one), i found the following quick-and-dirty solution fulfill my own needs - it has a benefit of being solely within SQL domain.
given a string "first;second;third;fourth;fifth", say, I want to get the third token. this works only if we know how many tokens the string is going to have - in this case it's 5. so my way of action is to chop the last two tokens away (inner query), and then to chop the first two tokens away (outer query)
i know that this is ugly and covers the specific conditions i was in, but am posting it just in case somebody finds it useful. cheers
select
REVERSE(
SUBSTRING(
reverse_substring,
0,
CHARINDEX(';', reverse_substring)
)
)
from
(
select
msg,
SUBSTRING(
REVERSE(msg),
CHARINDEX(
';',
REVERSE(msg),
CHARINDEX(
';',
REVERSE(msg)
)+1
)+1,
1000
) reverse_substring
from
(
select 'first;second;third;fourth;fifth' msg
) a
) b
declare #strng varchar(max)='hello john smith'
select (
substring(
#strng,
charindex(' ', #strng) + 1,
(
(charindex(' ', #strng, charindex(' ', #strng) + 1))
- charindex(' ',#strng)
)
))