日期:2014-05-17 浏览次数:20404 次
select ID,len(Name)-len(replace(Name,',',''))+1 from tb
--构建测试数据
create table #TB(ID INT,NAME VARCHAR(10))
INSERT INTO #TB select '1', 'A'
union all select '2', 'B'
union all select '3', 'A,B,C'
union all select '4', 'A,B'
union all select '5', 'C'
union all select '6', 'B'
--创建存储过程
alter proc SplitTable
@table varchar(50),
@Splitcolumn varchar(50),
@flag char(1)
as
set nocount on
declare @sql varchar(max)
set @sql = '
SELECT a.* , SUBSTRING(a.'+@Splitcolumn+', number, CHARINDEX('''+@flag+''', a.'+@Splitcolumn+' + '''+@flag+''', number) - number) AS element
FROM '+@table+' a
JOIN master..spt_values
ON number <= LEN(a.'+@Splitcolumn+') and type=''p''
AND SUBSTRING('''+@flag+''' + a.'+@Splitcolumn+', number, 1) = '''+@flag+''' and SUBSTRING(a.'+@Splitcolumn+', number, CHARINDEX('''+@flag+''', a.'+@Splitcolumn+' + '''+@flag+''', number) - number) <>''''
'
exec (@sql)
--解决方案
select top(0)*,cast(null as varchar(500)) as element into #tA from #Tb
insert into #ta exec splitTable '#TB','NAME',','
select element,count(element)as num from #ta group by element
/*element