I have a DataBase with around +100 tables, like half of tables have column A & column B.
My question is, Can I query all tables that have this columns with a specific values e.g.
SELECT * FROM DATABASE
WHERE
EACHTABLE HAS COLUMN A = 21 //only if table has columns and then values
AND
COLUMN B = 13
I am not sure how exact I will do it, nothing is coming up on google either
You can use the undocumented MS stored procedure
sp_MSforeachtable, if you fancy living life recklessly:Result:
By default,
sp_MSforeachtablewill, as its name implies, perform the same task for each table in the database. However, one optional parameter to this procedure, called@Whereand, can be used to modify theWHEREclause of the internal query that enumerates the tables in the database. It helps to know that this internal query has already established two aliases to some of the system views.ois an alias forsysobjects(the legacy system view).sysois an alias forsys.all_objects(a more modern system view).Once
sp_MSforeachtablehas decided which tables to run against, it will execute the query given to it as its first parameter. But, it will replace?with the schema and table name (?is the default replacement character. This can be changed as needed)In this case, I chose to create a temp table, then have each selected table store its results into this temp table, and after
sp_MSforeachtablehas finished running, to select the combined results out with no further processing.There is a similar (and similarly undocumented) procedure called
sp_MSforeachdbwhich will access each user database on the server. These can even be combined (although you have to be careful with doubling up'quote characters twice, at times). However, there’s no equivalentsp_MSforeachcolumn.