Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While Loop to Iterate through Databases

Tags:

sql

sql-server

I was wondering if someone could help me with creating a while loop to iterate through several databases to obtain data from one table from two columns. this is was I have done so far. nothing works because i do not know how to make the select statement work through each database with regards to the table that I am querying from each database (dbo.tbldoc)

DECLARE @Loop int
DECLARE @DBName varchar(300)
DECLARE @SQL varchar(max)
DECLARE @tableName VARCHAR(255)

SET @Loop = 1
SET @DBName = ''

   WHILE @Loop = 1
BEGIN

   SELECT [name] FROM sys.databases 
   WHERE [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
   ORDER BY [name]

      SET @Loop = @@ROWCOUNT

   IF @Loop = 0
      BREAK

   SET @SQL = ('USE ['+ @DBNAME +']')
      IF EXISTS(SELECT [name] FROM sys.tables WHERE name != 'dbo.tbldoc' )
                  BEGIN
               SELECT SUM(PGCOUNT), CREATED FROM **dbo.tbldoc**
            END
            ELSE
            --BEGIN
               PRINT 'ErrorLog'
            END 
like image 995
Jeff Avatar asked Jan 18 '11 17:01

Jeff


People also ask

Can you do a WHILE loop in SQL?

The while loop in SQL begins with the WHILE keyword followed by the condition which returns a Boolean value i.e. True or False. The body of the while loop keeps executing unless the condition returns false. The body of a while loop in SQL starts with a BEGIN block and ends with an END block.

What is ITERATE database?

ITERATE label. ITERATE can appear only within LOOP , REPEAT , and WHILE statements. ITERATE means “start the loop again.” For an example, see Section 13.6. 5.5, “LOOP Statement”.

Can we use WHILE loop in CTE?

You can't. Simply place the CTE declaration with in the loop.


2 Answers

I would consider sp_MSForEachDB which is a lot easier...

Edit:

EXEC sp_MSForEachDB 'USE [?]; IF DB_NAME() LIKE ''Z%%''
BEGIN


END
'
like image 90
gbn Avatar answered Sep 20 '22 18:09

gbn


CREATE TABLE #T
(dbname sysname NOT NULL PRIMARY KEY,
SumPGCOUNT INT,
CREATED DATETIME)

DECLARE @Script NVARCHAR(MAX) = ''

SELECT @Script = @Script + '

USE ' + QUOTENAME(name) + '
IF EXISTS(SELECT * FROM sys.tables WHERE OBJECT_ID=OBJECT_ID(''dbo.tbldoc''))
  INSERT INTO #T
  SELECT db_name() AS dbname, SUM(PGCOUNT) AS SumPGCOUNT, CREATED 
  FROM dbo.tbldoc
  GROUP BY CREATED;  
  '
FROM sys.databases 
WHERE state=0 AND user_access=0 and has_dbaccess(name) = 1
 AND [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
ORDER BY [name]

IF (@@ROWCOUNT > 0)
 BEGIN
 --PRINT @Script
 EXEC (@Script)
 SELECT * FROM #T
 END

 DROP TABLE #T
like image 44
Martin Smith Avatar answered Sep 22 '22 18:09

Martin Smith