这样的函数怎么写? 把多个ID的值合并成字符串
函数大概如下,但存在错误的,主要让大家能理解我需要要的函数:
create function hs_xuezhi(@nlist varchar(8000))
returns varchar(8000)
as
begin
declare @re varchar(8000)
set @re=''
select @re=@re+','+ rtrim(j2) from xuezhi where nid in (@nlist)
return @re
end
调用函数:
select hs_xuezhi('1,2,3')
这样的函数 怎么写啊 ?
我尝试用下面改进的函数,系统就提示错误:
消息 557,级别 16,状态 2,第 1 行
只有函数和扩展存储过程才能从函数内部执行。
函数内容如下:
create function hs_xuezhi(@nidlist varchar(300))
returns varchar(300)
as
begin
declare @csql nvarchar(4000),@re varchar(300)
set @re=N''
set @csql=N'select @re = @re+'',''+ rtrim(j2) from xuezhi where nid in ('+ @nidlist + ')'
exec sp_executesql @csql,N'@re varchar(300) output',@re output;
return @re
end
好像是 函数中不能用 sp_executesql ??
那么 该怎么修改,能实现我要的结果呢 ??
[解决办法]
create function hs_xuezhi(@nlist varchar(8000))--调用
returns varchar(8000)
as
begin
declare @re varchar(8000)
set @re=''
select @re=@re+','+ rtrim(j2) from xuezhi where charindex(','+cast(nid as varchar)+',',','+@nlist+',')>0
return @re
end
WITH a1 ([姓名],[学科ID]) AS
(
SELECT '张三','1,2,3' UNION ALL
SELECT '李四','2,5' UNION ALL
SELECT '王五','6'
)
,a2 ([学科ID],[名称]) AS
(
SELECT 1,'语文' UNION ALL
SELECT 2,'数学' UNION ALL
SELECT 3,'英语' UNION ALL
SELECT 4,'计算机原理' UNION ALL
SELECT 5,'实用软件' UNION ALL
SELECT 6,'地理' UNION ALL
SELECT 7,'历史'
)
SELECT *,STUFF(
(SELECT ','+[名称] FROM a2 WHERE CHARINDEX(','+RTRIM([学科ID])+',',+','+a.[学科ID]+',')>0 FOR XML PATH(''))
,1,1,'')
FROM a1 a