分解字符串到一个表-- split a string into a table
CREATE FUNCTION [dbo].[Split]
(
@c VARCHAR(4000),
@seperate VARCHAR(2)
)
RETURNS
@t TABLE(col VARCHAR(50))
AS
BEGIN
DECLARE @idx int
SET @idx = charindex(@seperate,@c);
WHILE (@idx > 0)
BEGIN
INSERT @t(col) VALUES( substring(@c,1,@idx-1) )
SET @c = stuff(@c,1,@idx,'')
SET @idx= charindex(@seperate,@c);
END
INSERT @t(col) VALUES (@c)
RETURN
END
怎样才能 将某个表中的一列组合成字符串呢?用函数, 不用存储过程
CREATE FUNCTION [dbo].[Split]
(
@c VARCHAR(4000),
@seperate VARCHAR(2)
)
RETURNS
@t TABLE(col VARCHAR(50))
AS
BEGIN
DECLARE @idx int
SET @idx = charindex(@seperate,@c);
WHILE (@idx > 0)
BEGIN
INSERT @t(col) VALUES( substring(@c,1,@idx-1) )
SET @c = stuff(@c,1,@idx,'')
SET @idx= charindex(@seperate,@c);
END
INSERT @t(col) VALUES (@c)
RETURN
END
怎样才能 将某个表中的一列组合成字符串呢?用函数, 不用存储过程
id value
----- ------
1 aa
1 bb
2 aaa
2 bbb
2 ccc需要得到结果:
id values
------ -----------
1 aa,bb
2 aaa,bbb,ccc即, group by id, 求 value 的和(字符串相加)这个问题的一般处理方法是, 写一个聚合函数:
create function dbo.f_str(@id int)
returns varchar(8000)
as
begin
declare @r varchar(8000)
set @r=''
select @r=@r+','+value from tb where id=@id
return stuff(@r,1,1,'')
end
go-- 调用函数
select id, values=dbo.f_str(id) from tb group by id
sql的函数参数不支持表变量,所以不能写出真正反过来的函数,必须借助有一个固定表
return stuff(@r,1,1,'')
可能出错,最好改成
if @r<>''
set stuff(@r,1,1,'')
return @r
吹毛求疵了