T-SQL Tip: Getting all the Records from all Tables in all User Databases

Yeah, I know, who would ever want to do that (!) but the purpose of this post is not to illustrate how you can actually get all the records from all tables in all user databases (even though it shows how to do it) but rather to provide an example of how we can dynamically generate T-SQL statements that can be used for undertaking various multi-database operations.


— Dynamically builds  T-SQL statements for retrieving all the records
— from all the tables in all user databases

— SQL Server versions  supported: SQL Server 2000 or later

exec sp_MSforeachdb
@command1=”IF DB_ID(‘?’) > 4 print ‘use ?;'”,
@command2=”IF DB_ID(‘?’) > 4 SELECT ‘SELECT * FROM [‘+TABLE_SCHEMA+’.’+TABLE_NAME+’]’ FROM ?.INFORMATION_SCHEMA.TABLES”

Details:

  1. In Query Window in SSMS, right clickResults To: Results to Text
  2. Run the above query and you will get “SELECT *” statements for each column of each table in each user database (Database ID > 4). By executing the produced code you get all the data records.

*Note: I could directly execute the produced code but when you run multi-database operations, it is wiser to first review the SQL statements, hey, you never know! 🙂
For more info, check out the following links: