1

我有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
4

2 回答 2

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 就没有办法做到这一点

于 2012-11-17T10:55:24.107 回答
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
于 2012-11-17T11:00:22.893 回答