日期:2014-05-19  浏览次数:20833 次

过程存储到表的问题
create   table   t(userid   int,configname   varchar(10),configvalue   varchar(10))
insert   into   t   select   1, 'a ', '4 '
insert   into   t   select   1, 'b ', 'ff '
insert   into   t   select   1, 'c ', '100 '
insert   into   t   select   1, 'd ', 'rr '
insert   into   t   select   2, 'a ', '6 '
insert   into   t   select   2, 'b ', 'iiiiii '
insert   into   t   select   2, 'c ', '1000 '
insert   into   t   select   2, 'd ', 'hhh '
insert   into   t   select   3, 'a ', '9 '
insert   into   t   select   3, 'b ', 'fdsa '
insert   into   t   select   3, 'c ', '5555 '
insert   into   t   select   3, 'd ', 'dfdad '

declare   @sql   varchar(8000)
set   @sql= 'select   userid   as   id '
select   @sql=@sql+ ',[ '+configname+ ']=max(case   configname   when   ' ' '+configname+ ' ' '   then   configvalue   end) '
from   t   group   by   configname   order   by   configname
set   @sql=@sql+ '   from   t   group   by   userid '
exec(@sql)

如何把结果保存到表中(行列数不确定),最好是整体复制

------解决方案--------------------
from t group by configname order by configname
-->
into tablename from t group by configname order by configname

------解决方案--------------------
--這樣, 把結果集保存到T2表

create table t(userid int,configname varchar(10),configvalue varchar(10))
insert into t select 1, 'a ', '4 '
insert into t select 1, 'b ', 'ff '
insert into t select 1, 'c ', '100 '
insert into t select 1, 'd ', 'rr '
insert into t select 2, 'a ', '6 '
insert into t select 2, 'b ', 'iiiiii '
insert into t select 2, 'c ', '1000 '
insert into t select 2, 'd ', 'hhh '
insert into t select 3, 'a ', '9 '
insert into t select 3, 'b ', 'fdsa '
insert into t select 3, 'c ', '5555 '
insert into t select 3, 'd ', 'dfdad '

declare @sql varchar(8000)
set @sql= 'select userid as id '
select @sql=@sql+ ',[ '+configname+ ']=max(case configname when ' ' '+configname+ ' ' ' then configvalue end) '
from t group by configname order by configname
set @sql=@sql+ ' into T2 from t group by userid '
exec(@sql)

select * from T2

--result
id a b c d
----------- ---------- ---------- ---------- ----------
1 4 ff 100 rr
2 6 iiiiii 1000 hhh
3 9 fdsa 5555 dfdad

(3 row(s) affected)
------解决方案--------------------
这个动态生成的表的列数和原表t不一样,lz打算纵向合在一起?
------解决方案--------------------
create table t(userid int,configname varchar(10),configvalue varchar(10))
insert into t select 1, 'a ', '4 '