日期:2014-05-20  浏览次数:20834 次

SQL字符串连接
当前有一数据表,表结构如下:
ID    Name   Type
1      A       S
2      B       S
3      C       S
4      D       M

现在想把Type=“M”的数据的"Name"值连接成一个字符串,如:A;B;C

请问如何实现?

------解决方案--------------------
DECLARE @temp nvarchar(MAX)
SET @temp = '';
SELECT @temp = @temp  + Name + ';' FROM tableName WHERE Type=M;
PRINT @temp
这样可以实现,不过最后会多出一个分号。
------解决方案--------------------

Create table T1  --创建表
(
    ID Int not null primary key identity(1,1),  
    Name  Varchar(50),   
    Type Varchar(50),         
);

Insert Into T1
Select 'A','S' Union all
Select 'B','S' Union all
Select 'C','S' Union all
Select 'D','E' Union all
Select 'E','E' 

--创建自定义函数
Create Function CSDN_T1
(
   @mx Varchar(50)
)
Returns Varchar(8000)
as 
Begin
Declare @str Varchar(8000)
Set @str = ''
Select @str = @str + cast(Name as Varchar(50))  + ';' from T1 Where [Type] = @mx 
Set @str = SubString(@str,1,len(@str)-1)
Return(@str)
End
 
--调用自定义函数得到结果
select Distinct Type,dbo.CSDN_T1(Type) as Name From T1 ;


------解决方案--------------------

with t as
(
   select (select Name+',' from table where Type='M' for xml path('')) as Name