我的string
格式为'S1CW3733|1050105000224,S1CW4923|1050105000009'
我在SQL中有一个函数,它以格式转换它
item
S1CW3733|1050105000224
S1CW4923|1050105000009
可以这样做吗? (多栏)
item item2
S1CW3733 1050105000224
S1CW4923 1050105000009
我的功能: -
ALTER Function [dbo].[fnSplit]
(
@sInputList Varchar(8000), -- List of delimited items
@sDelimiter VarChar(8000) = ',' -- delimiter that separates items
)
Returns @List Table (item VarChar(8000))
Begin
Declare @sItem VarChar(8000)
While CharIndex(@sDelimiter,@sInputList,0) <> 0
Begin
Select
@sItem=RTrim(LTrim(SubString(@sInputList,1,CharIndex(@sDelimiter,@sInputList,0)-1))),
@sInputList=RTrim(LTrim(SubString(@sInputList,CharIndex(@sDelimiter,@sInputList,0)+Len(@sDelimiter),Len(@sInputList))))
If Len(@sItem) > 0
Insert Into @List Select @sItem
End
If Len(@sInputList) > 0
Insert Into @List Select @sInputList -- Put the last item in
Return
End
答案 0 :(得分:2)
如果你只有两列,你总是可以做到这一点
select
left(f.item, c.c - 1) as item1,
right(f.item, len(f.item) - c.c) as item12
from dbo.fnSplit('S1CW3733|1050105000224,S1CW4923|1050105000009', ',') as f
outer apply (select charindex('|', f.item) as c) as c
我没有检查charindex!= 0,所以你可以添加这个检查。
但是,如果您有多个以“|”分隔的列,我认为没有动态SQL的方法可以做到这一点
答案 1 :(得分:1)
另一种方式。您可以修改您的功能。该函数必须期望附加参数 - 返回分割字符串的哪一部分。所以在你的sql请求中你会做这样的事情:
select
fnSplit(item, ',', '|', 0) as item_left,
fnSplit(item, ',', '|', 1) as item_right
from
mytable
在这种情况下,该函数必须看起来像
ALTER Function [dbo].[fnSplit]
(
@sInputList Varchar(8000), -- List of delimited items
@sDelimiter1 VarChar(8000) = ',', -- delimiter that separates items
@sDelimiter2 VarChar(8000) = '|', -- delimiter that separates splitted item
@which_part int = 0 -- if 0 return left part, 1 -right part
)
Returns VarChar(8000)
... business login here