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
结果
Name Family
----- ------
Aria Karimi
Bab Karimi
Joe Karimi
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
您可以调用此函数,如下所示:
select * from fn_split('1,24,5',',')
实施:
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
USE COMPANY;
SELECT PARSENAME('Whatever.you.want.parsed',3) AS 'ReturnValue';
本文还描述了如何使用名为“replacechars”的公共表表达式(cte)对分隔符替换的值运行parsename。cte用于返回临时视图或结果集。 之后,使用unpivot函数将一些列转换为行;substring和charindex函数用于清除数据中的不一致,lag函数(sql server 2012的新功能)用于最后,因为它允许引用以前的记录。
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
用法示例:
SELECT dbo.Wordparser(COLUMN, 1),
dbo.Wordparser(COLUMN, 2),
dbo.Wordparser(COLUMN, 3)
FROM TABLE
有多种方法可以解决这个问题,已经提出了许多不同的方法。最简单的方法就是 LEFT / SUBSTRING 和其他字符串函数来实现所需的结果。 样本数据
DECLARE @tbl1 TABLE (Value INT,String VARCHAR(MAX))
INSERT INTO @tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO @tbl1 VALUES(2,'John, Mathew');
使用字符串函数,如 LEFT ``` SELECT Value, LEFT(String,CHARINDEX(',',String)-1) as Fname, LTRIM(RIGHT(String,LEN(String) - CHARINDEX(',',String) )) AS Lname FROM @tbl1
如果字符串中有两个以上的项,则此方法失败。在这种情况下,我们可以使用拆分器,然后使用 `PIVOT` 或将字符串转换为 `XML` 使用 `.nodes` 获取字符串项。 `XML` aads和bvr在他们的解决方案中已经详细地描述了基于web的解决方案。
这个问题的答案使用拆分器,全部使用 `WHILE` 这对拆分效率很低。检查此性能比较。最好的分路器之一是 `DelimitedSplit8K` ,由jeff moden创建。你可以在这里了解更多
分路器 `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
输出
Value Fname Lname
1 Cleo Smith
2 John Mathew
``` `DelimitedSplit8K` 杰夫·摩登
CREATE FUNCTION [dbo].[DelimitedSplit8K] /********************************************************************************************************************** Purpose: Split a given string at a given delimiter and return a list of the split elements (items).
Notes:
Leading a trailing delimiters are treated as if an empty string element were present.
Consecutive delimiters are treated as if an empty string element were present between them.
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:
Optimized for VARCHAR(8000) or less. No testing or error reporting for truncation at 8000 characters is done.
Optimized for single character delimiter. Multi-character delimiters should be resolvedexternally from this function.
Optimized for use with CROSS APPLY.
Does not "trim" elements just in case leading or trailing blanks are intended.
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/
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.
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 ;
;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
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 Value , Substring(FullName, 1,Charindex(',', FullName)-1) as Name,
Substring(FullName, Charindex(',', FullName)+1, LEN(FullName)) as Surname
from Table1
sql server中没有现成的拆分函数,因此需要创建用户定义的函数。
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
30条答案
按热度按时间sulc1iza16#
可以使用表值函数
STRING_SPLIT
,仅在兼容级别130下可用。如果您的数据库兼容级别低于130,sql server将无法找到并执行STRING_SPLIT
功能。可以使用以下命令更改数据库的兼容级别:语法
请参阅此处的文档
oprakyz717#
使用parsename()函数
结果
owfi6suc18#
我认为以下功能对您有用:
必须先在sql中创建一个函数。这样地
您可以调用此函数,如下所示:
实施:
结果如下:
d4so4syb19#
我们可以创建这样一个函数
然后,我们可以使用select语句将csv值分离到各自的列中
pxyaymoc20#
az31mfrm21#
我认为parsename是用于本例的整洁函数,如本文所述:http://www.sqlshack.com/parsing-and-rotating-delimited-data-in-sql-server-2012/
parsename函数在逻辑上设计为解析由四部分组成的对象名。parsename的优点在于它不局限于只解析由sql server四部分组成的对象名—它将解析由点分隔的任何函数或字符串数据。
第一个参数是要解析的对象,第二个参数是要返回的对象片段的整数值。本文讨论的是解析和旋转分隔数据-公司电话号码,但它也可以用于解析姓名/姓氏数据。
例子:
本文还描述了如何使用名为“replacechars”的公共表表达式(cte)对分隔符替换的值运行parsename。cte用于返回临时视图或结果集。
之后,使用unpivot函数将一些列转换为行;substring和charindex函数用于清除数据中的不一致,lag函数(sql server 2012的新功能)用于最后,因为它允许引用以前的记录。
xqk2d5yq22#
尝试此操作(将“”的示例更改为“,”或任何您要使用的分隔符)
用法示例:
wz8daaqr23#
使用sql server 2016,我们可以使用字符串\u split来完成以下任务:
dm7nw8vv24#
有多种方法可以解决这个问题,已经提出了许多不同的方法。最简单的方法就是
LEFT
/SUBSTRING
和其他字符串函数来实现所需的结果。样本数据
使用字符串函数,如
LEFT
```SELECT
Value,
LEFT(String,CHARINDEX(',',String)-1) as Fname,
LTRIM(RIGHT(String,LEN(String) - CHARINDEX(',',String) )) AS Lname
FROM @tbl1
输出
CREATE FUNCTION [dbo].[DelimitedSplit8K]
/**********************************************************************************************************************
Purpose:
Split a given string at a given delimiter and return a list of the split elements (items).
Notes:
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:
function.
http://www.sqlservercentral.com/articles/T-SQL/62867/
VARCHAR(MAX) whether it fits in-row or not.
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
zour9fqk25#
交叉应用
f8rj6qna26#
我觉得这很酷
p5fdfcr127#
基于xml的答案简单明了
参考此
2q5ifsrm28#
也可以查看下面的链接以供参考
http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html
20jt8wwn29#
ni65a41a30#
您的目的可以通过以下查询解决-
sql server中没有现成的拆分函数,因此需要创建用户定义的函数。