create table tb (a varchar(10),b varchar(10))
insert tb
select '2009', 'AA' union all
select '2009', 'BB' union all
select '2008', 'CC' union all
select '2007', 'XX' union all
select '2009', 'HH' union all
select '2008', 'DD' union all
select '2007', 'SS' union all
select '2006', 'GG'
go
select * from tb
CREATE FUNCTION dbo.f_str(@col1 varchar(10))
RETURNS varchar(100)
AS
BEGIN
DECLARE @re varchar(100)
SET @re=''
SELECT @re=@re+','+CAST(b as varchar)
FROM tb
WHERE a=@col1
RETURN(STUFF(@re,1,1,''))
END
GO
select a,dbo.f_str(a)[b] from tb group by a
a b
---------- -------------------
2006 GG
2007 XX,SS
2008 CC,DD
2009 AA,BB,HH
(所影响的行数为 4 行)
拆分:
IF OBJECT_ID('tb') IS NOT NULL
DROP TABLE tb
GO
CREATE TABLE tb (id INT,col VARCHAR(30))
INSERT INTO tb VALUES (1,'aa,bb')
INSERT INTO tb VALUES (2,'aaa,bbb,ccc')
go
--1.2000/2005通用方法
SELECT
a.id,
col=SUBSTRING(a.col,number,CHARINDEX(',',a.col+',',number)-b.number)
FROM tb a
JOIN master..spt_values b
ON b.type='p'
--AND SUBSTRING(','+a.col,b.number,1)=',' --用此条件或下面的条件均可
AND CHARINDEX(',',','+a.col,number)=number
--2.2005以上新方法:
SELECT a.id,b.col
FROM (SELECT id,col=CAST('<v>'+REPLACE(col,',','</v><v>')+'</v>' AS xml) FROM tb) a
OUTER APPLY (SELECT col=T.C.value('.','varchar(50)') FROM a.col.nodes('/v') AS T(C)) b
--结果:
/*
id col
----------- --------------------------------------------------
1 aa
1 bb
2 aaa
2 bbb
2 ccc
(5 行受影响)
*/