SQL查询从ID等于的所有表中选择

时间:2019-02-06 14:44:01

标签: mysql sql

相对简单的问题,但是我是SQL查询的新手。我正在尝试在所有表中查找包含一定值的任何记录。

总而言之,我想在整个数据库中找到hContactId为200的任何实例。

我尝试了以下操作:

USE dbname
SELECT *
FROM sys.Tables
WHERE hContacts.hContactId = 200;

我最终得到

  

您的SQL语法有错误;检查手册   对应于您的MariaDB服务器版本

我已经看到一些非常复杂的查询(如下所示)无法正常工作,但是肯定应该有一种查询所有表的整数的方法吗?

我尝试过同样的错误消息的另一件事:

declare  @sql varchar(8000), @tbl varchar(255), @col varchar(255), 
@data  varchar(50)

set @data = '200'

declare cur_tbl cursor for
     select a.name, b.name from sysobjects a, syscolumns b, systypes c where a.id = b.id and a.type = 'U' and c.xtype = b.xtype and c.name in ( 'int' )
open cur_tbl
fetch next from cur_tbl into @tbl, @col
while @@fetch_status = 0
begin
     set @sql = '
                   if exists (select * from [' + @tbl + '] where convert( varchar(255), [' + @col + '] ) = ''' + @data + ''')
                         select tbl=''' + @tbl + ''', col=''' + @col + ''', [' + @col + '], * from [' + @tbl + '] where convert( varchar(255), [' + @col + '] ) = ''' + @data + '''
                   '
     exec(@sql)

     fetch next from cur_tbl into @tbl, @col
end
close cur_tbl
deallocate cur_tbl

再次在所有表上查找基本查询,以查找与hContactId匹配的表。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

好吧,您始终可以使用联合:

SELECT * FROM Table_name_1
WHERE hContactId = 200;
UNION  
SELECT * FROM Table_name_2 
WHERE hContactId = 200;
UNION  
SELECT * FROM Table_name_3 
WHERE hContactId = 200;