[英]How to select all records in sql database tables where any column has a particular value
I'm trying to find all the tables in my database that contain a particular email address. 我正在尝试查找数据库中包含特定电子邮件地址的所有表。
The only thing I know is that this means that I'm looking for any column that is a varchar of some length. 我唯一知道的是,这意味着我正在寻找长度一定的varchar的任何列。
I was thinking about some sort of loop through sys.tables
and then for each table in that loop, a loop through the rows in the table and then evaluation of each column on each row. 我正在考虑通过sys.tables
某种循环,然后针对该循环中的每个表,对表中的行进行循环,然后对每一行中的每一列进行求值。
Probably not the best way to go about it but there's things I don't know, particularly: 可能不是最好的解决方法,但是有些事情我还是不知道,尤其是:
Any assistance will be greatly appreciated. 任何帮助将不胜感激。
You could write a quick query that would build queries for each field. 您可以编写一个快速查询,为每个字段建立查询。
select 'select * from ' + TABLE_NAME + ' where ' + COLUMN_NAME + ' = ''the@email.com'''
from INFORMATION_SCHEMA.COLUMNS
where DATA_TYPE = 'nvarchar' and CHARACTER_MAXIMUM_LENGTH = '256'
You're probably looking at something like sp_MSforeachtable. 您可能正在查看类似sp_MSforeachtable的内容。 Find all tables with columns with [varchar] types ([nvarchar] as well right? Could they be on [char] or [nchar] columns as well?) from [sys].[columns]. 在[sys]。[columns]中找到所有具有[varchar]类型的列的表([nvarchar]也正确吗?它们是否也可以在[char]或[nchar]列上?)。 Then sp_MSforeachtable to access the values in the columns. 然后,sp_MSforeachtable访问列中的值。
Basically you're looking at nested cursors. 基本上,您正在看嵌套游标。 One to get all "text" columns along with the associated tables. 一种用于获取所有“文本”列以及关联的表。 Another to run a select on each table and column. 另一个在每个表和列上运行选择。
This is brute force stuff and is not pretty. 这是蛮力的东西,并不漂亮。
I've been in environments with an existing (and often ancient and revered) design as well. 我也曾在一个已有(通常是古老且受人尊敬的)设计的环境中工作。 Sometimes you just have to do stuff like this. 有时您只需要做这样的事情。 I like writing SQL so it can be fun. 我喜欢编写SQL,因此很有趣。
It is always nice to fantasize about building stuff from scratch to some ideal of perfection, but no plan is perfect. 幻想从头开始构建东西到一些完美的理想总是很好,但是没有一个计划是完美的。 You have to be able to do stuff like this. 您必须能够做这样的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.