上边数据是这样的:11我11你12他12你好想变成:11我,你12他,你好createfunctionf_str(@idint)returnsvarchar(4000)asbegindeclare@项目1+','+项目fromaawhereID=@IDreturn(stuff... 上边数据是这样的:
11 我
11 你
12 他
12 你好
想变成:11 我,你
12 他,你好
create function f_str(@id int )
returns varchar(4000)
as
begin
declare @项目1+','+项目 from aa where ID=@ID
return (stuff(@项目1,1,1,''))
end
select ID,dbo.f_str(项目) as 项目 from aa
为什什么查询后提示:varchar转化成int失败 到底哪里有这个int 求哪位大神给看看!!!
上边有一句写错了!应该是:
select @项目1+','+项目 from aa where ID=@ID

在执行最后一句后就会提示varchar转换成int失败 1. 你没有定义“@项目”这个变量
2. select @项目1+','+cast(项目 as nvarchar(20)) from aa whereID=@ID

如果你用的SQL是SQL SERVER 2005及以上版本,不用写这么复杂的
create function f_str(@id int )
returns varchar(4000)
as
begin
declare @returnvalue nvarchar(4000)
SELECT @returnvalue = LEFT(项目,LEN(项目)-1)
FROM
(
SELECT TOP 1 ID,(SELECT 项目 FROM AA B WHERE B.ID = A.ID) 项目
FROM AA A
WHERE ID = @ID
) A

reutrn @returnvalue
end with t1(id,name) as (select 11,'我' union select 11,'你'
union select 12,'他' union select 12,'你好')
, t2 as (select *,row_number() over(partition by id order by id) r from t1)
, t3 as (select r,id, cast(name as varchar(100)) name from t2 where r=1 union all
select t2.r, t2.id, cast((t3.name+','+t2.name) as varchar(100)) from t2 join t3 on t2.id=t3.id and t2.r=t3.r+1)
select t3.id,t3.name
from t3 join (select id,max(r) r from t3 group by id) t4 on t3.id=t4.id and t3.r=t4.r
order by t3.id,t3.name
一点变通都没有了,当然是把t1换成你自己的子查询了,象这样
with t1(id,name) as (select .......)
, t2 as .......
或者根本就没有t1,直接
with t2 as (select *,row_number() over partition by id order by id) r from 数据表)
.....

是这样的   id  和   xm  都有很多的不同项目  怎么实现?  没有那一列是固定的!全部是动态的

没看见我写的是递归么?
with t2 as (select *,row_number() over(partition by id order by id) r from aa)
, t3 as (select r,id, cast(xm as varchar(100)) xm from t2 where r=1 union all
select t2.r, t2.id, cast((t3.xm+','+t2.xm) as varchar(100)) from t2 join t3 on t2.id=t3.id and t2.r=t3.r+1)
select t3.id,t3.xm
from t3 join (select id,max(r) r from t3 group by id) t4 on t3.id=t4.id and t3.r=t4.r
order by t3.id,t3.name
本回答被提问者采纳