STORED PROCEDURES IN SQL SERVER

 > A stored procedure is a group of Sql statements that has been created and stored in the database. Stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data. Stored procedure will reduce network traffic and increase the performance. If we modify stored procedure all the clients will get the updated stored procedure

In SQL we are having different types of stored procedures are there

a) System Stored Procedures

b) User Defined Stored procedures

c) Extended Stored Procedures

System Stored Procedures:

System stored procedures are stored in the master database and these are starts with a sp_ prefix. These procedures can be used to perform variety of tasks to support Sql server functions for external application calls in the system tables and use to perform many administrative and informational activities.

Ex: sp_helptext [StoredProcedure_Name]

User Defined Stored Procedures:

User Defined stored procedures are usually stored in a user database and are typically designed to complete the tasks in the user database. While coding these procedures don’t use sp_ prefix because if we use the sp_ prefix first it will check master database then it comes to user defined database.

Stored procedure are modules or routines that encapsulate code for reuse. A stored procedures can take input parameters, return tabular or scalar results and messages to the client.

Extended Stored Procedures:

Extended stored procedures are the procedures that call functions from DLL files that an instance of Microsoft SQL Server can dynamically load and run. Now a day’s extended stored procedures are depreciated for that reason it would be better to avoid using of Extended Stored procedures.

Why use Stored Procedures?

> Rewriting inline SQL statements as Stored Procedures

> Compilation and storing of the query execution plan

> Enabling of conditional and procedural logic

> Centralized repository for DML and DDL code enabling code reuse

> Protection from SQL Injection attacks

> Enabling of strict security model

> Readability

Sample of creating Stored Procedure

USE AdventureWorks2008R2;

GO

CREATE PROCEDURE dbo.sp_who

AS

SELECT FirstName, LastName FROM Person.Person;

GO

EXEC sp_who;

EXEC dbo.sp_who;

GO

DROP PROCEDURE dbo.sp_who;

GO

Advantages of using stored procedures

a) Stored procedure allows modular programming.

You can create the procedure once, store it in the database, and call it any number of times in your program.

b) Stored Procedure allows faster execution.

If the operation requires a large amount of SQL code is performed repetitively, stored procedures can be faster. They are parsed and optimized when they are first executed, and a compiled version of the stored procedure remains in memory cache for later use. This means the stored procedure does not need to be reparsed and reoptimized with each use resulting in much faster execution times.

c) Stored Procedure can reduce network traffic.

An operation requiring hundreds of lines of Transact-SQL code can be performed through a single statement that executes the code in a procedure, rather than by sending hundreds of lines of code over the network.

d) Stored procedures provide better security to your data

Users can be granted permission to execute a stored procedure even if they do not have permission to execute the procedure's statements directly.

DBCC (DATABASE CONSOLE COMMANDS) COMMANDS

 > DBCC commands are used to check the consistency of the database or database objects. While executing DBCC commands the DB engine creates a database snapshot and then runs the checks against this snapshot. After the DBCC command is completed, this snapshot is dropped.

> It’s consuming hardware resources. The DBCC commands are most useful for performance and troubleshooting exercises.

DBCC commands broadly falls into four categories:

 Maintenance

 Informational

 Validation

 Miscellaneous

MAINTENANCE COMMANDS:

Perform the maintenance tasks on a database, index, or filegroup.

CLEANTABLE:

> Reclaims space from dropped variable-length columns in tables or indexed views.

DBCC CLEANTABLE (‘Database name’, ‘Table name’, size)

DBREINDEX:

> Rebuilds one or more indexes for a table in the specified database.

DBCC DBREINDEX (‘Table name’, ‘Index name’, Fill factor)

DROPCLEANBUFFERS:

> Removes all clean buffers from the buffer pool.

DBCC DROPCLEANBUFFERS

FREEPROCCACHE:

> Removes all elements from the plan cache, removes a specific plan from the plan cache by specifying a plan handle or SQL handle, or removes all cache entries associated with a specified resource pool.

DBCC FREEPROCCACHE

INDEXDEFRAG:

> Defragments indexes of the specified table or view.

DBCC INDEXDEFRAG (‘Database name’,’Table name’,’index name, partition number’)

SHRINK DATABASE:

> Shrinks the size of the data and log files in the specified database.

DBCC SHRINKDATABASE (‘Database name’, target percentage)

SHRINKFILE:

> Shrinks the size of the specified data or log file for the current database, or empties a file by moving the data from the specified file to other files in the same filegroup, allowing the file to be removed from the database. You can shrink a file to a size that is less than the size specified when it was created. This resets the minimum file size to the new value.

DBCC SHRINKFILE (‘File name’, target percentage)

INFORMATIONAL COMMANDS:

Performs tasks that gather and display various types of information.

CONCURRENCYVIOLATION:

> Is maintained for backward compatibility. It runs but returns no data.

DBCC CONCURRENCYVIOLAION

UPDATEUSAGE:

> Reports and corrects pages and row count inaccuracies in the catalog views. These inaccuracies may cause incorrect space usage reports returned by the sp_spaceused system stored procedure.

DBCC UPDATEUSAGE (‘Database name’)

INPUTBUFFER:

> Displays the last statement sent from a client to an instance of Microsoft SQL Server 2005.

DBCC INPUTBUFFER (session id)

OPENTRAN:

> Displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions.

DBCC OPENTRAN (‘database name’)

OUTPUTBUFFER:

> Returns the current output buffer in hexadecimal and ASCII format for the specified session_id.


DBCC OUTPUTBUFFER (session id)

PROCCACHE:

> Displays information in a table format about the procedure cache.

DBCC PROCCACHE

SHOW_STATISTICS:

> Displays the current distribution statistics for the specified target on the specified table.

DBCC SHOW_STATISTICS (table or index view name’, target)

SHOWCONTIG:

> Displays fragmentation information for the data and indexes of the specified table or view.

DBCC SHOWCONTIG (‘table name’)

SQLPERF:

> Provides the transaction log space usage statistics for all databases. It can also be used to reset wait and latch statistics.

DBCC SQLPERF (LOGSPACE)

TRACESTATUS:

> Display the status of trace flags.

DBCC TRACESTATUS (Trace number)

USEROPTIONS:

> Returns the SET options active (set) for the current connection.

DBCC USEROPTIONS

VALIDATION COMMANDS:

> Performs validation operations on a database, table, index, catalog, filegroup, or allocation of database pages.

CHECKALLOC:

> Checks the consistency of disk space allocation structures for a specified database.

DBCC CHECKALLOC (‘Database name’)

CHECKCATALOG:

> Checks for catalog consistency within the specified database.

DBCC CHECKCATALOG (‘Database name’)

CHECKCONSTRAINTS:

> Checks the integrity of a specified constraint or all constraints on a specified table in the current database.

DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS

CHECKDB:

> Checks the logical and physical integrity of all the objects in the specified database.

DBCC CHECKDB (‘Database name)

CHECKFILEGROUP:

> Checks the allocation and structural integrity of all tables and indexed views in the specified filegroup of the current database.



Log Shipping Article

List of Tables & Stored Procedures


Primary server tables



                      Table

                                  Description

Stores alert job ID. This table is only used on the primary server if a remote monitor server has not been configured.

Stores error detail for log shipping jobs associated with this primary server.

Stores history detail for log shipping jobs associated with this primary server.

Stores one monitor record for this primary database.

Contains configuration information for primary databases on a given server. Stores one row per primary database.
Maps primary databases to secondary databases.


Primary Server Stored Procedures


Stored Procedure

Description

Sets up the primary database for a log shipping configuration, including the backup job, local monitor record, and remote monitor record.

Adds a secondary database name to an existing primary database.

Changes primary database settings including local and remote monitor record.

sp_cleanup_log_shipping_history
Cleans up history locally and on the monitor based on retention period.

Removes log shipping of primary database including backup job as well as local and remote history.

Removes a secondary database name from a primary database.

sp_help_log_shipping_primary_database
Retrieves primary database settings and displays the values from the log_shipping_primary_databases and log_shipping_monitor_primary tables.
sp_help_log_shipping_primary_secondaryRetrieves secondary database names for a primary database.

sp_help_log_shipping_primary_secondary

Retrieves secondary database names for a primary database.

sp_refresh_log_shipping_monitor

Refreshes the monitor with the latest information for the specified log shipping agent.

Secondary Server Tables

               
                     Table
                  
                        Description

log_shipping_monitor_alert
Stores alert job ID. This table is only used on the secondary server if a remote monitor server has not been configured.

Stores error detail for log shipping jobs associated with this secondary server.

log_shipping_monitor_history_detail
Stores history detail for log shipping jobs associated with this secondary server.

log_shipping_monitor_secondary
Stores one monitor record per secondary database associated with this secondary server.

log_shipping_secondary
Contains configuration information for the secondary databases on a given server. Stores one row per secondary ID.

log_shipping_secondary_databases
Stores configuration information for a given secondary database. Stores one row per secondary database.

Note: Secondary databases on the same secondary server for a given primary database share the settings in the log_shipping_secondary table. If a shared setting is altered for one secondary database, the setting is altered for all of them.

Secondary Server Stored Procedures


             Stored Procedures

                     Description

sp_add_log_shipping_secondary_database

Sets up a secondary database for log shipping.

sp_add_log_shipping_secondary_primary
Sets up the primary information, adds local and remote monitor links, and creates copy and restore jobs on the secondary server for the specified primary database.

sp_change_log_shipping_secondary_database
Changes secondary database settings including local and remote monitor records.

sp_change_log_shipping_secondary_primary
Changes secondary database settings such as source and destination directory, and file retention period.

sp_cleanup_log_shipping_history
Cleans up history locally and on the monitor based on retention period.

sp_delete_log_shipping_secondary_database
Removes a secondary database and the local history and remote history.

sp_delete_log_shipping_secondary_primaryRemoves the information about the specified primary server from the secondary server.
sp_help_log_shipping_secondary_databaseRetrieves secondary database settings from the log_shipping_secondary,log_shipping_secondary_databases, and log_shipping_monitor_secondary tables.
sp_help_log_shipping_secondary_primaryThis stored procedure retrieves the settings for a given primary database on the secondary server.
sp_refresh_log_shipping_monitorRefreshes the monitor with the latest information for the specified log shipping agent.

Monitor Server Tables

            
                      Table

                   Description
log_shipping_monitor_alertStores alert job ID.
log_shipping_monitor_error_detailStores error detail for log shipping jobs.
log_shipping_monitor_history_detailStores history detail for log shipping jobs.
log_shipping_monitor_primaryStores one monitor record per primary database associated with this monitor server.
log_shipping_monitor_secondaryStores one monitor record per secondary database associated with this monitor server.

Monitor Server Stored Procedures


                       Stored Procedures

                   Description

sp_add_log_shipping_alert_job
Creates a log shipping alert job if one has not already been created.

sp_delete_log_shipping_alert_job
Removes a log shipping alert job if there are no associated primary databases.
sp_help_log_shipping_alert_jobReturns the job ID of the alert job.

sp_help_log_shipping_monitor_primary
Returns monitor records for the specified primary database from the log_shipping_monitor_primary   table.

sp_help_log_shipping_monitor_secondary
Returns monitor records for the specified secondary database from the log_shipping_monitor_secondary table.