Sql-server – List column value for all databases that have a specific table and column

sql servert-sql

What I am really looking for is the name of each database with table ApplicationVersion and column [Version] as well as the value in [Version]. Some of my databases don't have the specified table column and should be ignored. The table always has only one row.

Database    ApplicationVersion
DB_001      5.123.0.234
DB_002      5.123.0.234
DB_003      6.223.0.435

Best Answer

I really, really, really recommend against sp_MSforeachdb. It's easy, sure, but it is undocumented, unsupported, and buggy as all get out.

Here is a dynamic SQL solution:

CREATE TABLE #x([Database] sysname, ApplicationVersion varchar(32));

DECLARE @sql nvarchar(max) = N'';

SELECT @sql += N'
  BEGIN TRY
    INSERT #x EXEC ' + QUOTENAME(name) +N'.sys.sp_executesql 
    N''SELECT DB_NAME(), MAX(Version) FROM dbo.ApplicationVersion'';
  END TRY
  BEGIN CATCH
    PRINT CHAR(32);
  END CATCH;'
FROM sys.databases 
WHERE state = 0; -- database is online

EXEC sys.sp_executesql @sql;

SELECT [Database], ApplicationVersion FROM #x;

DROP TABLE #x;