关于SQL SERVER问题,急求?
现在我查询出某个字段可能有多条记录,我想把这些记录串联起来,用“/”分开,如何实现?
------解决方案--------------------declare @a varchar(1000)
select @a=coalesce(@a+ '/ ', ' ')+ltrim([Field]) from [Table]
select @a
------解决方案--------------------Create Function F_GetRole(@ID Int)
Returns Nvarchar(2000)
As
Begin
Declare @S Nvarchar(2000)
Select @S = ' '
Select @S = @S + '/ ' + Role From B Where ID = @ID
Select @S = Stuff(@S, 1, 1, ' ')
Return @S
End
GO
Select
ID,
Name,
dbo.F_GetRole(ID) As Role
From
A
GO
------解决方案--------------------create table t(id varchar(10))
insert into t
select 'aaa ' union all
select 'dddd ' union all
select 'cccc '
select * from t
---联结所有的ID
declare @str varchar(200)
select @str= ' '
select @str=@str + ID + '/ ' from t
select left(ltrim(@str),len(ltrim(@str))-1)
--drop table t
------解决方案--------------------create table #
(
a int,
b varchar(10)
)
insert into #
select 1, 'aaaa ' union all
select 2, 'bbbb ' union all
select 3, 'cccc ' union all
select 4, 'dddd ' union all
select 5, 'eeee ' union all
select 6, 'ffff '
select *
from #
--进行拼接
declare @str varchar(100)
set @str= ' '
select @str=@str+b+ '/ ' from #
select left(@str,len(@str)-1) as 结果
drop table #
运行后:
(所影响的行数为 6 行)
a b
----------- ----------
1 aaaa
2 bbbb
3 cccc
4 dddd
5 eeee
6 ffff
(所影响的行数为 6 行)
结果
----------------------------------------------------------------
aaaa/bbbb/cccc/dddd/eeee/ffff
(所影响的行数为 1 行)