返回拼合字符串

调用方法:
select [dbo].[GetAdTopic] '1,2,3,4,5,6' ,','

返回对应表中对应ID的其它字段拼合字符串
如:
名称1,名称2,名称3,名称4,名称5,名称6


ALTER   FUNCTION [dbo].[GetAdTopic]
 (@TopicIDs VARCHAR(50),  --待拆分的字符串
  @markStr varchar(100))   --拆分标记,如','

-- 返回广告主题名称
-- 2008.01.24
-- 杨鑫

RETURNS VARCHAR(50)

AS
BEGIN
declare @s varchar(50)
    set @s=''

  declare @strlen int,@postion int,@start int,@sublen int,@TEMPstr varchar(200),@TEMPid int
  SELECT @strlen=LEN(@TopicIDs ),@start=1,@sublen=0,@postion=1,@TEMPstr='',@TEMPid=0
 
  if(RIGHT(@TopicIDs ,1)<>@markStr )
  begin
    set @TopicIDs  = @TopicIDs  + @markStr
  end
  WHILE((@postion<=@strlen) and (@postion !=0))
  BEGIN
   IF(CHARINDEX(@markStr,@TopicIDs ,@postion)!=0)
  BEGIN
    SET @sublen=CHARINDEX(@markStr,@TopicIDs ,@postion)-@postion;
   END
   ELSE
   BEGIN
   SET @sublen=@strlen-@postion+1;
 
   END
   IF(@postion<=@strlen)
   BEGIN
   SET @TEMPid=@TEMPid+1;
    SET @TEMPstr=SUBSTRING(@TopicIDs ,@postion,@sublen);
  

    select @s=@s+','+[TopicName] from  AdTopic WHERE [TopicID]=@TEMPstr

 
    IF(CHARINDEX(@markStr,@TopicIDs ,@postion)!=0)
    BEGIN
     SET @postion=CHARINDEX(@markStr,@TopicIDs ,@postion)+1
    END
    ELSE
    BEGIN
     SET @postion=@postion+1
    END
   END
  END

 set @s=SubString(@s,2,100)
 RETURN @s
END

posted @ 2009-03-05 00:09  YaSin  阅读(161)  评论(0)    收藏  举报