Forum Discussion
przemek_pbi
8 years agoRegular Visitor
Use a list of databases from one query into another query cursor
Hi All, I've got hundreds of databases with identical tables structure and tens of queries to run against these dbs. To avoid loading list of db for each query cursor, I've created a seperate que...
przemek_pbi
8 years agoRegular Visitor
Hi All,
I've got hundreds of databases with identical tables structure and tens of queries to run against these dbs. To avoid loading list of db for each query cursor, I've created a seperate query in PBI - DBs - that keeps the list of dbs which I need to incorporate in my SQL queries. The queries are too complicated for me to transform them into DAX so I'd like to keep them in pure SQL. Please see the below example and advise how to do it.
DECLARE
@db VARCHAR(128),
@query VARCHAR(MAX),
@sql VARCHAR(MAX)
SET @query = 'SELECT DB_NAME(), TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE=''BASE TABLE'''
CREATE TABLE #Tables (DBNAME VARCHAR(128), TABLE_NAME VARCHAR(128))
DECLARE db_cursor CURSOR FOR
--I want to replace this line with a already loaded recordset 'DBs'
SELECT name FROM master.dbo.sysdatabases WHERE name NOT IN ('master','model','msdb','tempdb')
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @db
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql =' USE '+@db+'; INSERT INTO #Tables '+@query+''
FETCH NEXT FROM db_cursor INTO @db
EXEC (@sql)
END
CLOSE db_cursor
DEALLOCATE db_cursor
SELECT * FROM #Tables
DROP TABLE #TablesRegards,
Przemek