求SQL查询.

zl194 2012-05-09 10:41:27
SQL2000环境。
表结构如下:
列A |列B
1 |张三
1 |李四
1 |王五
1 |赵六

where 列A=1 时 想得到如下的查询结果

张三;李四;王五;赵六;

请教怎样取得。
...全文
56 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
以学习为目的 2012-05-09
  • 打赏
  • 举报
回复
declare @name nvarchar(2000)
select @name = isnull(@name + ';','') + 列B
from 表
where 列A = 1
select @name as name

这个更直观
Mr_Nice 2012-05-09
  • 打赏
  • 举报
回复
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (A int,B nvarchar(4))
insert into [TB]
select 1,'张三' union all
select 1,'李四' union all
select 1,'王五' union all
select 1,'赵六'

select * from [TB]

drop function dbo.f_str

create function dbo.f_str(@id int) returns varchar(100)
as
begin
declare @str varchar(1000)
set @str = ''
select @str = @str + ';' + cast(b as varchar) from tb where a = @id
set @str = right(@str , len(@str) - 1)
return @str
end
go

select a,dbo.f_str(a) from TB group by a

/*
a
----------- ----------------------------------------------------------------------------------------------------
1 张三;李四;王五;赵六

(1 行受影响)
昵称被占用了 2012-05-09
  • 打赏
  • 举报
回复
最后的;也要?

declare @name nvarchar(2000)
select @name = isnull(@name ,'') + 列B + ';'
from 表
where 列A = 1
select @name as name

昵称被占用了 2012-05-09
  • 打赏
  • 举报
回复
declare @name nvarchar(2000)
select @name = isnull(@name + ';','') + 列B
from 表
where 列A = 1
select @name as name
  • 打赏
  • 举报
回复
declare @str varchar(2000)
set @str=''
select @str=@str+B_';' from table
select left(@str,len(@str)-1)

34,588

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧