2016-07-06 99 views
2

文件中的行我有類似搜索使用SQL

set @file = 'aaaa,bbbb,cccc,dddd,eeee,ffff' 
SELECT SUBSTRING(@file,CHARINDEX(',',@file)+1, CHARINDEX(',',@file,CHARINDEX(',',@file)+1) -CHARINDEX(',',@file)-1) as My_string 

這將打印出

 My_string 
    ---------------- 
    1|  bbbb 

我如何才能讓列印嗎?

My_string 
------------ 
1| bbbb 
2| cccc 
3| dddd 
4| eeee 
+3

採取這裏看看http://stackoverflow.com/questions/5493510/turning-a-comma-separated-string-into-individual-rows –

+0

的Microsoft SQL Server 2008 R2 –

回答

2

嘗試此代碼。,(Refered從Turning a Comma Separated string into individual rows

declare @file varchar(max) 
set @file = 'aaaa,bbbb,cccc,dddd,eeee,ffff' 

;with tmp(DataItem, Data) 
as (
select LEFT(@file, CHARINDEX(',',@file+',')-1), 
    STUFF(@file, 1, CHARINDEX(',',@file+','), '') 
union all 
select LEFT(Data, CHARINDEX(',',Data+',')-1), 
    STUFF(Data, 1, CHARINDEX(',',Data+','), '') 
from tmp 
where Data > '') 
select DataItem from tmp 
+0

我必須問一些我很好奇的東西,有沒有辦法說'set @file ='aaa,2,1,bbb,3,2,ccc,1,ddd,2,eee,3,2 '',有沒有辦法將'aaa&bbb&ccc&ddd&eee'作爲first_column'2&3&1&2&3'作爲second_column和'1&2&NULL&NULL&2'作爲third_column?我要求這個具體的例子不爲其他人將是字符串字符串整數或詮釋整數字符串,我要求這個例子,你有字符串,整數,詮釋 –

+0

是的,但列入可選列複雜事項。如果你能指出規則,也許在一個新的問題中,我相信我們可以想出一些東西。 –

+0

http://stackoverflow.com/questions/38238242/read-char-double-int-pattern-from-string-in-sql –

2

使用以下函數所使用的Split string functions ..我的一個..

declare @file nvarchar(max) 
set @file = 'aaaa,bbbb,cccc,dddd,eeee,ffff' 

select row_number() over (order by (select null)) as number,b.* 
from 
[dbo].[SplitStrings_Numbers](@file,',') b 

輸出:

number Item 
1 aaaa 
2 bbbb 
3 cccc 
4 dddd 
5 eeee 
6 ffff 

分割字符串源代碼我​​用於完整性:

CREATE FUNCTION dbo.SplitStrings_Numbers 
    (
     @List  NVARCHAR(MAX), 
     @Delimiter NVARCHAR(255) 
    ) 
    RETURNS TABLE 
    WITH SCHEMABINDING 
    AS 
     RETURN 
     (
      SELECT Item = SUBSTRING(@List, Number, 
      CHARINDEX(@Delimiter, @List + @Delimiter, Number) - Number) 
      FROM dbo.Numbers 
      WHERE Number <= CONVERT(INT, LEN(@List)) 
      AND SUBSTRING(@Delimiter + @List, Number, LEN(@Delimiter)) = @Delimiter 
     ); 
2

你可以用XML這樣做。

測試數據

IF OBJECT_ID('tempdb..#TestData') IS NOT NULL DROP TABLE #TestData 
GO 
CREATE TABLE #TestData (StringName varchar(100)) 
INSERT INTO #TestData (StringName) 
VALUES ('aaaa,bbbb,cccc,dddd,eeee,ffff') 

查詢

SELECT Split.a.value('.', 'VARCHAR(100)') AS String 
FROM (SELECT [StringName], 
     CAST ('<M>' + REPLACE(StringName, ',', '</M><M>') + '</M>' AS XML) AS String 
    FROM #TestData) AS A 
CROSS APPLY String.nodes ('/M') AS Split(a); 

結果

String 
aaaa 
bbbb 
cccc 
dddd 
eeee 
ffff 
2
DECLARE @file varchar(255) 
SET @file = 'aaaa,bbbb,cccc,dddd,eeee,ffff' 
DECLARE @X xml 
DECLARE @Split char(1) = ',' 
SELECT @X = CONVERT(xml,'<root><s>' + REPLACE(@file,@Split,'</s><s>') + '</s></root>') 

SELECT [Value] = T.c.value('.','varchar(20)') 
FROM @X.nodes('/root/s') T(c) 

輸出

Value 
aaaa 
bbbb 
cccc 
dddd 
eeee 
ffff