Managing Repetitive Jobs Without Cursors

Managing Repetitive Jobs Without Cursors

hile lurking on the SQL List server, I happened upon a suggestion that eliminates the need for writing your own cursors to accomplish common database administration tasks. These tasks apply to each database installed on a MSSQL (6.5) server. The tasks involved are things like running the DBCC (database consistency checker) routines to update index statistics, or to run a backup of a database.

The tip uses an undocumented system-stored procedure called ms_ForEachDB and its companion, ms_ForEachTable. I collected a few excellent examples of uses and applications for these procedures with respect to a few common DBA tasks. The examples were provided by the exchanges between Dave Canham, MCP, and Shaun Tinline, MCP, and they provided the ideas and guidance. Shaun was the original questioner, and he was kind enough to send a summation of the thread. We owe a great ‘thank you’ and debt of gratitude to them for giving their permission to share the exchanges and examples.

MSSQL Installation Databases
When MSSQL Server is installed, it installs several databases. They are named MSDB, Model, Temp, Master, and Pubs. MSDB stores alert and task information, Model stores database template information, Temp is a work area database used for sorts and formatting, and Pubs is the SQL Server example database. The Master database holds a server-wide system catalog and other system tables that store security and backup information, among other server statistics.

The Master Database also has a library of system-stored procedures installed with it. A stored procedure is a procedural program whose code is written in a database proprietary language. MSSQL Server’s name for its procedural language is T SQL, for example, and Oracle’s is named PL SQL.

Database Maintenance and SQL
All database activity (inserts, updates and deletes) is accomplished by Structured Query Language statements. The SQL 92 standard for Structured Query Language is probably the greatest point of convergence between products because all the vendors have to meet a minimum standard on their language implementation. The fact is that every vendor adds extensions to both their SQL implementation and their procedural language to highlight the strengths of their product.

Even though everything necessary to maintain the database is represented in the SQL language, there are times when a procedural code ‘wrapper’ around SQL statements adds a lot of convenience and repeatability to accomplishing the task at hand. Some of these tasks are dumping the database (backing up), loading the database (restoring), and granting access (administering security). A stored procedure is a procedural program that is stored, compiled, and executed in the database. It is written in a database-specific procedural language that acts as a wrapper around a Structured Query Language statement. We use the stored procedures provided by MSSQL Server to accomplish repetitive database administration tasks.

The DBA’s Helper
A DBA is responsible for maintaining the database’s availability, integrity, and security. To help in these tasks, the DBA can use the library of system-stored procedures to check on the status of the database, as well as run corrective procedures from the DBCC (database consistency check) routines. The system-stored procedures offer a routine called sp_MSForEachDB that helps the DBA by identifying the names of the databases on the server and executing an administrative SQL statement that applies to that database. Typically, a SQL Server is home to more than one database. First, you need to observe some caution in naming your own stored procedures.

Stored Procedure Naming
The Master database stored procedures are prefixed with an ‘sp__’. When you write your own stored procedures, it is recommended that you name them with a different prefix, instead of the ‘sp__’ convention used by the Master database’s stored procedures. This is because stored procedures prefixed with ‘sp__’ are executed in the context of whatever database you happen to be in when you invoke them. Consequently, there is a great likelihood of unintended results with a procedure named with ‘global’ applicability. Database professionals call this a ‘high whoops’ factor.

When you write your own stored procedures, you have two choices. Either let them accept a parameter for the database name in which to execute, or prefix them with something else that will signal them as user-created procedures so they won’t run by accident. (This touches on another very useful feature of stored procedures: that they accept parameters. Not only that, but they have parameters for input as you’d expect, and they can store parameters for output, too. But that’s another article.)

How about using ‘usp__’ and some other clue as to the purpose of the procedure for your own stored procedures? This little bit of caution could save you hours of recovery from unintended results caused by executing the right stored procedure in the wrong database.

Now that You Know What It Is, How Do You Use It?
As mentioned above, to maximize availability and integrity, the DBA has many checks to perform on the server. Using sp_MSForEachDB and its companion sp_MSForEachTable to execute these checks was not intuitive. When I tried to run them I got an error asking for a table that did not exist, in other words, sp_MSForEachDB required the existence of a temporary table called #SQLOLEDBUserProfile to execute. This type of requirement is not uncommon, and you can usually figure it out by opening up the code and reading it, but I didn’t figure this one out myself. I have to thank Dave for pointing this out.

--original msforeachdb exampleDROP TABLE #SQLOLEDBUserProfilego--In 6.5, you must create this temp table, #SQLOLEDBUserProfile, prior to using the Sp_MSForEachDB.--create temp tableCREATE TABLE #SQLOLEDBUserProfile(DBID int NOT NULL Primary Key, Profilebits int NOT NULL)--initializeEXEC sp_MSDBUserprofile 'init'  -----this must be run in the master database.---run taskEXEC sp_MSForEachDB 'USE ? SELECT DB_Name() EXEC sp_help '

This code will run the sp_help stored procedure in each database on the server.

Updating index statistics is still a DBA task in MSSQL 6.5. The update statistics command creates an up-to-date representation of the page that data is stored on, reconciling the data’s location to where the index says it is. In order to accomplish this, it is necessary to run the DBCC command update statistics against all user tables. The DBA also checks for the existence and constitution of indexes that relate the tables in the database. Instead of writing the cursor and getting involved in writing code, I learned that you could accomplish the same thing with one line at the ISQL window using the sp_MSForEachTable variant of the procedure.

EXEC sp_MSForEachTable  "update statistics ?"

Similarly, I found I could back up single tables with the line

EXEC sp_MSForEachTable "dump table ? to diskdump"

Checking current activity on the server showing locking and blocking can be neatly accomplished with a slight variation on Dave’s example.

EXEC sp_MSForEachDB 'USE ? SELECT DB_Name() EXEC sp_helplock'

Summary
The new features in SQL Server 7 go a long way to alleviating the monitoring tasks for the DBA. This is especially so in monitoring memory and storage details. The lion’s share of administrative and maintenance tasks that once occupied a significant effort in planning and tracking now take place under the hood. In MSSQL 6.5, however, these tasks remain the responsibility of the DBA. I hope these examples bring other uses to mind for you, so that you can use sp_MSForEachDB and sp_MSForEachTable to lighten your workload. I would like to express my sincerest thanks to the members of the SQL listserv at www.swynk.com for their help and willingness to share information.

devx-admin

devx-admin

Share the Post:
Web App Security

Web Application Supply Chain Security

Today’s web applications depend on a wide array of third-party components and open-source tools to function effectively. This reliance on external resources poses significant security

Thrilling Battle

Thrilling Battle: Germany Versus Huawei

The German interior ministry has put forward suggestions that would oblige telecommunications operators to decrease their reliance on equipment manufactured by Chinese firms Huawei and

iPhone 15 Unveiling

The iPhone 15’s Secrets and Surprises

As we dive into the most frequently asked questions and intriguing features, let us reiterate that the iPhone 15 brings substantial advancements in technology and

Performance Camera

iPhone 15: Performance, Camera, Battery

Apple’s highly anticipated iPhone 15 has finally hit the market, sending ripples of excitement across the tech industry. For those considering upgrading to this new

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years,

Web App Security

Web Application Supply Chain Security

Today’s web applications depend on a wide array of third-party components and open-source tools to function effectively. This reliance on external resources poses significant security risks, as malicious actors can

Thrilling Battle

Thrilling Battle: Germany Versus Huawei

The German interior ministry has put forward suggestions that would oblige telecommunications operators to decrease their reliance on equipment manufactured by Chinese firms Huawei and ZTE. This development comes after

iPhone 15 Unveiling

The iPhone 15’s Secrets and Surprises

As we dive into the most frequently asked questions and intriguing features, let us reiterate that the iPhone 15 brings substantial advancements in technology and design compared to its predecessors.

Chip Overcoming

iPhone 15 Pro Max: Overcoming Chip Setbacks

Apple recently faced a significant challenge in the development of a key component for its latest iPhone series, the iPhone 15 Pro Max, which was unveiled just a week ago.

Performance Camera

iPhone 15: Performance, Camera, Battery

Apple’s highly anticipated iPhone 15 has finally hit the market, sending ripples of excitement across the tech industry. For those considering upgrading to this new model, three essential features come

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years, as reported by energy analytics

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW) of wind, solar, and energy

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and wind sources. This funding will

Renesas Tech Revolution

Revolutionizing India’s Tech Sector with Renesas

Tushar Sharma, a semiconductor engineer at Renesas Electronics, met with Indian Prime Minister Narendra Modi to discuss the company’s support for India’s “Make in India” initiative. This initiative focuses on

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These