MS SQL Server中根据某一字段内容合并多个字段
在MS SQL的日常应用中,字段的查询、合并等操作非常常见,本文总结了一下如何将具有同一个字段值的其他字段进行合并。
方法一:自定义函数并调用
1 create function [dbo].[fn_get_column_value] 2 ( 3 @id varchar(10), 4 @name varchar(10) 5 ) 6 returns varchar(1000) 7 as 8 begin 9 declare @value varchar(1000) 10 set @value='' 11 select @value=@value+','+name from table_name 12 where id=@id 13 return stuff(@value,1,1,'') 14 end
方法二:利用系统函数for xml path
1 create table table_tb (id int,name varchar(10)) 2 insert into table_tb values(1,'aa') 3 insert into table_tb values(1,'bb') 4 insert into table_tb values(2,'cc') 5 insert into table_tb values(2,'dd') 6 insert into table_tb values(2,'ee') 7 go 8 select id,[value]=stuff((select ','+[value] from table_tb where id=t.id for xml path('')),1,1,'') 9 from table_tb t 10 group by id
方法三:建立该字段游标,循环合并字符串,该方式较为繁琐,本文不做推荐。
浙公网安备 33010602011771号