你是不是用A表的quanbu 存B表的字段名,当VISIBLE为TRUE时,就把B表的这个字段显示出来,如你例中所要的结果便是:
bianhao   yjmc   danwei  
 A厂家    红酒     克      
 A厂家    白酒     斤     如果是这样的话:
declare @str varchar(100),@sql varchar(100)
set @str='a.bianhao'
update a set @str=@str+','+quanbu where visible=true 
set @sql='select distinct '+@str +' from b join a on b.bianhao=a.bianhao and a.visible=true'
exec(@sql)

解决方案 »

  1.   

    to:liuri(璇玑)你好!就是这个意思,A表存放B表的字段名字!上面看不大明白,因为我是在delphi写的sql语句,对于SQL不熟悉!希望你帮我解析一下,我容易理解点,谢谢了!
      

  2.   

    哦!你将liuri(璇玑) 大虾的写成过程就可以了:
    create procedure 名
    @str varchar(100),@sql varchar(100)
    as
    begin
     set @str='a.bianhao'
     update a set @str=@str+','+quanbu where visible=true 
     set @sql='select distinct '+@str +' from b join a on b.bianhao=a.bianhao and a.visible=true'
     exec(@sql)
    --^^^^动态sql
    end
      

  3.   

    如版主所言,做成存储过程,在DELPHI中用ADOSTOREDPROC执行就是了update a set @str=@str+','+quanbu where visible=true 
    是为了得到一个VISIBLE为真的字段列,如在你的例子中就是
    a.bianhao,yjmc,danwei  //a.bianhao,是初始值然后,通过加到@sql,就相当于:
    select distinct a.bianhao,yjmc,danwei from b join a on b.bianhao=a.bianhao and a.visible=true不过这个语句是动态生成的而已
      

  4.   

    在delphi里如果不是用sql存储过程,可以分两步来做,
    1 读出有效的字段名
      select quanbu from a表 where visible=1  //sql server 中的true 应该为bit的1
    2 写动态sql执行数据查询
      看这样的程序能不能满足你的要求
      query1.active := false;
      query1.sql.clear;
      query1.sql.add('select quanbu from a表 where visible =1');
      query1.active := true;
      if not query1.eof then
      begin
        query2.sql.add('select ');
        while not query1.eof do
        begin
          query2.sql.add(query1.fields[0].asstring);
          query1.next;
        end
        query2.sql.add(' from b表');
        query2.open;
      end;  不过这样的效率一定比存储过程的差  不知道是不是你所说的意思了。