数据库列问题

wms05128 2010-09-26 07:25:25
有一数据库表如下:
ID NAME
1 ABC
2 BCD
3 MPD
4 MB
5 LP
要求出NAME列的所有数据,并将数据存入一个字符串,如:ABC,BCD,MPD,MB,LP这样
...全文
28 点赞 收藏 8
写回复
8 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
闹铃 2010-09-26

declare @str varchar(1000);
select @str = coalesce(@str+',','')+ Name from dbo.test;
print @str;
---的确很妙!
回复
闹铃 2010-09-26

use tempdb;
create table dbo.test
(
id int,
name varchar(10)
)
insert into dbo.test
values (1, 'ABC'),
(1, 'BCD'),
(2 ,'MPD'),
(2 ,'MB'),
(2 ,'LP'); --sql server 2008 新增

declare @temp table
(
id int,
name varchar(100)
);
insert into @temp
select distinct id,''
from dbo.test;

declare @id int;
declare @name varchar(10);

declare cur_test cursor for
select id,name from dbo.test;
open cur_test
fetch next from cur_test into @id,@name;
while @@FETCH_STATUS=0
begin
update @temp
set name=name+@name+','
where id=@id;
fetch next from cur_test into @id,@name;
end
close cur_test;
deallocate cur_test;

select ID,left(name,LEN(name)-1)as name
from @temp;

/***

ID name
----------- -----------
1 ABC,BCD
2 MPD,MB,LP

(2 行受影响)

***/
回复
gw6328 2010-09-26

declare @xml xml
select [name]+',' from tb for xml path('')
select left(cast(@xml as nvarchar(max)),len(cast(@xml as nvarchar(max)))-1)
回复
ws_hgo 2010-09-26
[Quote=引用 4 楼 dawugui 的回复:]

太快了撒。
[/Quote]

哈哈
老D吃饭了没有啊
回复
dawugui 2010-09-26
太快了撒。
回复
dawugui 2010-09-26
[Quote=引用 2 楼 ws_hgo 的回复:]
兄弟你的结贴率
很低
注意结贴
[/Quote]哈哈。

----------------------------------------------------
/*如何将一列中所有的值一行显示
数据源
a
b
c
d
e
结果
a,b,c,d,e
*/

create table tb(col varchar(20))
insert tb values ('a')
insert tb values ('b')
insert tb values ('c')
insert tb values ('d')
insert tb values ('e')
go

--方法一
declare @sql varchar(1000)
set @sql = ''
select @sql = @sql + t.col + ',' from (select col from tb) as t
set @sql='select result = ''' + left(@sql , len(@sql) - 1) + ''''
exec(@sql)
/*
result
----------
a,b,c,d,e,
*/

--方法二
declare @output varchar(8000)
select @output = coalesce(@output + ',' , '') + col from tb
print @output
/*
a,b,c,d,e
*/

drop table tb
回复
ws_hgo 2010-09-26
兄弟你的结贴率
很低
注意结贴
回复
ws_hgo 2010-09-26
if object_id('A') is not null drop table A
go
create table A
(
ID int identity(1,1) primary key,
Name varchar(20)
)
insert into A select 'ABC'
insert into A select 'BCD'
insert into A select 'MPD'
insert into A select 'MB'
insert into A select 'LP'
go


create function dbo.f_str1()
returns varchar(1000)
as
begin
declare @str varchar(1000)
select @str = isnull(@str + ',' , '') + Name from A
return stuff(@str,1,1,'')
end


select distinct dbo.f_str1() from A


----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
BC,BCD,MPD,MB,LP

(1 行受影响)
回复
发帖
疑难问题
创建于2007-09-28

2.1w+

社区成员

MS-SQL Server 疑难问题
申请成为版主
帖子事件
创建了帖子
2010-09-26 07:25
社区公告
暂无公告