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

列が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 に答える