2011-09-23 62 views
0

如何在SQL中將拆分管道分隔的字符串值分隔到不同的列中,例如:SQL 2008 - 管道分隔字符串拆分

2008 | 1245 | 0 | 1004 | 1224 | 0 |

FirstValue SecondValue ThirdValue ForthValue FifthValue SixthValue 
2008  1245  0   1004   1224   0 

使用一個簡單的選擇腳本。

謝謝

+0

嗯..什麼是SIM卡? –

+0

在這種情況下什麼是「sim」? –

+0

你可以[分割] [1]字符串。 [1]:http://stackoverflow.com/questions/314824/t-sql-opposite-to-string-concatenation-how-to-split-string-into-multiple-recor – PiTheNumber

回答

1

試用

CREATE 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 
GO 
--Test 
select * from fnSplit('2008|1245|0|1004|1224|0|','|')