SQL Server字符串拆分函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL Server字符串拆分函数相关的知识,希望对你有一定的参考价值。

From StackOverflow. I'm still not quite happy with my understanding of it, but it looks an order of magnitude more elegant than most I've found.
  1. CREATE FUNCTION dbo.Split (@sep CHAR(1), @s VARCHAR(512))
  2. RETURNS TABLE
  3. AS
  4. RETURN (
  5. WITH Pieces(pn, START, stop) AS (
  6. SELECT 1, 1, CHARINDEX(@sep, @s)
  7. UNION ALL
  8. SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
  9. FROM Pieces
  10. WHERE stop > 0
  11. )
  12. SELECT pn,
  13. SUBSTRING(@s, START, CASE WHEN stop > 0 THEN stop-START ELSE 512 END) AS s
  14. FROM Pieces
  15. )
  16.  
  17.  
  18. --Here's a simpler demo of the CTE Recursion with the string parsing removed for clarity:
  19. --Part before the UNION is called the Anchor expression.
  20.  
  21. BEGIN
  22. WITH Pieces(START, stop) AS (
  23. SELECT 2, 2
  24. UNION ALL
  25. SELECT START + 1, stop + 1
  26. FROM Pieces
  27. WHERE stop < 5
  28. )
  29. SELECT START, stop
  30. FROM Pieces
  31. END
  32.  
  33. --Returns
  34. --start stop
  35. --2 2
  36. --3 3
  37. --4 4
  38. --5 5

以上是关于SQL Server字符串拆分函数的主要内容,如果未能解决你的问题,请参考以下文章

在 SQL Server 2008 的拆分函数中使用连接表列

sql数据库截取字符串函数

MS SQL Server 在空格上拆分单词,但仅在不在双引号中时

SQL Server函数里面有一个Select语句和事务死锁

SQL Server 中的函数拆分导致错误

Sql Server字符串拆分(Split)方法汇总