Wednesday 8 August 2018

How to execute SQL against all DBs on a Server

One option is sp_MSForEachDB. It's undocumented but useful nonetheless

DECLARE @command varchar(1000) 
SELECT @command = 
 'USE [?] SELECT c.name AS ColName, t.name AS TableName FROM sys.columns c JOIN 
sys.tables t ON c.object_id = t.object_id WHERE c.name LIKE ''%BILLG_BIN_ID%''' 
EXEC sp_MSforeachdb @command
NOTES:
  1. ? is replaced in the query as the database name, so structure the query to explicitly define which DB it is to query against

No comments:

Post a Comment