例如:
table字段为:tableID(nchar)
查询结果为不确定的多条:
tableID
T1
T2
T3
T4
……
如何用一条SQL语句将这些记录合并为一个字段,值为:'T1T2T3……'
create table t
(tableid nchar(30))
insert t
select 'T1' union all
select 'T2' union all
select 'T3' union all
select 'T4' union all
select 'T5' union all
select 'T6'
go
create function f_he()
returns @t table(col varchar(50))
as
begin
declare @sql varchar(50)
set @sql=''
select @sql=@sql+ltrim(rtrim(tableid)) from t
insert @t values (@sql)
return
end
go
select * from t
select * from dbo.f_he()
drop function f_he
drop table t
col
--------------------------------------------------
T1T2T3T4T5T6
(所影响的行数为 1 行)