在SQL Server中拆分逗号分隔值(php爆炸像)

时间:2014-01-26 09:27:48

标签: sql sql-server sql-server-2005 explode

我在表格中有一个名为Tags的列,其中包含逗号分隔值,如

select 'hot,sweet,wow,cool' as Tags

问题是我想用逗号分解它,并在下面显示它

Tags
-----
hot
sweet
wow
cool

可能的?

3 个答案:

答案 0 :(得分:5)

简单的查找和替换将做解决方案..虽然看起来很脏但仍然有效:)

declare @dynamic_sql as varchar(2000)
select 
@dynamic_sql=REPLACE  ('SELECT '''+ 'hot,sweet,wow,cool' , ',' , ' '' as tags UNION  SELECT '' ' )+''' as tags'
exec(@dynamic_sql)

输出

tags
 cool
 sweet 
 wow 
hot 

答案 1 :(得分:2)

0)我会规范化数据库。

1)在SQL Server Central上,你可能会发现Jeff Moden撰写的一篇关于这个主题的非常好的文章:Tally OH! An Improved SQL 8K “CSV Splitter” Function

2)我会使用基于XML的方法:

DECLARE @SourceString VARCHAR(1000);
SET @SourceString = 'ho<t,sweet,wow,cool';

DECLARE @x XML;
SET @x = '<r>' + REPLACE((SELECT @SourceString FOR XML PATH('')), ',', '</r><r>') + '</r>';
SELECT  y.XmlCol.value('(text())[1]', 'VARCHAR(1000)') AS Value
FROM    @x.nodes('/r') y(XmlCol);

输出:

Value
-----
ho<t
sweet
wow
cool

答案 2 :(得分:1)

据我所知,事实上的功能是Jeff Moden发现的8k CSV分离器here

CREATE FUNCTION [dbo].[DelimitedSplit8K]
--===== Define I/O parameters
        (@pString VARCHAR(8000), @pDelimiter CHAR(1))
--WARNING!!! DO NOT USE MAX DATA-TYPES HERE!  IT WILL KILL PERFORMANCE!
RETURNS TABLE WITH SCHEMABINDING AS
 RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 1 up to 10,000...
     -- enough to cover VARCHAR(8000)
  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l
;