【发布时间】:2020-04-11 01:52:48
【问题描述】:
我有一个包含行的表,并且在一个字段中有这样的值 A、B、C
表'Mytable':
|ID | Date | MyValue | SplitID |
|1 | 2019-12-17 | A | |
|2 | 2019-12-15 | A,B | |
|3 | 2019-12-16 | B,C | |
结果应该是:
|1 | 2019-12-17 | A | 1 |
|2 | 2019-12-15 | A | 2 |
|4 | 2019-12-15 | B | 2 |
|3 | 2019-12-16 | B | 3 |
|5 | 2019-12-16 | C | 3 |
(抱歉,我在 Stackoverflow 帮助中找不到如何格式化表格)
我尝试了一个内联表函数,它将字段 Myvalue 拆分为更多行,但无法使用
传递我的行charindex(',',[MyValue])>0
来自 MyTable 作为输入行。
代码是这样的:
ALTER function [dbo].[fncSplitString](@input Varchar(max), @Splitter Varchar(99), @ID int)
returns table as
Return
with tmp (DataItem, ix, ID) as
( select LTRIM(@input) , CHARINDEX('',@Input), @ID --Recu. start, ignored val to get the types right
union all
select LTRIM(Substring(@input, ix+1,ix2-ix-1)), ix2, @ID
from (Select *, CHARINDEX(@Splitter,@Input+@Splitter,ix+1) ix2 from tmp) x where ix2<>0
) select DataItem,ID from tmp where ix<>0
感谢您的帮助
迈克尔
【问题讨论】:
-
您的 SQL Server 版本是多少?
-
序数位置重要吗?
-
SQL Server 2012;没有序号位置不重要,我只需要在“SplitID”字段中添加“原始ID”即可跟进ID(PK)。
-
@Zhorov:你是如何格式化我的表格的???
-
你可以用它来写漂亮的表格:senseful.github.io/text-table
标签: sql-server split