SQL Server:在存在子字符串的多个数据库中查找所有列
我正在使用一个SQL Server,该SQL Server在其模式中具有多个数据库(我们将其称为Alpha,Beta,Gamma等)。
我想浏览每个数据库中的每个数据库,并找到哪些列至少包含某个子字符串的值(例如,它是“狗”)。
I know that if I want to check if a certain column (COLUMN_NAME) contains this substring I could use
WHERE COLUMN_NAME LIKE '%dog%'
and if the table that is returned is not empty, that column had the sub string and if the table is empty, there was no substring "狗。”
For a more concrete example, let's say I have the table:
Person | Pet | Favorite Animal |
---|---|---|
Jack | Cat | Dog |
James | Dog | Lion |
I would want the result of my query to be (in some format) "Pet" and "Favorite Animal."
我不知道的是如何在所有列上迭代(检查每个列的任何值是否具有“狗”),更不用说所有数据库的所有列。
我该怎么做?这超出了SQL查询的范围(换句话说,这应该在Python之类的事情中完成)吗?
(为了清楚质疑而编辑。)
I am working with a SQL Server that has multiple databases in its schema (let's call them alpha, beta, gamma, etc.).
I'm looking to go through each of these databases and find which columns have at least one value containing a certain substring (let's say it is "dog").
I know that if I want to check if a certain column (COLUMN_NAME) contains this substring I could use
WHERE COLUMN_NAME LIKE '%dog%'
and if the table that is returned is not empty, that column had the sub string and if the table is empty, there was no substring "dog."
For a more concrete example, let's say I have the table:
Person | Pet | Favorite Animal |
---|---|---|
Jack | Cat | Dog |
James | Dog | Lion |
I would want the result of my query to be (in some format) "Pet" and "Favorite Animal."
What I don't know is how to iterate over all of the columns (check if any values of each column has "dog"), let alone all of the columns of all of the databases.
How would I do this? Is this beyond the scope of a SQL query (in other words, should this be done in something like Python)?
(Edited for clarity of question.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是使用纯T-SQL进行操作的一种方法。它涉及光标,如果可能的话,最好避免使用动态的SQL WICH。首先循环浏览所有数据库,并获取类型Varchar/nvarchar的列(如果需要诸如text/ntext,可以添加其他类型)。然后使用动态SQL循环遍历所有列,以计算具有匹配的行。
警告:不要在较大的生产环境上运行此查询,因为它可能会对性能产生严重影响。
This is one way to do it with pure t-sql. It involves cursors and dynamic sql wich is best avoided if possible. First loop through all databases and get the columns of type varchar/nvarchar (you can add other types if you want like text/ntext). Then loop through all columns using dynamic sql to count rows that have a match.
Warning: Do not run this query on a big production environment as it can have serious impact on performance.