Solved

To run a SP against many databases in the same server.

Posted on 2006-06-09
7
402 Views
Last Modified: 2007-12-19
In SQL2K I am trying

sp_Msforeachdb @command1 =
'use [?]
if exists (select 1 from information_schema.tables where table_name = ''Db_true'')
exec sp__defrag_n_reindex '

[A cursor with the name 'hCForEach' already exists.]

I have traced the problematic line and that is the last line in my proc. The full proc is given in my first comment


What is the solution.


0
Comment
Question by:Mateen
  • 4
  • 3
7 Comments
 

Author Comment

by:Mateen
ID: 16875628
sp__defrag_n_reindex  is created in master database and has marked as systemobject.

create proc sp__defrag_n_reindex as
SET NOCOUNT ON
DECLARE @tablename VARCHAR (128)
DECLARE @execstr   VARCHAR (255)
DECLARE @objectid  INT
DECLARE @indexid   INT
DECLARE @frag      DECIMAL
DECLARE @maxfrag   DECIMAL

-- Decide on the maximum fragmentation to allow
SELECT @maxfrag = 15.0

-- Declare cursor
DECLARE tables CURSOR FOR
   SELECT TABLE_NAME
   FROM INFORMATION_SCHEMA.TABLES
   WHERE TABLE_TYPE = 'BASE TABLE'

-- Create the table
CREATE TABLE #fraglist (
   ObjectName CHAR (255),
   ObjectId INT,
   IndexName CHAR (255),
   IndexId INT,
   Lvl INT,
   CountPages INT,
   CountRows INT,
   MinRecSize INT,
   MaxRecSize INT,
   AvgRecSize INT,
   ForRecCount INT,
   Extents INT,
   ExtentSwitches INT,
   AvgFreeBytes INT,
   AvgPageDensity INT,
   ScanDensity DECIMAL,
   BestCount INT,
   ActualCount INT,
   LogicalFrag DECIMAL,
   ExtentFrag DECIMAL)

-- Open the cursor
OPEN tables

-- Loop through all the tables in the database
FETCH NEXT
   FROM tables
   INTO @tablename

WHILE @@FETCH_STATUS = 0
BEGIN
-- Do the showcontig of all indexes of the table
   INSERT INTO #fraglist
   EXEC ('DBCC SHOWCONTIG (''' + @tablename + ''')
      WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS')
   FETCH NEXT
      FROM tables
      INTO @tablename
END

-- Close and deallocate the cursor
CLOSE tables
DEALLOCATE tables

-- Declare cursor for list of indexes to be defragged
DECLARE indexes CURSOR FOR
   SELECT ObjectName, ObjectId, IndexId, LogicalFrag
   FROM #fraglist
   WHERE LogicalFrag >= @maxfrag
      AND INDEXPROPERTY (ObjectId, IndexName, 'IndexDepth') > 0

-- Open the cursor
OPEN indexes

-- loop through the indexes
FETCH NEXT
   FROM indexes
   INTO @tablename, @objectid, @indexid, @frag

WHILE @@FETCH_STATUS = 0
BEGIN
   PRINT 'Executing DBCC INDEXDEFRAG (0, ' + RTRIM(@tablename) + ',
      ' + RTRIM(@indexid) + ') - fragmentation currently '
       + RTRIM(CONVERT(varchar(15),@frag)) + '%'
   SELECT @execstr = 'DBCC INDEXDEFRAG (0, ' + RTRIM(@objectid) + ',
       ' + RTRIM(@indexid) + ')'
   EXEC (@execstr)

   FETCH NEXT
      FROM indexes
      INTO @tablename, @objectid, @indexid, @frag
END

-- Close and deallocate the cursor
CLOSE indexes
DEALLOCATE indexes

-- Delete the temporary table
DROP TABLE #fraglist

exec sp_MSForEachTable 'DBCC DBREINDEX ( ''?'' , '''' , 0 )'


GO
0
 
LVL 75

Accepted Solution

by:
Aneesh Retnakaran earned 500 total points
ID: 16875656
This error is because sp_MSForEachTable nd sp_MSForEachDB uses the same cursor Name
0
 

Author Comment

by:Mateen
ID: 16875664
Ok.
What is the solution to replace
exec sp_MSForEachTable 'DBCC DBREINDEX ( ''?'' , '''' , 0 )'



 
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 16875679
i am not sure on this ,I think it is better to run the above statement against all the dbs  without using sp_MsForEachDB
0
 

Author Comment

by:Mateen
ID: 16875680
Hi aneeshattingal

It seems that I have got it right.

Please wait.
0
 

Author Comment

by:Mateen
ID: 16875687
I have already store procedure created in my master database

CREATE procedure sp__ReindexEachTable as
--exec sp_MSForEachTable 'DBCC DBREINDEX ( ''?'' , '''' , 0 )'
declare @TableName     sysname
declare c_Tables cursor for
select Table_Name
from information_schema.tables
where Table_Type = 'Base Table'
open c_Tables
fetch next from c_Tables into @TableName
while @@fetch_status = 0 begin
     print @TableName
     dbcc dbreindex( @TableName, '', 90 )
     execute( N' Update Statistics ' + @TableName )
     fetch next from c_Tables into @TableName
end
close c_Tables
deallocate c_Tables
GO

I deleted the line
exec sp_MSForEachTable 'DBCC DBREINDEX ( ''?'' , '''' , 0 )'
from the PROCEDURE AND replaced

sp_Msforeachdb @command1 =
'use [?]
if exists (select 1 from information_schema.tables where table_name = ''Db_true'')
exec sp__defrag_n_reindex '

                    BY
sp_Msforeachdb @command1 =
'use [?]
if exists (select 1 from information_schema.tables where table_name = ''Db_true'')
exec sp__defrag_n_reindex ',
@command2 = ' use [?] exec sp__ReindexEachTable'

It seems to be working.





0
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 16875694
ok. that's good..
I was trying to edit one of the sps and change the cursornames ..
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

706 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now