日期:2014-05-18 浏览次数:20609 次
create table t1(c1 int, u1 int) insert into t1 select 1, 2 union all select 1, 3 union all select 2, 2 union all select 1, 5 -- 第一个问题:检索 select t.c1, left( cast((select cast(u1 as varchar(1))+',' from t1 where c1=t.c1 for xml path('')) as varchar(10)), len(cast((select cast(u1 as varchar(1))+',' from t1 where c1=t.c1 for xml path('')) as varchar(10)))-1) u1 from t1 t where t.c1=1 group by t.c1 c1 u1 ----------- ---------- 1 2,3,5 (1 row(s) affected) -- 第二个问题是:插入新数据集 declare @c int,@u varchar(10) -- 传入的参数 select @c=1,@u='2,3,7,9' insert into t1 select t2.* from (select a.c0, substring(a.u0,b.number,charindex(',',a.u0+',',b.number)-b.number) u0 from (select @c c0,@u u0) a inner join master.dbo.spt_values b on b.[type]='p' and substring(','+a.u0,b.number,1) = ',') t2 left join t1 on t2.c0=t1.c1 and t2.u0=t1.u1 where t1.u1 is null select * from t1 where c1=1 c1 u1 ----------- ----------- 1 2 1 3 1 5 1 7 1 9 (5 row(s) affected)