有一个数据库。我要读取里面有一个表里面的数据,但我不知道该表的名字。但该表中有一列(假设为abc),该列中的数据我是知道的,并且只有这个表里面的abc列有该值(即其它表中的abc列均不是该傎)。我该怎么样通过该值来得到该表的名字呢?
如果得到不了的话,可不可以写一个select选择所有表?
如select abc from 所有表 where abc=指定值。
请问该SQL语句怎么写?谢谢!

解决方案 »

  1.   

    通过allcolumns找到包含该列的所有表,游标遍历筛选出来的表找该列所含的某个值
      

  2.   

    select o.name from syscolumns s join sysobjects o on s.id=o.id
    where s.name='abd' and o.type='u'
      

  3.   

    查询出表名和列名?select a.name dbname, b.name colname from sysobjects a , syscolumns b where a.id=b.id and a.xtype = 'u' and b.name = 'abc'
      

  4.   


    麻烦可以说得更具体一点吗?
    另外我这个是用在sqlite中的,并不是MS-SQL中的,谢谢!
      

  5.   


    我可以把你的这个语句直接放在 select abc from后面吗?也就是你写的select语句可以直接放在from后面吗?
      

  6.   


    create table f1(abc int)
    create table f2(abc int)
    create table f3(abc int)insert into f1(abc) values(51)
    insert into f2(abc) values(52)
    insert into f3(abc) values(53)
    declare @abc_value int
    select @abc_value=52  --> abc列的值select object_name([object_id]) tablename,
    'select 1 from '+object_name([object_id])+' where abc='+cast(@abc_value as varchar) tsqls
    into #t from sys.columns where name='abc'set nocount on
    declare @sql varchar(2000),@tablename varchar(200)
    while(exists(select 1 from #t))
    begin
      select top 1 @tablename=tablename,@sql=tsqls from #t
      exec(@sql)
      if @@ROWCOUNT>0
        print @tablename
      delete from #t where tablename=@tablename
    end-- 结果
     f2
      

  7.   

    不能,如果你的表名,列名不确定,需要动态语句来拼接.然后动态执行.declare @tbname varchar(20)
    set @tbname = (select a.name from sysobjects a , syscolumns b where a.id=b.id and a.xtype = 'u' and b.name = 'abc')exec('select * from ' + @tbname )
    exec('select * from ' + @tbname + ' where abc = ...')