TSQL to Select Only Databases that have tables sp_MSforeachdb

This piece of code is handy for generating a list of databases that actually have tables, thereby ignoring any databases that have been created, but do not yet have table structures created.  The code also searches for databases of a specific partial search string.  The undocumented stored procedure sp_MSforeachdb is used here and a nice little bonus is the script will ignore offline database states.

Declare @vTable Table (name NVARCHAR(256))

Insert into @vTable

EXEC sp_MSforeachdb N'

IF EXISTS

(

SELECT 1 from [?].sys.tables

WHERE ''?'' like ''%partialsearchstring%''

)

BEGIN

SELECT ''?''

END;'

SELECT * FROM @vTable ORDER BY name

About AussieBICG

Connect with me here https://au.linkedin.com/in/aussiebicg

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s