现有如下这张表:   
  create   table   LT_FORM_TABLE   (   
      ID   INT,   
s1 VARCHAR(255)  
      tableName   VARCHAR(255)   
  )   
  tableName字段里存储的都是如下形式的数据:   
  LT_FROM_TABLE_1   
  LT_FROM_TABLE_2   
  LT_FROM_TABLE_3   
  LT_FROM_TABLE_4   
  ....   
  以此类推,这些数据其实都是数据库中创建的新表,每个表都有固定字段如下:   
  id   int,   
  admin   int   
  workflowID   int   
    
  现在我希望用一个查询查出所有这些表中admin=1的纪录   
    
  本来可以用union解决这个问题   
  select   id,admin   from   lt_form_table_1   union   
  select   id,admin   from   lt_form_table_2   union   
  select   id,admin   from   lt_form_table_3   union   
  .....   
    
  但是现在的问题是我根本无法知道lt_form_table_*这种样式的表有几张,表名只能去lt_form_table中查,这个问题怎么解决啊?
最后的效果应该是select s1,(select dd from tableName) as ss2  where ...只用一个sql语句;不要使用存储过程等。多语句;
不知道是否可以实现

解决方案 »

  1.   

    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([tablename] varchar(15))
    insert [tb]
    select 'LT_FROM_TABLE_1' union all
    select 'LT_FROM_TABLE_2' union all
    select 'LT_FROM_TABLE_3' union all
    select 'LT_FROM_TABLE_4'
     
    declare @sql varchar(8000)
    select
      @sql=isnull(@sql+' union all ','')+'select id,admin from ['+tablename+']'
    from tbprint @sql--exec (@sql)/**
    select id,admin from [LT_FROM_TABLE_1] 
    union all 
    select id,admin from [LT_FROM_TABLE_2] 
    union all 
    select id,admin from [LT_FROM_TABLE_3] 
    union all 
    select id,admin from [LT_FROM_TABLE_4]**/
      

  2.   

    declare @str varchar(8000)
    select @str=isnull(@str+' union all ','')+
    'select  id,admin  from  + tableName +''
    from LT_FORM_TABLE 
    print @str
    exec(@str)动态执行
      

  3.   

    declare @str varchar(8000)
    select @str=isnull(@str+' union all ','')+
    'select  id,admin  from'  + tableName +''
    from LT_FORM_TABLE 
    print @str
    exec(@str)
      

  4.   

    可能没描述清楚。我不需要把这些表连接起来
    比如 
    LT_FORM_TABLE 
    中有行记录 
    ID s1    tableName 
    1   ww     tb1我需要通过 最终获取到一下语句
    select id,s1,(select ss2 from tb1) as s2  from LT_FORM_TABLE
      

  5.   


    select tableName into # from LT_FORM_TABLE
    update # set tableName='update '+tableName+ 'set select id,admin,workflowID from '+tableName+' where admin=1 union'select tableName from #复制出tableName列的内容,删除最后一个UNION
    执行就可以了。