Friday, June 12, 2009

System stored procedures every developer should know

Top 5 SQL System stored procedures every developer should know

There are a number of documented and undocumented system stored procedures in MS SQL Server that are helpful for every web developer working with databases. From the developer’s perspective, here’s a list of 5 System stored procedures that are my favorite.

1. sp_help


sp_help gives information about database objects. If you wanted to quickly know the structure of a table but are too lazy to look for the schema diagram or to dig for the table you are interested in within the Object explorer, sp_help is here to help

Syntax : sp_help object>

It can be used without parameters to get the information of objects in the database.

2. sp_helptext


sp_help gives definition information of objects such as system stored procedures, user defined stored procedures, user defined functions, triggers etc.

Syntax : p_helptext object>


On the testdb database:

Executing a sp_helptext 'dbo.Materialsbill' yields the following definition of the user defined stored procedure

3. sp_MSforeachtable


Caution – This is an undocument stored procedure and should not be relied on. It is not listed in SQL BOL and should be used at your own risk.

This is a very useful stored procedure for executing a command for ALL the tables in the database. Say you wanted to get the number of rows in all the tables in your database, you could write:

Example : EXEC sp_MSforeachtable 'SELECT ''?'', COUNT(*) FROM ?'

The literal ? is used as a token to replace the table name.

4. sp_depends


Ever wanted to make a change to a table but were not sure what other objects are dependent on this table? There could be views or stored procedures that could break due to this change. In situations like this, sp_depends come to the rescue.

Syntax : sp_depends object>


In the testdb database, say I wanted to find out all the objects that are dependent on the Person.Address table.

5. sp_spaceused


This is a simple stored procedure that gives information on the size of the database or the database objects

Syntax sp_spaceused object>

If it is used without parameters, it would return the database information


If it is used with a parameter, it would return the information on the object

No comments:

Post a Comment