用函数解决之。代码如下:
--创建一个合并的函数
create function f_hb(@original_id
varchar(10))
returns varchar(8000)
as
begin
declare @str
varchar(8000)
set @str = ''
select @str = @str + ',' +b.word
from similarword a inner join dbo.originalword b on a.similar_id=b.ID
where original_id = @original_id
set @str = right(@str , len(@str) -
1)
return(@str)
End
go
--调用自定义函数得到结果:
select distinct
a.original_id [originalword.ID],b.word [orig_word],dbo.f_hb(a.original_id) as
similar_id
from similarword a inner join dbo.originalword b on
a.original_id=b.ID
go
返回:
originalword.ID orig_word similar_id
--------------- ------------- -----------
101 about
abound
102 abound about
103 beard
beast
104 boast beast
105 beast
beard,boast
SET NOCOUNT ON
CREATE TABLE originalword(id int ,word nvarchar(30))
CREATE
TABLE similarword (ID int ,original_id int,similar_id int)
GO
INSERT INTO
originalword
SELECT 101, 'about' UNION ALL
SELECT 102, 'abound'
UNION ALL
SELECT 103, 'beard' UNION ALL
SELECT 104, 'boast'
UNION ALL
SELECT 105, 'beast'
INSERT INTO similarword
SELECT 1,
101, 102 UNION ALL
SELECT 2, 102,
101 UNION ALL
SELECT 3, 103,
105 UNION ALL
SELECT 4, 105, 103 UNION
ALL
SELECT 5, 104, 105 UNION ALL
SELECT
6, 105, 104
GO
DECLARE @Result
TABLE(id int IDENTITY(1,1),[originalword.ID] int,orig_word
nvarchar(30),similar_word nvarchar(30))
INSERT INTO @Result
([originalword.ID],orig_word) SELECT * FROM originalword
DECLARE @i int
,@j int
,@similar_word nvarchar(200)
SELECT
@i=1,@j=ISNULL(COUNT(1),0) FROM @Result
WHILE @i<=@j
BEGIN
SET @similar_word=''
SELECT
@similar_word=@similar_word+word+',' FROM
(SELECT
B.word FROM similarword A INNER JOIN originalword B ON A.original_id=B.ID
AND EXISTS(SELECT 1 FROM @Result C WHERE
C.[originalword.ID]=A.original_id AND C.ID=@i)) Tmp
IF(ISNULL(@similar_word,'')<>'')
UPDATE @Result
SET similar_word=SUBSTRING(@similar_word,1,LEN(@similar_word)-1) WHERE
ID=@i
SET @i=@i+1
END
SELECT
[originalword.ID],orig_word,similar_word FROM @Result