如何将逗号分隔的值拆分成列

191
我有一个如下的表格:
Value String
1 Cleo, Smith
我想把逗号分隔的字符串分成两列:
Value Name Surname
1 Cleo Smith
我只需要额外的两列。

可能是重复的问题:如何将单列值拆分为多列值? - Pondlife
来自 String_Split: "输出行可能以任何顺序出现。不能保证顺序与输入字符串中的子字符串顺序匹配。" 它是在 SQL Server 2016 中添加的。 - HABO
@HABO,因此对于关于如何在SQL Server 2008中执行此操作的问题是无用的 :-) - TylerH
这里的大多数答案将其分成了行而不是列...因此,大多数答案都是不正确的。 - Nick.McDermaid
38个回答

168

你可以使用以下查询来实现你的目的 -

Select Value  , Substring(FullName, 1,Charindex(',', FullName)-1) as Name,
Substring(FullName, Charindex(',', FullName)+1, LEN(FullName)) as  Surname
from Table1

在 SQL Server 中没有现成的 Split 函数,因此我们需要创建用户定义函数。

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

1
请查看下面 @ughai 回答中 Jeff Moden 的 DelimitedSplit8K 数字表解决方案。 - Ruskin
3
SQL 2016 现在附带了一个拆分函数。 - tvanharp
SQL 2016及以上版本:SELECT * FROM STRING_SPLIT('John,Jeremy,Jack',',') - Alaa Alweish
1
SUBSTRING和CHARINDEX在PySpark中也可以使用,因此这个答案解决了#pyspark上相同的列分隔挑战。 - Brad Hein

69
;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

并且参考下面的链接

http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html


5
这个更好了,简洁明了。 - Kimchi Man
5
我非常喜欢这种方法。当需要拆分超过两个值时(例如1、2、3),使用CHARINDEX和SUBSTRING会很混乱。非常感谢。 - jotapdiez
2
好主意。对我来说,比起 CHARINDEXSUBSTRING 的混乱,慢了三倍。 :-( - Michel de Ruiter
5
很好的解决方案,但是某些字符在XML中是非法的(例如'&'),因此我不得不将每个字段都包裹在CDATA标记中...... `CONVERT(XML,'<Names><name><![CDATA['
  • REPLACE(Name,',', ']]></name><name><![CDATA[') + ']]></name></name>') AS xmlname`
- Tony
2
@Tony 需要将代码从 Tony 更新为 CONVERT(XML,'<Names><name><![CDATA[' + REPLACE(address1,',', ']]></name><name><![CDATA[') + ']]></name></Names>') AS xmlnames(缺少最后一个 s 在 </Names> 上)。 - Ryan Buddicom
显示剩余4条评论

52

基于XML的答案简单而干净

请参考此链接

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)

2
太棒了!这个类似于数组的特性非常有用,而且我之前不知道它的存在。谢谢! - Vnge

50

我认为这很酷

SELECT value,
    PARSENAME(REPLACE(String,',','.'),2) 'Name' ,
    PARSENAME(REPLACE(String,',','.'),1) 'Surname'
FROM table WITH (NOLOCK)

3
您的要求仅包括名字和姓氏,对吗? - Azar
1
你还需要知道,对于长度超过128个字符的项目,PARSENAME将返回NULL。 - Luis Cazares
不错。对我的数据集也很有效! - glass_kites

30

使用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

5
我无法理解为什么您需要在原始字符串末尾添加两个逗号才能使其正常工作。为什么不加“ + ',,' ”就不能正常工作? - tomato
@developer.ejay 是因为 Left/SubString 函数不能接受 0 值吗? - Waller
太好了!您可以轻松地复制/粘贴每个额外列的2行代码-然后只需递增数字,例如: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 p3 = charindex( ',', str, p2 + 1 ) ) ap3 cross apply ( select FName = substring( str, 1, p1-1 )
, LName = substring( str, p1+1, p2-p1-1 ) , Age = substring( str, p2+1, p3-p2-1 ) ) ParsedData
- Mike

24

有多种方法可以解决这个问题,已经提出了许多不同的方法。最简单的方法是使用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

如果一个字符串中有超过2个项,则此方法将失败。在这种情况下,我们可以使用分隔符,然后使用PIVOT或将字符串转换为XML并使用.nodes来获取字符串项。 aads和bvr在他们的解决方案中详细介绍了基于XML的解决方案。
对于使用分隔符的这个问题的答案,所有答案都使用效率低下的WHILE进行拆分。请查看此性能比较。其中最好的分隔符之一是由Jeff Moden创建的DelimitedSplit8K。您可以在此处阅读更多信息。 使用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 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

22

使用 SQL Server 2016,我们可以使用 string_split 来完成此操作:

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,',')

我正在使用SQL Server 2016,但它出现了一个错误:“无效的对象名称'string_split'”。 - Bruno
3
请问您能否检查一下数据库的兼容性水平?它必须是130,这对应着SQL Server 2016。您可以使用以下查询语句:select * from sys.databases。 - Kannan Kandasamy
1
数据库开发人员可能会将兼容级别设置为任何较低的值,以保持与数据库兼容,即使实际安装的版本更高也是如此。使用此功能将级别设置为尽可能高的要求,只要数据库支持:DECLARE @cl TINYINT; SELECT @cl = compatibility_level FROM [sys].[databases] WHERE name = 'mydb'; IF @cl < 130 BEGIN ALTER DATABASE myDb SET COMPATIBILITY_LEVEL = 130 END; - Joerg Krause
3
除非你将其从行转换为列,否则这是无用的。 - Guy Manova
我们可以在单个查询中对多列使用Split_String吗?假设我有两列中的逗号分隔记录,那么我们可以使用它吗? - nixxo_raa
显示剩余2条评论

19
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

13
这不应该成为被接受的答案……一个多语句TVF(非常糟糕!)和一个WHILE循环(更糟)结合在一起将表现得非常糟糕。此外,这是一个 仅有代码 的答案,甚至没有解决问题。有更好的方法!对于SQL-Server 2016+,请寻找STRING_SPLIT()(它不包含片段的位置,这是一个巨大的失败!)或真正快速的JSONhack。对于旧版本,请寻找众所周知的XML hack(json和xml详细信息[在这里](https://stackoverflow.com/a/58856480/5089204))。或者寻找基于递归CTE的众多iTVFs之一。 - Shnugo
SQL 2016及以上版本:SELECT * FROM STRING_SPLIT('John,Jeremy,Jack',',') - Alaa Alweish
同意给出的解决方案。但是,如果您使用的是SQL Server 2016,则可以使用string_split函数。您还可以在此处找到此内置函数的用法:https://tecloger.com/string-split-function-in-sql-server/ - Khatri
7
大家都建议使用STRING_SPLIT函数,但这个函数如何将字符串拆分为(而不是像它本来的用途那样拆分成行)? - geominded

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

6
如果您能详细解释一下您的答案,并使用代码格式工具,那将非常有用。 - Politank-Z
关闭,这将包括姓氏中的逗号。+1放错了位置。应该是Substring(NAME,Charindex(',',NAME)+1,Len(NAME))AS lastname。 - LarryBud
以上查询将会给出姓氏和逗号,因为它以逗号开头。以下是正确的查询:SELECT id, Substring(NAME, 0, Charindex(',', NAME)) AS firstname, Substring(NAME, Charindex(',', NAME)+1, Len(NAME) ) AS lastname FROM spilt - Rahul Shukla
在多个逗号分隔值的情况下会发生什么? - Rahul Bhat
在多个逗号分隔值的情况下会发生什么? - Rahul Bhat

15

试试这个(将 ' ' 的实例更改为 ',' 或任何您想要使用的分隔符)

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

如果同一行中存在相同的值,则对我失败。 - Pete Alvin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接