如何在具有两个不同分隔符的sql server中拆分字符串

时间:2017-03-02 16:56:15

标签: sql-server

我想将字符串传递给存储过程 '1:3,2:4,5:8'其中1,2,5是产品ID,3,4,8是各自的数量。 它应该添加到表中,如下所示

PID|Qty
1  |3
2  |4
5  |8

我创建了分裂功能

CREATE FUNCTION SplitString
(    
      @Input NVARCHAR(MAX),
      @Character CHAR(1)
)
RETURNS @Output TABLE (
      Item NVARCHAR(1000)
)
AS
BEGIN
      DECLARE @StartIndex INT, @EndIndex INT

      SET @StartIndex = 1
      IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
      BEGIN
            SET @Input = @Input + @Character
      END

      WHILE CHARINDEX(@Character, @Input) > 0
      BEGIN
            SET @EndIndex = CHARINDEX(@Character, @Input)

            INSERT INTO @Output(Item)
            SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)

            SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
      END

      RETURN
END
GO

1 个答案:

答案 0 :(得分:3)

这就是你如何使用Jeff Moden的CSV Splitter函数分割字符串的方式:

declare @str varchar(100) = '1:3,2:4,5:8' ;

select 
    s.ItemNumber
  , Product  = left(s.Item,charindex(':',s.Item)-1)
  , Quantity = stuff(s.Item,1,charindex(':',s.Item),'')
from (select * from [dbo].[delimitedsplit8K] (@str,',')) as s

测试设置:http://rextester.com/HWSVW98120

返回:

+------------+---------+----------+
| ItemNumber | Product | Quantity |
+------------+---------+----------+
|          1 |       1 |        3 |
|          2 |       2 |        4 |
|          3 |       5 |        8 |
+------------+---------+----------+

拆分字符串参考:

您应该考虑使用表值参数。