Note: this article is published on 01/07/2025.
This series of articles will discuss Database Dictionary related issues
- Database Dictionary (1) --- Schema
- Database Dictionary (2) --- Extended Properties
- Database Dictionary (3) --- Loop Databases and Servers by AI --- this article
Introduction:
When we loop databases we need dynamic SQL to implement it as we discussed in Database Dictionary (1-2-1) --- Using Dynamic SQL Script.
AI approach:
This article was started writing in September, when I used dynamic SQLs to handle the loop against databases (in Section A). Later on, I used AI to do the same task, I found using AI is much easier and can get solution directly. I put the resolution in Section B and C. And I will put this article category as AI.
- A - Loop with Databases by Dynamic SQL --- my Contribution
- B - Loop with Databases by System Stored Procedure --- AI product
- C - Loop for databases in all linked servers by both SQL with Cursors and Dynamic SQL --- AI Product
A - Loop with Databases by Dynamic SQL --- my Contribution
This is what I wrote previously --- using pure dynamic SQL to loop databases:
CREATE PROCEDURE [dbo].[GetDatabases]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @sql NVARCHAR(MAX) = N'';
DECLARE @sqlBody NVARCHAR(MAX) = N'';
-- Execution for one database
SELECT @sqlBody =
'
INSERT INTO SDD.dbo.[Database]
SELECT d.name, s.id
FROM
sys.databases d
INNER JOIN
SDD.dbo.[Server] s
ON
s.Id = 1
AND
d.name = DB_NAME()
AND
d.name NOT IN (SELECT i.name FROM SDD.dbo.IgnoreItem i WHERE i.[index] = 2)
'
-- Loop all databases
SELECT @sql += 'USE ' + QUOTENAME(name) + @sqlBody
FROM sys.databases
WHERE state_desc = 'ONLINE' AND name NOT IN ('master', 'tempdb', 'model', 'msdb');
-- Execution for the all databases
EXEC sp_executesql @sql;
END
GO
B - Loop with Databases on a Server by System Stored Procedure --- AI product
This is a AI product, what I used is Microsoft Copilot, ask for: Loop for databases in a server
To loop through databases on a SQL Server, you can use the sp_MSforeachdb system stored procedure. This allows you to execute a command on each database without setting up a cursor. Here's a basic example:
EXEC sp_MSforeachdb 'USE ?; SELECT name FROM sys.tables;'


Join the conversation! Your thoughts help the community grow.