Tuesday, December 18, 2012

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 ?;'",


  1. In Query Window in SSMS, right click - Results 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:
Check out my latest eBook on SQL Server:
Tuning SQL Server - Ebook

Easily secure your SQL Server instances! Try out DBA Security Advisor!
DBA Security Advisor for SQL Server by SQLArtBits
DBA Security Advisor was developed by SQLArtBits. The tool was being carefully developed for an entire year and it contains comprehensive security checks and recommendations based on proven SQL Server security best practices. Feel free to download and use the Community Edition which is free and if you find it useful, you can consider upgrading to the Enterprise Edition!

Artemakis Artemiou [MVP]

Author & Editor

Artemakis Artemiou is a Senior SQL Server Architect, Software Developer and Microsoft Data Platform MVP. He is also an author, regular blogger, president of Cyprus.NET User Group and CY Country leader of INETA-EU. He is also the creator of DBA Security Advisor and In-Memory OLTP Simulator. Artemakis is a frequent guest author of worldwide well-respected online journals where he writes articles focusing on many SQL Server topics.

Reference: The SQL Server and .NET Hub (http://www.sqlnethub.com)