Monday, September 8, 2014

Stored Procedures in SQL Server

In this article, I am giving a quick overview about Stored Procedure in SQL Server. After completing this article you will understand:

What is mean by Stored Procedure?
How to Create, Alter and Drop Stored Procedure in SQL Server?
How to do Error Handling in Stored Procedure?
What are the advantages of Stored Procedure?
What is the difference between Stored Procedure and User Defined Functions?
How to manage Transactions in Stored Procedure?

Please give your valuable suggestions and feedback to improve this article.

I have already discussed TSQL Programming Basics in SQL Server in my previous post; I will recommend you to go through this post before you start on Stored Procedure.

I hope you have gone through the basics of TSL Programming basics, now we can start.

As you know we have two types of blocks in TSQL programming, Anonymous Blocks and Sub-Program Blocks.

Sub Program blocks are of two types in SQL Server.

1. Procedures

In this article I will be focusing on Procedures, because both of the topics are very vast so I will be writing another article on functions.

What is mean by Stored Procedure?

A Stored Procedure is a saved collection of TSQL statement that you can reuse over and over again.

Let’s understand what does the above line mean? generally you write and use a SQL Query over and over again but instead of writing the SQL query again and again you can write once and save it in SQL Server with a name, later whenever you want you can call your stored query by its name. This sorted query will be known as Stored Procedure.

In addition stored procedures provide input and output parameters, depending on your input parameters stored procedure can return needed result set.Stored Procedure can run independently, it can be executed using EXEC or EXECUTE command. The greatest advantage of stored procedure is we can do Error handling using TRY, CATCH statements in Stored Procedure.

How to Create, Alter, Drop Stored Procedure in SQL Server?

Here we will understand how to create simple stored procedure, We will also create Stored Procedure with more advanced options later in this article.

Before I start with the example, let’s understand the syntax we use to create a simple stored procedure.

Syntax to create stored procedure

CREATE PROCEDURE <Procedure-Name> (
@parameter 1 data-type [=default] [out |output],
@parameter 2 data-type [=default] [out |output],
………
@parameter n data-type [=default] [out |output]
)
WITH <Procedure-Options>
AS
BEGIN
<SQL-Statements>
END

<Procedure-Name>: This is the procedure name you will give to store your query in SQL Server; you have to remember this name because you call the procedure using its name.
<Parameter-type>: Here you define your stored procedure parameter and parameter mode i.e. input or output.
<Procedure-Options>: There are two stored procedure options Encryption and Recompile. I will explain this with examples later in this article.
<SQL-Statements>: Here you write your SQL query which will be stored and executed on call.

Let’s create a simple Stored Procedure.

Stored Procedure can be created either by CREATE PROCEDURE or CREATE PROC, after giving the Stored Procedure name we need to use AS keyword. Just after the AS keyword we write our regular SQL query. If we have multiple statements then we keep it in BLOCK otherwise we can directly write the SQL Statement.

We need some data in our TEACHMESQLSERVER database, let’s populate some data.

If you don’t have TEACHMESQLSERVER database in your SQL Server instance then please use below query to create the database.

CREATE DATABASE TEACHMESQLSERVER

Let's populate some data. 

USE TEACHMESQLSERVER
GO
IF OBJECT_ID('EMP','U') IS NOT NULL
DROP TABLE EMP
CREATE TABLE EMP(EMPID INT, EMPNAME VARCHAR(MAX))
INSERT INTO EMP VALUES(1,'GHANESH'),(2,'PRASAD'),(3,'GAUTAM'),(4, 'ANVIE')
GO
SELECT * FROM EMP

As you can see from the above result set we have successfully populated the data. Suppose SELECT * FROM EMP is the query you write and run again and again. In this example I am using the simplest example to understand the concept but in real world it will be a set of SQL Statements.

Let’s create a stored procedure for this.

CREATE PROCEDURE EMPLIST AS
SELECT * FROM EMP

Congratulations you have successfully created your first stored procedure. You can find list of all stored procedure from sys.Procedures table using the below query

GO
SELECT * FROM SYS.procedures


As you can see from the result set of above query, EMPLIST is a SQL Stored Procedure. You can also find the other related information.

You can also find the list of Stored Procedures using object explorer in SQL Server Management Studio.

Follow the below path
As you can see under the Stored Procedures folder, our recently created EMPLIST stored procedure is saved.

Now let’s execute recently created EMPLIST stored procedure. We can execute stored procedure using EXEC or EXECUTE command.

EXEC EMPLIST
or
EXECUTE EMPLIST 

As you can see it is returning the list of all employees present in the EMP table.

Stored Procedures with Parameter

We have already created a simple stored procedure without any parameter; we can create Procedures with parameters which mean we can pass parameters to Procedure; they are the means to pass a value to the procedure or returns from a procedure.These modes will specify whether the parameter is passed into the procedure or returned out of the procedure.

There are two modes of parameters in Stored Procedure.

1.       IN MODE (DEFAULT)
2.       OUT or OUTPUT MODE

IN MODE- Passes a value into the procedure for execution this is the best suitable for Constants and expressions. The value of the parameter can be changed in the program but it can’t be returned. It is the default mode if nothing is specified.

OUT MODE- Passes a value back from the program after the execution of the procedure. The value of this option can be returned to the calling EXECUTE statement. Use OUTPUT parameter to return values to the caller of the procedure. Text, ntext, Image data type parameters cannot be used as OUTPUT parameters. Stored Procedure can’t return table variable.

Now let’s create little complex stored procedure using input parameters.

1.       Input parameters

Problem- How can you get employees details based on EMPID?
Solution- Yes you are correct, you can write a select statement and can use where clause on EMPID.
SQL code- SELECT * FROM EMP WHERE EMPID=1

You can modify your Stored Procedure using ALTER; you can use ALTER PROCEDURE at place of CREATE PROCEDURE.

Now let’s modify the stored procedure which takes Input parameter for EMPID and returns the result based on the input parameter.We will modify our EMPLIST stored procedure for the above problem.

ALTER PROCEDURE EMPLIST (@EMPID INT)
AS
SELECT * FROM EMP WHERE EMPID= @EMPID

You have successfully modified the EMPLIST stored procedure. As you can see from the above query your procedure is having one parameter, we have also modified the SQL statement. @EMPID parameter is passed in the SQL Query, based on this parameter value our procedure will return the result set.

Now let’s execute the procedure

GO
EXEC EMPLIST

Once you ran the above query you got an error message as shown below.


As you know we had modified our stored procedure, which is expecting the input parameter value but we didn’t give it at the time of execution.

There are multiple ways to assign parameter value, now let’s execute the procedure with input parameter value using any of the below method.

GO
EXEC EMPLIST 1

OR

EXEC EMPLIST @EMPID=1

Bingo our above procedure ran successfully for both of the above execute statements and returned the expected result set. 

Default Parameter values

As you know now when you don’t give your parameter value at the time of execution it ends up with an error message. If you don’t want this to happen then you can set a default value for your input parameter. In below example we will be doing the same.

Let’s modify the EMPLIST stored procedure with input parameter default value.

ALTER PROCEDURE EMPLIST (@EMPID INT =1 )
AS
SELECT * FROM EMP WHERE EMPID= @EMPID

As you can see from the above SQL Statement this time we have given 1 value for @EMPID input parameter.

Now let’s execute the procedure using any of the below method.

GO
EXEC EMPLIST

OR

EXEC EMPLIST @EMPID=2

OR

EXEC EMPLIST Default

OR

EXEC EMPLIST @EMPID=Default

Bingo this time our above execute statement ran successfully and returned the expected result set.This time It didn’t give any error; you can change your parameter value as we did in previous exercise.

Multiple Parameters

Setting up multiple parameters is not very difficult; you have to separate your each parameter using comma separator. At the time of execution also you have to use comma separator.

2.       Output Parameters

This is another advantage of Stored Procedure. It can take input from parameter and it can return parameter. This can be helpful when you call another stored procedure that does not return any data, but returns parameter values to be used by the calling stored procedure.

Let’s understand how to create procedure with output parameters.

Problem- How to return all records count from EMP table using stored procedure?
Solution- You can create stored procedure with OUTPUT parameter mode.
SQL Code-

ALTER PROCEDURE EMPLIST (@RECORDCOUNT INT OUTPUT)
AS
SELECT @RECORDCOUNT=COUNT(*) FROM EMP
GO
As you can see from the above query, we have modified our procedure with one OUTPUT parameter. @RECORDCOUNT is returning the count of all records from EMP table.

As you know we are returning parameter value from above query, so we have to capture the returned value into a variable. We have to define a variable to capture the returned parameter value otherwise it will throw error.

DECLARE @ALLRECORDCOUNT INT
EXECUTE EMPLIST @ALLRECORDCOUNT OUTPUT
SELECT @ALLRECORDCOUNT

Stored Procedure Advanced Options

We can create stored procedure with two advanced options.

1-      Encryption
2-      Recompile

Encryption – when we create any procedure with encryption option then its definition information will be hidden, which means No user can see stored procedure’s definition from the system tables.

Example- I am modifying the previously created stored procedure with encryption option.

ALTER PROCEDURE EMPLIST WITH ENCRYPTION
AS
SELECT * FROM EMP

We have created the stored procedure with encryption option, now no user can see the definition of stored procedure using SP_HELPTEXT system stored procedure.


EXEC SP_HELPTEXT EMPLIST

Recompile – Database engine always cache execution plan when we execute stored procedure. When we create stored procedure with RECOMPILE option it indicates that database engine will not cache a plan for this procedure and every time procedure is compiled at run time. To instruct the database engine to discard plans for the individual queries inside a stored procedure, use the RECOMPLIE query hint.

Example- I am modifying the previously created stored procedure with recompile option.

ALTER PROCEDURE EMPLIST WITH ENCRYPTION
AS
SELECT * FROM EMP
  
Other Stored Procedure Examples

EXAMPLE 1 : ADDING TWO NUMBERS

USE TEACHMESQLSERVER
GO
CREATE PROCEDURE MYSECONDPROCEDURE (@X INT,@Y INT)
AS
BEGIN
DECLARE @Z INT
SET @z=@X+@Y
PRINT @Z
END
GO
EXEC MYSECONDPROCEDURE 10,20

EXAMPLE 2: INSERTING RECORDS IN EMP TABLE USING STORED PROCEDURE.

USE TEACHMESQLSERVER
GO
CREATE PROCEDURE INSERTEMP (@EMPNO INT,@EMPNAME VARCHAR (20))
AS
BEGIN
INSERT INTO EMP  VALUES(@EMPNO,@EMPNAME)
END
GO
EXECUTE  INSERTEMP  10,'RAKESH'
GO
SELECT * FROM EMP

We can drop Stored Procedure using Drop command, using the below syntax.

DROP PROCEDURE ProcedureName


i.e DROP PROCEDURE EMPLIST

How to do Error Handling in Stored Procedure?
I have created a separate article on error handling in Stored Procedure.  Please click here to understand how to do error handling in Stored Procedure.  

What are the advantages of Stored Procedure?
I have created a separate article on advantages of Stored Procedure.  Please click here to understand the advantages of Stored Procedure in SQL Server.

What is the difference between Stored Procedure and User Defined Functions?
I have created a separate article for this topic.  Please click here to understand what are the differences between Stored Procedure and User Defined Functions in SQL Server?

How to manage Transactions in Stored Procedure?
I have created a separate article for this topic.  Please click here to understand how to manage Transactions in Stored Procedure in SQL Server?

I hope you enjoyed the article don't forget to share on Facebook.

Keep Learning !

Friday, September 5, 2014

DBCC Commands in SQL Server

DBCC stands for Database Console Command, these commands are used for database maintenance, validation, informational and some other miscellaneous tasks. DBCC commands take input parameters and return values. DBCC commands accept both Unicode and DBCS literals. It can also be run from Command line or query analyzer.

DBCC statements are grouped into the following categories.

DBCC Category
Perform
Maintenance
Used for Database, Index and Filegroup Maintenance.
Validation
Used for Database, Table, Index, Catalog, Filegroup and allocation of data pages Validations.
Informational
Used to gather various types of information from database.
Miscellaneous
Such as enabling trace flags or removing DDL from memory.

DBCC Maintenance Category Commands

Below is the list of all DBCC commands which are used for maintenance purpose.

DBCC CLEANTABLE
DBCC DBREINDEX
DBCC DROPCLEANBUFFERS
DBCC INDEXDEFRAG
DBCC SHRINKDATABASE
DBCC SHRINKFILE
DBCC FREEPROCCACHE
DBCC UPDATEUSAGE

DBCC CLEANTABLE
This DBCC command is used to remove spaces occupied by columns when they are removed.

DBCC DBREINDEX
This DBCC command is used to recreate the indexes for a particular table. This DBCC command rebuilds indexes in a single step. It also assigns fresh pages to reduce internal and external fragmentation.

DBCC DROPCLEANBUFFERS
This DBCC command is used to drop clean buffers from the buffer pool.

DBCC INDEXDEFRAG
This DBCC command is used to defragment the clustered and secondary indexes associated with the particular table. The index defragmentation is carried out using the fill factor specified at the time of creation of indexes. While its operation is strikingly similar to that of DBCC DBREINDEX, unlike DBCC INDEXFRAG it does not allow new fill factor to be specified.

DBCC SHRINKDATABASE
This DBCC command is used to reduce the size of a database. This DBCC command reduces the physical size of the database log file. An alternate way to shrink a database is to use the commander ALTER DATABASE.

DBCC SHRINKFILE
This DBCC command is used to reduce the size of a data file or log file of a particular database. The file could also be shrunk by using the SHRINKFILE attribute of the ALTER DATABASE command.

DBCC FREEPROCCACHE
This DBCC command is used to remove all elements from the procedure cache.

DBCC UPDATEUSAGE
This DBCC command is used to correct inaccuracies in the page and row statistics in the views.

DBCC Validation Category Commands

Below is the list of all DBCC commands which are used for validation purpose.

When you execute one of these DBCC commands, the Database Engine creates a database snapshot and brings it to a transactionally consistent state. The DBCC command then runs the checks against this snapshot. After the DBCC command is completed, this snapshot is dropped.
Sometimes an internal database snapshot is not required or cannot be created. When this occurs, the DBCC command executes against the actual database. If the database is online, the DBCC command uses table-locking to ensure the consistency of the objects that it is checking.

DBCC CHECKALLOC
DBCC CHECKDB
DBCC CHECKTABLE
DBCC CHECKCATALOG
DBCC CHECKFILEGROUP
DBCC CHECKIDENT
DBCC CHECKCONSTRAINTS

DBCC CHECKALLOC
This DBCC command is used to checks whether every extent allocated by the system has been allocated and whether there are extents that have not been allocated.

DBCC CHECKDB
This DBCC command is used to check integrity and allocation of specific objects in a database. 

DBCC CHECKTABLE
This DBCC command is used to check the integrity of a table and all the pages and structures which comprise the table. Both physical and logical checks are performed in this case. However, a PHYSICAL ONLY option can be used to check for physical consistency alone.

DBCC CHECKCATALOG
This DBCC command is used to check for consistency between system tables in the system catalog

DBCC CHECKFILEGROUP
This DBCC command is used to check allocation and structural integrity of tables.

DBCC CHECKIDENT
This DBCC command is used to check identity value of specified table.

DBCC CHECKCONSTRAINTS
This DBCC command is used to check integrity of specific constraints.

DBCC Informational Category Commands

Below is the list of all DBCC commands which are used for informational purpose.

DBCC INPUTBUFFER
DBCC OPENTRAN
DBCC SQLPERF
DBCC OUTPUTBUFFER
DBCC SHOW_STATISTICS
DBCC TRACESTATUS
DBCC PROCCACHE
DBCC SHOWCONTIG
DBCC USEROPTIONS

DBCC INPUTBUFFER
This DBCC command is used to display the last statement stored in the buffer.

DBCC OPENTRAN
This DBCC command is used to display information about the oldest open transaction.

DBCC SQLPERF
This DBCC command is used to show transaction log statistics

DBCC OUTPUTBUFFER
This DBCC command is used to return the current value of the output buffer.

DBCC SHOW_STATISTICS
This DBCC command is used to show current distribution statistics

DBCC TRACESTATUS
This DBCC command is used to display status of trace flags.

DBCC PROCCACHE
This DBCC command is used to display information about procedure cache.

DBCC SHOWCONTIG
This DBCC command is used to display fragmentation information

DBCC USEROPTIONS
This DBCC command is used to return set as ACTIVE

DBCC Miscellaneous Category Commands

Below is the list of all DBCC miscellaneous commands.

DBCC DLLNAME(FREE)
DBCC FREESYSTEMCACHE
DBCC TRACEON
DBCC FREESESSIONCACHE
DBCC HELP
DBCC TRACEOFF


DBCC dllname (FREE)
This DBCC command is used to unload a particular stored procedure DLL from memory.

DBCC HELP
This DBCC command is used to return syntax information.

DBCC TRACEOFF
This DBCC command is used to disable a trace flag.

DBCC TRACEON
This DBCC command is used to turn on a specific trace flag.

DBCC FREESESSIONCACHE
This DBCC command is used to free the session cache.

DBCC FREESYSTEMCACHE
This DBCC command is used to free system cache.

I hope you enjoyed the article don't forget to share on Facebook.

Keep Learning !

Thursday, September 4, 2014

Deterministic and Non-deterministic Functions in SQL Server

In this article, I am giving a quick overview about Deterministic and Non-deterministic Functions in SQL Server. After completing this article you will understand:

What is Deterministic and Non-deterministic Functions?
What are different Deterministic and Non-deterministic Functions in SQL Server?

Please give your valuable suggestions and feedback to improve this article.

What is Deterministic and Non-deterministic Functions?

Deterministic functions always return the same result any time they are called with a specific set of input values and given the same state of the database.

For example, the function AVG always returns the same result given the qualifications stated above

Nondeterministic functions may return different results each time they are called with a specific set of input values even if the database state that they access remains the same.


For example, the GETDATE function, which returns the current datetime value, always returns a different result at every run.

What are different Deterministic and Non-deterministic Functions in SQL Server?


Deterministic Functions in SQL SERVER

All built-in string functions are deterministic.

ASCII
CHAR
CHARINDEX
CONCAT
DIFFERENCE
FORMAT
LEFT
LEN
LOWER
LTRIM
NCHAR
PATINDEX
QUOTENAME
REPLACE
REPLICATE
REVERSE
RIGHT
RTRIM
SOUNDEX
SPACE
STR
STUFF
SUBSTRING
UNICODE
UPPER






The following built-in functions always deterministic.

ABS
ACOS
ASIN
ATAN
ATN2
CEILING
COALESCE
COS
COT
DATALENGTH
ADDDATE
DATEDIFF
DAY
DEGREE
EXP
FLOOR
ISNULL
ISNUMERIC
LOG
LOG10
MONTH
NULLIF
POWER
RADIANS
ROUND
SIGN
SIN
SQUARE
SQRT
TAN
YEAR






The following functions are not always deterministic.

ALL AGGREGRATE FUNCTION
CAST
CONVERT
CHECKSUM
ISDATE
RAND

Non-Deterministic Functions in SQL SERVER

The following built-in functions are always nondeterministic.

@@CONNECTIONS
@@TIMETICKS
NEWID
GETUTCDATE
@@CPU_BUSY
@@TOTAL_ERRORS
NEWSEQUENTIALID
GET_TRANSMISSION_STATUS
@@DBTS
@@TOTAL_READ
NEXT VALUE FOR
LAG
@@IDLE
  @@TOTAL_WRITE
NTILE
LAST_VALUE
@@IO_BUSY
CUME_DIST
PARSENAME
LEAD
@@MAX_CONNECTIONS
CURRENT_TIMESTAMP
PERCENTILE_CONT
MIN_ACTIVE_ROWVERSION
@@PACK_RECEIVED
DENSE_RANK
PERCENTILE_DISC
RAND
@@PACK_SENT
FIRST_VALUE
PERCENT_RANK
RANK
@@PACKET_ERRORS
GETDATE
ROW_NUMBER
TEXTPTR

All the configuration, cursor, metadata, security, and system statistical functions are non deterministic. 
Content taken from BOL.

If you liked the article hit the Facebook like button.

Keep Learning!