意思是这样的表名qiyexx
结构:
uid  qiyemc
1     a
2     b
3     c
4     d那样在数据库里必有类似的表
a
b
c
d
表名与qiyemc字段的值相对应,所有表的结够都一样。
意思是表qiyexx的字段qiyemc所有值都对应一个表。
我是想把表a,表b,表c,表d中的所有字段值都取出来,但是现在需要去表qiyexx里获取这些表名,怎么做才能实现?

解决方案 »

  1.   

    可能说的不太清楚,我有一个表放企业信息(qiyexx),该表里有所有的企业名称(qiyemc),企业为(a,b,c,d),企业名称是动态的,随时会增加新的企业,增加新企业时会为该企业增加一个表,在数据库中每个企业有一个独立的表,即表(a,b,c,d),我要的就是用语句将这些表的所有值取出来。这么表的结构是一样的。即动态获取表名后,用select *来取值,然后用union来连接select。。
      

  2.   

    declare @sql varchar(3000)
    set @sql = ''
    declare @count int
    set @count = 0
    declare @a int
    select @a=count(*) from qiyexx
    while (@count<@a)
    begin
       select @tb=qiyemc from qiyexx where uid=@count
       set @sql = @sql + 'select * from ' + @tb 
       if exists(select 1 from qiyexx where uid=@count+1)
           set @sql = @sql + 'union all'
       set @count = @count + 1
    end
      

  3.   

    if object_id('tb') is not null drop table tb
    go 
    create table tb (name varchar(10))
    insert tb select
    'a' union select
    'b' if object_id('a') is not null drop table a
    go 
    create table a (name varchar(10))
    insert a select
    'aaa'
    if object_id('b') is not null drop table b
    go 
    create table b (name varchar(10))
    insert b select
    'bbb'
    ----------------------------------------->if object_id('#t') is not null drop table #t
    go 
    create table #t (name varchar(10))
    declare @tbname varchar(5)
    declare cur cursor for select name from tb
    open cur fetch next from cur into @tbname
    while @@fetch_status =0
    begin 
    exec('insert into #t select name from '+@tbname)
    fetch next from cur into @tbname
    end
    close cur 
    deallocate cur
    go 
    select * from #t name
    ----------
    aaa
    bbb(2 行受影响)
    drop table #t 
     
      

  4.   

    -------->添加测试表
    if object_id('tb') is not null drop table tb
    go 
    create table tb (name varchar(10))
    insert tb select
    'a' union select
    'b' if object_id('a') is not null drop table a
    go 
    create table a (name varchar(10))
    insert a select
    'aaa'
    if object_id('b') is not null drop table b
    go 
    create table b (name varchar(10))
    insert b select
    'bbb'
    ----------------------------------------->
    -------->创建临时表,存放结果
    if object_id('#t') is not null drop table #t
    go 
    create table #t (name varchar(10))-------->创建游标
    declare @tbname varchar(5)
    declare cur cursor for select name from tb
    open cur fetch next from cur into @tbname
    while @@fetch_status =0
    begin 
    exec('insert into #t select name from '+@tbname)
    fetch next from cur into @tbname
    end
    close cur 
    deallocate cur
    go ----------------------结果
    select * from #t name
    ----------
    aaa
    bbb(2 行受影响)
    drop table #t 
     
      

  5.   

    if exists(select 1 from qiyexx where uid=@count+1)这句话什么意思啊?