这样的SQL语句怎么写?

mingjunr 2006-02-07 12:11:57
有一个表
ID Name Age
1 小王 28
2 小李 24
3 小张 26
4 小周 27
我写一个SQL,把大于25的姓名取出放在一个字段里,
结果像这样一个字符串:小王,小张,小周
大侠们赶快来抢分啊,谢谢 了

如果能写一个函数更好
...全文
102 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
samfeng_2003 2006-02-07
  • 打赏
  • 举报
回复
create table t
(id int,name varchar(20),age int)

insert t
select 1,'小王',28 union all
select 2,'小李',24 union all
select 3,'小张',26 union all
select 4,'小周',27
go

create function f_he(@col1 int,@col2 int)
returns varchar(50)
as
begin
if @col1>@col2
return(null)
declare @sql varchar(50)
set @sql=''
select @sql=@sql+','+name from t where age>@col1
return(stuff(@sql,1,1,''))
end
go


select *,dbo.f_he(25,age) as newfield from t

drop function dbo.f_he
drop table t

id name age newfield
----------- -------------------- ----------- --------------------------------------------------
1 小王 28 小王,小张,小周
2 小李 24 NULL
3 小张 26 小王,小张,小周
4 小周 27 小王,小张,小周

(所影响的行数为 4 行)
mingjunr 2006-02-07
  • 打赏
  • 举报
回复
谢谢了
samfeng_2003 2006-02-07
  • 打赏
  • 举报
回复
create table t
(id int,name varchar(20),age int)

insert t
select 1,'小王',28 union all
select 2,'小李',24 union all
select 3,'小张',26 union all
select 4,'小周',27
go

create function f_he(@col int)
returns @t table(col varchar(50))
as
begin
declare @sql varchar(50)
set @sql=''
select @sql=@sql+','+name from t where age>@col
insert @t values (stuff(@sql,1,1,''))
return
end
go


select * from dbo.f_he(25)

drop function dbo.f_he
drop table t

col
--------------------------------------------------
小王,小张,小周

(所影响的行数为 1 行)
a97191 2006-02-07
  • 打赏
  • 举报
回复
up

34,576

社区成员

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

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