T SQL将字符串拆分为行和列

时间:2017-04-19 12:48:47

标签: split

使用Microsoft SQL Server 2005将拆分转换为行和列 输入字符串:

SET @FieldList ='a1~b1~c1~d1~e1 | a2~b2~c2~d2~e2 | ~b3~c3~d3~e3 | a4 ~~ c4~d4~e4 | a5~b5~ C5 ~~ E5 |“6〜b将6〜c取代; 6〜d和6〜e''6 |一个©7〜b $ 7〜C%7〜d * 7〜E7' - 输入

1 个答案:

答案 0 :(得分:0)

DECLARE @FieldList VARCHAR(MAX)
DECLARE
@Pipe CHAR(1)
,@逗号CHAR(1) ,@ Pos INT
,@ Pos1 INT
,@ List VARCHAR(MAX) ,@ BWColumn1 VARCHAR(100)
,@ BWColumn2 VARCHAR(100)
,@ BWColumn3 VARCHAR(100) ,@ BWColumn4 VARCHAR(100)
,@ BWColumn5 VARCHAR(100)

SET @Pipe ='|'
SET @ Comma ='〜'

SET @FieldList ='a1~b1~c1~d1~e1 | a2~b2~c2~d2~e2 | ~b3~c3~d3~e3 | a4 ~~ c4~d4~e4 | a5~b5~ C5 ~~ E5 |“6〜b将6〜c取代; 6〜d和6〜e''6 |一个©7〜b $ 7〜C%7〜d * 7〜E7' - 输入

SET @FieldList = @FieldList +'|'

如果LEN(LTRIM(RTRIM(@FieldList)))> 0 开始     SET @Pos = CHARINDEX(@ Pipe,@ FieldList,1)

IF OBJECT_ID('tempdb..#BWSourceFields') IS NOT NULL
BEGIN
    DROP TABLE #BWSourceFields
END

CREATE TABLE #BWSourceFields(BWColumn1 VARCHAR(100),BWColumn2 VARCHAR(100),BWColumn3 VARCHAR(100),BWColumn4 VARCHAR(100),BWColumn5 VARCHAR(100))     

WHILE( @Pos > 0 )            
BEGIN                        
    --Fetch BWColumn1                    
    SET @List = LTRIM(RTRIM(LEFT(@FieldList, @Pos - 1)))               
    SET @Pos1 = CHARINDEX(@Comma, @List, 1)               
    SET @BWColumn1 = LTRIM(RTRIM(LEFT(@List, @Pos1 - 1)))            
    --Fetch BWColumn2            
    SET @List = LTRIM(RTRIM(SUBSTRING(@List, ( @Pos1 + 1 ), LEN(@List) )))               
    SET @Pos1 = CHARINDEX(@Comma, @List, 1)               
    SET @BWColumn2 = LTRIM(RTRIM(NULLIF(LEFT(@List, @Pos1 - 1), '')))             
    --Fetch BWColumn3            
    SET @List = LTRIM(RTRIM(SUBSTRING(@List, ( @Pos1 + 1 ), LEN(@List) )))               
    SET @Pos1 = CHARINDEX(@Comma, @List, 1)               
    SET @BWColumn3 = LTRIM(RTRIM(NULLIF(LEFT(@List, @Pos1 - 1), '')))             
    --Fetch BWColumn4            
    SET @List = LTRIM(RTRIM(SUBSTRING(@List, ( @Pos1 + 1 ), LEN(@List) )))               
    SET @Pos1 = CHARINDEX(@Comma, @List, 1)               
    SET @BWColumn4 = LTRIM(RTRIM(NULLIF(LEFT(@List, @Pos1 - 1), '')))             
    --Fetch BWColumn5            
    SET @List = LTRIM(RTRIM(SUBSTRING(@List, ( @Pos1 + 1 ), LEN(@List))))               
    SET @Pos1 = CHARINDEX(@Comma, @List, 1)               
    SET @BWColumn5 = LTRIM(RTRIM(SUBSTRING(@List, ( @Pos1 + 1 ), LEN(@List))))  


    INSERT INTO #BWSourceFields(BWColumn1,BWColumn2,BWColumn3,BWColumn4,BWColumn5) VALUES (@BWColumn1,@BWColumn2,@BWColumn3,@BWColumn4,@BWColumn5)

    SET @FieldList = RIGHT(@FieldList, LEN(@FieldList) - @Pos)               
    SET @Pos = CHARINDEX(@Pipe, @FieldList, 1)                                     
END --End While

END

SELECT * FROM #BWSourceFields