我有类似
的东西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
答案 0 :(得分: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
);
答案 1 :(得分:2)
你可以用这种方式做到这一点。
测试数据
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 :(得分:2)
试试这段代码。,(参考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
答案 3 :(得分: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