--在网吧写的,没有办法验证有没有错误
--只能一个字段字段的取哦
create table t1
( f1 int,
  f2 int,
  f3 int,
  f4 int
)
create table t2
( t int,
  v int
)insert into t2
select 1 as t , f1 as v
from  t1
where f1 <> 0
union
select 2 as t , f2 as v
from  t1
where f2 <> 0
union
select 3 as t , f3 as v
from  t1
where f3  <> 0
union
select 4 as t , f4 as v
from  t1
where f4 <> 0select * from t2
 
drop table t1
drop table t2

解决方案 »

  1.   

    create table t1
    ( f1 int,
      f2 int,
      f3 int,
      f4 int
    )
    insert t1
    select 50,60,80,90 union
    select 100,150,200,0 uniondrop table t2
    create table t2
    ( t int,
      v int
    )DECLARE @SQL as varchar(8000)
    set @SQL=''
    select @SQL=@SQL + ' select '+ cast(T_Id as varchar) +' as T_Id,' + name + ' from t1 union all' from (select (select count(*) from (select name from syscolumns where id=object_id('t1'))T2 where T2.name<=T1.name) as T_Id,T1.name from (select name from syscolumns where id=object_id('t1')) T1) M
    set @SQL='insert into t2 '+left(@SQL,len(@SQL)-len(' union all'))
    exec (@SQL)
    select * from t2
      

  2.   

    应该是这样DECLARE @SQL as varchar(8000)
    set @SQL=''
    select @SQL=@SQL + ' select '+ cast(T_Id as varchar) +' as T_Id,' + name + ' from t1 where '+ name +'>0  union all' from (select (select count(*) from (select name from syscolumns where id=object_id('t1'))T2 where T2.name<=T1.name) as T_Id,T1.name from (select name from syscolumns where id=object_id('t1')) T1) M
    set @SQL='insert into t2 '+left(@SQL,len(@SQL)-len(' union all'))
    exec (@SQL)