How to Run SQL Against Every Database on a Microsoft SQL Server

Use the sp_msforeachdb stored procedure. In the following example, I needed to find out if there were any objects that were referencing a specific linked server: DECLARE @command varchar(1000) SELECT @command = ‘USE ? SELECT OBJECT_NAME(object_id) [?] FROM sys.sql_modules WHERE definition LIKE ”%LINKEDSERVERNAME%”’ EXEC sp_msforeachdb @command In my case above, …

MSSQL 2005 Dynamic PIVOT

Here’s a method of generating a dynamic pivot of a dataset. It first generates the columns as a string (“[ColumnHeader0],[ColumnHeader1],[ColumnHeader2], …” format), builds a dynamic SQL string and executes it using the PIVOT expression. From the code below, the @cols variable is generated by using the FOR XML PATH expression. …