本帖最后由 weisai 于 2010-02-08 21:57:11 编辑

解决方案 »

  1.   

    实际上数据横表名是一样的,只是现在有多个数据库,每个数据库的数据横表的从第2列开始,列名和列数不一样,每个数据库都有其结构一样的基础表 。
    要求一个SQL语句,对不同数据库查询得出结果
      

  2.   

    只能针对你需要的表来写SQL。
      

  3.   

    select Fnum, 
    (select 值 from 基础表 where FID=F1),
    (select 值 from 基础表 where FID=F2)
    from 数据横表1
      

  4.   

    一个是数据库太多,二是横表的列会动态增加(当然列值肯定在基础表FID中)有没有方法动态识别一个表中的列名
      

  5.   

    这样看行不?
    declare @tb table (FID int,值  nchar(1))insert into @tb
    select 0,'*' union all 
    select 1,'红' union all 
    select 2,'蓝' union all 
    select 3,'绿 ' drop table 数据横表1
    create table 数据横表1 (Fnum nchar(3),F1  int,F2  int)
    insert into  数据横表1 
    select '001',0,1 union all 
    select '002',2,3 union all 
    select '003',0,0 declare @strSql nvarchar(4000)
    declare @tablename nvarchar(20)
    set @strSql=''
    set @tablename='数据横表1'
    select @strSql=@strSql+'(select 值 from  @tb where  FID=t1.'+[name]+') as '+[name]+',' 
    from syscolumns where id =(
    select id from sysobjects  
    where  xtype='u' and name=@tablename)
    --select ' select Fnum,'+left(@strSql,len(@strSql)-1)+'  from '+@tablename+' as t1'
    exec (' select Fnum,'+left(@strSql,len(@strSql)-1)+'  from '+@tablename+' as t1')
      

  6.   


    create table 基础表(FID int,值 varchar(5))insert 基础表
    select 0,'*' union all
    select 1,'红' union all
    select 2,'蓝' union all
    select 3,'绿' create table tt(fnum char(3),f1 int,f2 int,f3 int)
    insert tt
    select '001',1,0,1 union all
    select '002',2,3,0create table tt1(fnum char(3),f1 int,f2 int)
    insert  tt1
    select '001',0,1 union all
    select '002',2,3 union all
    select '003',0,0DECLARE @SQL VARCHAR(8000),@table_name varchar(20)
    set @table_name='tt1'
    select 
      @sql=isnull(@sql+',','')+'(select 值 from 基础表 where FID=a.['+name+']) as ['+name+']'
    from sys.syscolumns WHERE id=OBJECT_ID(@table_name)
    and name !='fnum'select @sql='select fnum,'+@sql+ 'from '+@table_name+' a'exec(@sql)
      

  7.   

    哇楼上说得正是- -0
    俺忽略了,,
    fnum了
      

  8.   

    试过 ldslove 的方法,应该可以,结贴