开发者

Querying all the tables in a DB

I am using SQL Server 2005. I am having a peculiar need now.

I am having a Database and it in turn have several table(>50). All of these table have 开发者_JAVA技巧a similar named column with a condition. I want to query this column across all the tables in the DB.

I am not finding a proper solution in Googling. Please help me.

Thanks a lot in Advance :)


Maybe this can help you?

SELECT * FROM information_schema.tables

Afterwards, you can loop through all tables and query your column.


Using Kevin's suggestion you do something like this, then execute it's output.

DECLARE @ColumnName AS VARCHAR(20)
SET @ColumnName = 'MyColumn'

SELECT 'SELECT ' + @ColumnName + ' FROM ' + TABLE_NAME FROM information_schema.tables


sp_msforeachtable @command1=N'SELECT ''?'', * from ? WHERE yourcol=''whatever'''

Above will run query against every table in selected database, and print tablename + every column in the table for conditions met. If it reaches a table that has an invalid column, it'll just keep going (but print an error message).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜