Home > SQL Server Tips > Database Development > Stored procedures: Perform operations on SQL Server tables and objects
SQL Server Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 

DATABASE DEVELOPMENT

Stored procedures: Perform operations on SQL Server tables and objects


Brian Walker, Contributor
08.18.2005
Rating: -5.00- (out of 5)


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


Here I will describe two simple routines. In the first, the SQL code creates a system stored procedure named sp_FixTables, which performs a specified operation on a specified set of tables. The second is a system stored procedure named sp_FixObjects, which performs a specified operation on a specified set of objects.

[TABLE]

The sp_FixTables stored procedure performs a specified operation on a specified set of tables. It accepts six parameters and all of them are optional.

The first parameter specifies timing issues, whether T-SQL code is generated or actions are performed immediately. A value of zero returns T-SQL code that can be saved and/or executed as a separate task. A value of one causes the specified action(s) to be performed on the selected objects immediately. The default value is zero.

The next four parameters (two through five) work together to form a combination of search criteria using object names. Please refer to my previous tip on finding columns and tables for an explanation of how these parameters work.

The last (sixth) parameter specifies which operation will be performed on each object. The string value should consist of T-SQL statements. Caret symbols "^" are replaced by single quotes, making it cleaner when you include embedded single quotes in the T-SQL statements. The default operation is to UPDATE STATISTICS and EXECUTE sp_recompile.

The sp_FixTables stored procedure is similar to an undocumented stored procedure that comes with SQL Server (sp_MSforeachtable), but this routine has some additional flexibility. You can generate T-SQL code or immediately execute commands. You can more easily specify a subset of tables. You can perform character substitutions other than table name.

There are repetitive character substitutions made within the string of T-SQL statements to be executed for each object. An asterisk "*" is replaced by the current object name. A pound sign "#" is replaced by the


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


RELATED CONTENT
Database Development
Managing the development lifecycle with Visual Studio Team System 2008
Processing XML files with SQL Server functions
A first look at Visual Studio Team System 2008 Database Edition
How to create a SQL inner join and outer join: Basics to get started
New datetime data types in SQL Server 2008 offer flexibility
Using DATEADD and DATEDIFF to calculate SQL Server datetime values
SQL Server database design disasters: How it all starts
SQL Server database design disasters: What not to do
Secure SQL Server from SQL injection attacks
Check SQL Server database and log file size with this stored procedure

SQL Server Stored Procedures
Top 10 SQL Server development tips of 2008
SQL Server trigger vs. stored procedure to receive data notification
SQL Server errors, failures and other problems fixed from the trenches
SQL Server and data manipulation in T-SQL
How to use SQL Server 2008 hierarchyid data type
SQL Server stored procedures tutorial: Write, tune and get examples
Check SQL Server database and log file size with this stored procedure
SQL Server source code analysis and management adds database security
Configure SQL Server Service Broker for sending stored procedure data
Find size of SQL Server tables and other objects with stored procedure

SQL/Transact SQL (T-SQL)
Working with sparse columns in SQL Server 2008
Determining the source of full transaction logs in SQL Server
New GROUP BY option provides better data control in SQL Server 2008
Using the OPENROWSET function in SQL Server
Loading data files with SQL Server's BULK INSERT statement
Importing and exporting bulk data with SQL Server's bcp utility
Testing transaction log autogrowth behavior in SQL Server
Securing SQL Server with access control, login monitoring and DDL triggers
Top 10 SQL Server development tips of 2008
The sqlcmd utility in SQL Server
SQL/Transact SQL (T-SQL) Research

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
library  (SearchSQLServer.com)
trigger  (SearchSQLServer.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary


current object ID. A dollar sign "$" is replaced by the object owner name. An ampersand "&" is replaced by the current table name without the prefix (if table name prefixes are used).

The sp_FixTables stored procedure can be used in place of hand-coded script for each table or writing SQL code to implement a cursor that loops through the tables. Tasks such as index maintenance can be performed on all tables with examples like these:

EXECUTE sp_FixTables @DBUltra = 1, @PCAdmin = 'DBCC INDEXDEFRAG (0, #)'

EXECUTE sp_FixTables @DBUltra = 1, @PCAdmin = 'DBCC DBREINDEX (^* ^)'

This example checks the customer tables in the Northwind database:

USE Northwind EXECUTE sp_FixTables 1,NULL,NULL,'Customer%',NULL,'DBCC CHECKTABLE (^ * ^)'

[TABLE]

The sp_FixObjects stored procedure performs a specified operation on a specified set of objects. It accepts six parameters and all of them are optional.

The first parameter specifies whether T-SQL code is generated or actions are performed immediately. A value of zero returns T-SQL code that can be saved and/or executed as a separate task. A value of one causes the specified action(s) to be performed on the selected objects immediately. The default value is zero.

The next four parameters (two through five) work together to form a combination of search criteria using object names.

The last (sixth) parameter specifies the operation to be performed on each object. The string value should consist of T-SQL statements. Caret symbols "^" are replaced by single quotes, which makes it cleaner to include embedded single quotes in the T-SQL statements. The default operation is to change the object owner to dbo.

The sp_FixObjects stored procedure is much like the sp_FixTables stored procedure, but this routine has slightly different features while the other routine is specifically designed for working on tables.

There are repetitive character substitutions made within the string of T-SQL statements to be executed for each object. An asterisk "*" is replaced by the current object name. A pound sign "#" is replaced by the current object ID. A dollar sign "#" is replaced by the object owner name. An ampersand "&" is replaced by the object type (TABLE, VIEW, PROCEDURE, FUNCTION).

This example returns information about all objects in the Northwind database that contain "Sales by Year" in their names:

USE Northwind EXECUTE sp_FixObjects 1,NULL,NULL,'%Sales by Year%',NULL,'EXECUTE sp_help ^ * ^'

It may be more convenient to provide the sixth parameter by name and omit all the others when calling these stored procedures.

This example generates T-SQL code to drop all the objects in the Northwind database:

USE Northwind EXECUTE sp_FixObjects @PCAdmin = 'DROP & [*]'

[TABLE]

Click for the stored procedures: sp_FixTables and sp_FixObjects


About the author: Brian Walker is a senior database architect in an IS department that uses SQL Server 2000 and the .NET Framework. He has more than 25 years of experience in the IT industry with the last several years focused on databases and SQL Server. Walker is a software developer, database developer, database administrator and database consultant. He develops utility software as a hobby, including a large collection of SQL Server utilities.


More information from SearchSQLServer.com

  • Tip: Stored procedure: Find columns and tables
  • Learning Center: Stored procedures
  • Topic: Get best practices for working with stored procedures


  • Rate this Tip
    To rate tips, you must be a member of SearchSQLServer.com.
    Register now to start rating these tips. Log in if you are already a member.




    DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.



    SQL Server Development - .NET, C#, T-SQL, Visual Basic
    HomeNewsTopicsITKnowledge ExchangeTipsAsk the ExpertsMultimediaWhite PapersIT Downloads
    About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
    SEARCH 
    TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.

    TechTarget Corporate Web Site  |  Media Kits  |  Site Map




    All Rights Reserved, Copyright 2005 - 2009, TechTarget | Read our Privacy Policy
      TechTarget - The IT Media ROI Experts