【问题标题】:Function to split string by commas, inserting into two columns函数用逗号分割字符串,插入两列
【发布时间】:2013-10-08 12:45:31
【问题描述】:

我正在尝试创建一个函数,该函数将用逗号分隔并插入到包含“Num”和“String”列的表中。

输入字符串看起来像

Number 在 num 列中,而 name 在 string 列中。

到目前为止我有

drop function dbo.GetCommaSplit;
go

CREATE FUNCTION dbo.GetCommaSplit (@String varchar(max))
RETURNS table
AS
RETURN 
(
WITH Splitter (Num, String)
AS

FROM dbo.Numbers
WHERE Num <= LEN(@String)
AND (SUBSTRING(@String, Num - 1, 1) = N',' OR Num = 0)
)
SELECT
RTRIM(LTRIM(String)) AS Word
FROM Splitter
WHERE String <> ''
);
GO

但这会拆分所有内容并每次都给出一个新行,这不是我想要的。

\ 干杯

【问题讨论】:

  • 所以你想要像'Michael,Tito,Jermaine,Marlon'和'1,2,3,4'这样的输出只有一行你给的字符串???
  • 一行是 1 |迈克尔,下一行是 2 | tito..等等,这有意义吗?
  • 你想要给定字符串中的 8 行 ???
  • 给定的字符串将有 4 行 2 列

标签: sql sql-server stored-procedures user-defined-functions


【解决方案1】:

类似

;with cte as
(
select 
    1 as rn, 
    CHARINDEX(',',@string, 0) pos, 
    LEFT(@string,CHARINDEX(',',@string, 0) -1) as word, 
    substring(@string,CHARINDEX(',',@string, 0) +1, LEN(@string)) as string
union all
select
    rn+1,
    CHARINDEX(',',string, 0) pos, 
    case when CHARINDEX(',',string, 0) >0 then  LEFT(string,CHARINDEX(',',string, 0) -1) else string end as word, 
    case when CHARINDEX(',',string, 0) >0 then  substring(string,CHARINDEX(',',string, 0) +1, LEN(string)) else null end as string
from cte
where CHARINDEX(',',string, 0) >=0
)
select c1.word as Num, c2.word as Name from    
(select * from cte where rn %2=0) c1
inner join
(select * from cte) c2
    on c1.rn =c2.rn+1

【讨论】:

  • @JohnSmith 您替换了 return 括号内的所有内容。
  • 似乎很好,除了这个错误“每个视图或函数中的列名必须是唯一的。视图或函数'GetCommaSplit'中的列名'word'被指定了不止一次。”你知道为什么会这样吗?
猜你喜欢
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
相关资源
最近更新 更多