看看这条语句怎么写,在线等

szc21 2007-10-18 12:49:02
表 AB 字段 id aa
1 aaaa
2 bbbb
3 cccc
其中AB表中有很多记录,我想随机取出5条,并把字段aa组合成一个以‘,’分隔的长字符串,更新到另一表中,不知道怎样写好

create proc xxxxxxx
as
begin
declare @bbb varchar(200)
--随机选出记录并组合成字符串传给变量@bbb 例如:aaaa,bbbb,cccc,(这部分怎么写?)
update ab2 set aa = @bbb where ....
end
...全文
161 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
fcuandy 2007-10-18
  • 打赏
  • 举报
回复
declare @linkSTR varchar(200)
select top 5 @linkSTR=isnull(@linkSTR,'') + ',' + aa from ab order by newid()
update ab2 set aa=stuff(@linkSTR,1,1,'') where ...
chuifengde 2007-10-18
  • 打赏
  • 举报
回复
create proc xxxxxxx
as
begin
declare @bbb varchar(200)
select @bbb=isnull(@bbb+',','')+ aa from (select top 5 bb from ab order by newid()) bb
update ab2 set aa = @bbb where ....
end
火星求索 2007-10-18
  • 打赏
  • 举报
回复

create proc GetTop
as
begin
declare @Row int
set @Row=0
while @Row < 5
begin
declare @sql nvarchar(200)
set @sql=''
select @sql=@sql+[name] from (select top 5 * from tb order by newid()) t
update ttb set id = @Row
set @Row=@Row+1
end
end
szc21 2007-10-18
  • 打赏
  • 举报
回复
谢谢各位
dawugui 2007-10-18
  • 打赏
  • 举报
回复
create table tb(id varchar(10),username varchar(10))
insert into tb values('1', '123')
insert into tb values('2', '234')
insert into tb values('3', 'hell')
go

declare @a varchar(5000),@b varchar(5000)
select @a='',@b=''
select @a=@a+','+rtrim(id),@b=@b+','+username from tb
select 'id',stuff(@a,1,1,'') union select 'username',stuff(@b,1,1,'')


drop table tb

/*
-------- --------------
id 1,2,3
username 123,234,hell

(所影响的行数为 2 行)
*/
火星求索 2007-10-18
  • 打赏
  • 举报
回复

--环境
create table tb(id int identity(1,1),[name] char(10))
insert into tb select 'a'
insert into tb select 'b'
insert into tb select 'c'
insert into tb select 'd'
insert into tb select 'e'
insert into tb select 'f'
go
create table ttb(id int identity(1,1),[name] char(100))
select * from ttb
delete from ttb
go
--存储过程
create proc GetTop
as
begin
declare @Row int
set @Row=0
while @Row < 5
begin
declare @sql nvarchar(200)
set @sql=''
select @sql=@sql+[name] from (select top 5 * from tb order by newid()) t
insert ttb select name = @sql
set @Row=@Row+1
end
end

--删除环境
drop table ttb
go
drop table tb
go
drop proc GetTop
中国风 2007-10-18
  • 打赏
  • 举报
回复


declare @s nvarchar(1000)
select @s=isnull(@s+',','')+quotename(Name) from (select top 5 Name from 表名 order by newiD())t
update 表名 set Name=@s where .......


lass_name 2007-10-18
  • 打赏
  • 举报
回复
declare @str varchar(200)
select @str = isnull(@str+',','')+aa from (select top 5 * from AB) bb
print @str
这样就可以查出你要的数据了
pt1314917 2007-10-18
  • 打赏
  • 举报
回复
declare @sql varchar(1000)
select @sql=isnull(@sql+',','')+aa from (select top 5 * from ab order by newid())a
update ab2 set aa=@sql where ......

34,837

社区成员

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

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