我需要搜索数据库中哪个表具有给定主键的记录。如果我知道数据库,查询将非常简单,如下面的
select * from custom.customerA where id = 'BBD87605-8992-40B5-9BEA-5C85F3969CEC'
但由于我不了解数据库,我正在尝试下面的内容,但这不正确。
select * from 'custom.'+INFORMATION_SCHEMA.Tables where id = 'BBD87605-8992-40B5-9BEA-5C85F3969CEC'
基本上我需要在DB中的所有表中执行以下查询。
select *, TableName from custom.{TABLE} where id = 'BBD87605-8992-40B5-9BEA-5C85F3969CEC'
答案 0 :(得分:1)
那么你要做的是在每个表中搜索给定的值?这非常难看,没有办法快速做到这一点。我希望这件事你只需要在一段时间内完成一次。此代码将生成可以运行的select语句的动态列表。它只会查看数据类型为uniqueidentifier的列。
DECLARE @MySearchCriteria VARCHAR(500)
SET @MySearchCriteria = '''BBD87605-8992-40B5-9BEA-5C85F3969CEC''' --you do need all these quotation marks because this string is injected to another string.
SELECT 'SELECT ' + c.columnlist + '] FROM [' + t.name + '] WHERE ' + w.whereclause as SelectStatement
FROM sys.tables t
CROSS APPLY (
SELECT STUFF((
SELECT '], [' + c.Name AS [text()]
FROM sys.columns c
join sys.types t2 on t2.user_type_id = c.user_type_id
WHERE t.object_id = c.object_id
and t2.name = 'uniqueidentifier'
FOR XML PATH('')
), 1, 2, '' )
) c (columnlist)
CROSS APPLY (
SELECT STUFF((
SELECT ' OR [' + c.Name + '] IN (' + @MySearchCriteria + ')' AS [text()]
FROM sys.columns c
join sys.types t2 on t2.user_type_id = c.user_type_id
WHERE t.object_id = c.object_id
and t2.name = 'uniqueidentifier'
FOR XML PATH('')
), 1, 4, '' )
) w (whereclause)
where c.columnlist is not null
ORDER BY t.name
答案 1 :(得分:0)
使用sp_MSforeachtable
。这是一个未记录的存储过程,因此不要在生产中使用它:
EXEC sp_MSforeachtable 'SELECT * FROM custom.[?] WHERE id =''BBD87605-8992-40B5-9BEA-5C85F3969CEC'''