Executing a stored procedure while in a cursor loop

Posted on 2010-08-20
Last Modified: 2012-05-10
I created a cursor to store script so that I could loop through all of the databases and list all of their tables. The looping script creation worked but I hit the 8,000 character limit barrier in SqlServer.

So rather than accumulate the entire script, I decided to execute a portion of the script while it was being generated. It did not work

Yet when I copy and paste the generated script and run it in a query panel, it works like a charm.

Attached is the code
CREATE TABLE #TableStructures(
	  [ApplicationCode] [varchar](50) NULL,
	  [RootFile] [varchar](255) NULL,
	  [DestinationTable] [varchar](255) NULL,
	  [Column Name] [varchar](128) NULL    
    SET @strSQL =''
    DECLARE curDBName CURSOR  FOR SELECT name FROM sys.databases WHERE name NOT IN('CommonPrograms','ExtractorControl','master','model','msdb','tempdb')

    OPEN curDBName
	      SET @strSQL = @strSQL + 
        'INSERT INTO #TableStructures (ApplicationCode, RootFile, DestinationTable, [Column Name])
         SELECT ExtractorControl..FilesToProcess.ApplicationCode, ExtractorControl..FilesToProcess.RootFile, ExtractorControl..FilesToProcess.DestinationTable, '+ @DBName +' AS ''Column Name'' 
         FROM (ExtractorControl..FilesToProcess INNER JOIN '+ @DBName +'..sysobjects ON ExtractorControl..FilesToProcess.DestinationTable = '+ @DBName +' INNER JOIN '+ @DBName +'..syscolumns ON '+ @DBName +' = '+ @DBName +'
         GROUP BY ExtractorControl..FilesToProcess.ApplicationCode, ExtractorControl..FilesToProcess.RootFile, ExtractorControl..FilesToProcess.DestinationTable, '+ @DBName +', '+ @DBName +'..sysobjects.xtype
         HAVING ('+ @DBName +'..sysobjects.xtype)= ''U''' + CHAR(10)
        EXEC @STRSQL  
        PRINT @STRSQL    
        SET @strSQL =''    
        FETCH curDBName INTO @DBName

    CLOSE curDBName
    DEALLOCATE curDBName   
    SELECT * FROM #TableStructures
    DROP TABLE #TableStructures

Open in new window

Question by:LennyGray
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 33488669
LVL 12

Accepted Solution

mcv22 earned 250 total points
ID: 33488696
Why not try something like this:

EXEC sp_msforeachdb
	USE [?]
	IF (''?'' NOT IN (''CommonPrograms'',''ExtractorControl'',''master'',''model'',''msdb'',''tempdb'')
		INSERT #TableStructures (..)
		SELECT ...

Open in new window

LVL 69

Assisted Solution

by:Scott Pletcher
Scott Pletcher earned 250 total points
ID: 33488817
More specifically (and hopefully more helpfully :-) ):

EXEC sp_MSforeachdb '
IF ''?'' IN (''CommonPrograms'',''ExtractorControl'',''master'',''model'',''msdb'',''tempdb'')
INSERT INTO #TableStructures (ApplicationCode, RootFile, DestinationTable, [Column Name])
SELECT ftp.ApplicationCode, ftp.RootFile, ftp.DestinationTable, AS ''Column Name''
FROM ExtractorControl..FilesToProcess ftp
INNER JOIN [?]..sysobjects so ON ftp.DestinationTable =
INNER JOIN [?]..syscolumns sc ON =
WHERE so.xtype = ''U''
GROUP BY ftp.ApplicationCode, ftp.RootFile, ftp.DestinationTable,
ORDER BY ftp.ApplicationCode, ftp.RootFile, ftp.DestinationTable,

Table aliases -- such as ftp, sc and so -- make code much easier to write, read and maintain.
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 10

Author Closing Comment

ID: 33500381
Masterful solution, Scott!

LVL 10

Author Comment

ID: 33500512
MCV22 - I apologize for awarding you the points in error.

ScottPletcher - I also apologize to you.

I have contacted EE for assistance in order to correct this error. You both are valuable assets to EE and to me. Thank you for the unselfish sharing of your time and experience.

It is a pleasure to know that the world has people like you and that you are generous-enough to share with people like me.

You are making a difference!

Lenny Gray
LVL 10

Author Closing Comment

ID: 33500627
The two of you created an elegant solution. Thanks, again!

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question