select
    a.表名,a.字段名,b.公司名
from 
    (select distinct 表名,字段名 from 表) a
left join 
    (select * from 表 where 公司名=@company) b 
on 
    a.字段名=b.字段名 
    and
    a.公司名=b.公司名

解决方案 »

  1.   

    create table os(表名 varchar(50),字段名 varchar(50),公司名 varchar(50))
    insert into os select 'tlb1','fld1','aaa'
    insert into os select 'tlb1','fld2','bbb'
    insert into os select 'tlb1','fld1',null
    insert into os select 'tlb1','fld2',nullcreate proc wsp
    @c varchar(50)=null
    as
    if(isnull(@c,'')='')
    select * from os where isnull(公司名,'')=isnull(@c,'')
    else
    select * from os where 公司名=@c 
    union all
    select a.* from os a,os b where b.公司名=@c and a.字段名<>b.字段名 and isnull(a.公司名,'')=''
    exec wsp exec wsp 'aaa'
      

  2.   

    当我登录公司为aaa时,就生成以下两条记录 
    tlb1  fld1 aaa 
    tlb1  fld2 null   -----这条怎么来的? 还是 tlb1  fld1 null
      

  3.   

    select a.表名,a.字段名,b.公司名
    from (select distinct 表名,字段名 from 表) a
    left join 
         (select * from 表 where 公司名=@company) b 
    on  a.字段名=b.字段名 and a.公司名=b.公司名
      

  4.   

    抱歉,写错了联接条件里的一个字段名,借用pt1314917的数据:create table os(表名 varchar(50),字段名 varchar(50),公司名 varchar(50))
    insert into os select 'tlb1','fld1','aaa'
    insert into os select 'tlb1','fld2','bbb'
    insert into os select 'tlb1','fld1',null
    insert into os select 'tlb1','fld2',null
    declare @company varchar(20)
    set @company='ccc'select
        a.表名,a.字段名,b.公司名
    from 
        (select distinct 表名,字段名 from os) a
    left join 
        (select * from os where 公司名=@company) b 
    on 
        a.字段名=b.字段名 
        and
        a.表名=b.表名/*
    表名        字段名        公司名         
    ----------- ------------- ----------- 
    tlb1        fld1          NULL
    tlb1        fld2          NULL
    */drop table os
      

  5.   

    select a.表名,a.字段名,b.公司名 from 
    (select distinct 表名,字段名 from os) a
    left join (select * from os where 公司名='aaa') b
    on a.表名=b.表名 and a.字段名=b.字段名
      

  6.   

    要是还有一个字段,就不行了如
    create table os(表名 varchar(50),字段名 varchar(50),公司名 varchar(50),字段1 varchar(50))
    insert into os select 'tlb1','fld1','aaa','1'
    insert into os select 'tlb1','fld2','bbb','2'
    insert into os select 'tlb1','fld1',null,'3'
    insert into os select 'tlb1','fld2',null,'4'
    declare @company varchar(20)
    set @company='ccc'select
        a.表名,a.字段名,b.公司名,b.字段1
    from 
        (select distinct 表名,字段名 from os) a
    left join 
        (select * from os where 公司名=@company) b 
    on 
        a.字段名=b.字段名 
        and
        a.表名=b.表名/*
    表名        字段名        公司名           字段1
    ----------- ------------- ----------- 
    tlb1        fld1          NULL        1
    tlb1        fld2          NULL        null(错的)
    */drop table os