Thursday 21 February 2013

SQL Server Stored Procedure

Before Learning SQL SERVER STORED PROCEDURE Its better if you have a knowledge on  the concepts of Pl/Sql because whatever the programming syntax we are going to use is the shadow of PL/SQL syntex. So here you go for some of the PL/SQL concepts.

PL/SQL-  Procedural Language extension to SQL. And it is a technology mainly used in oracle database.

PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation in the early 90's to enhance the capabilities of SQL.
PL/SQL is one of three key programming languages embedded in the Oracle Database, along with SQL itself and Java.


 Following are notable facts about PL/SQL:
  • PL/SQL is a completely portable, high-performance transaction-processing language.
  • PL/SQL provides a built-in interpreted and OS independent programming environment.
  • PL/SQL can also directly be called from the command-line SQL*Plus interface.
  • Direct call can also be made from external programming language calls to database.
  • PL/SQL's general syntax is based on that of ADA and Pascal programming language.
  • Apart from Oracle, PL/SQL is available in TimesTen in-memory database and IBM DB2.

Features of PL/SQL

PL/SQL has the following features:
  • PL/SQL is tightly integrated with SQL.
  • It offers extensive error checking.
  • It offers numerous data types.
  • It offers a variety of programming structures.
  • It supports structured programming through functions and procedures.
  • It supports object oriented programming.
  • It supports developing web applications and server pages.

Advantages of PL/SQL

PL/SQL has the following advantages:
  • SQL is the standard database language and PL/SQL is strongly integrated with SQL. PL/SQL supports both static and dynamic SQL.
    •  Static SQL supports DML operations and transaction control from PL/SQL block. 
    •  Dynamic SQL is SQL allows embedding DDL statements in PL/SQL blocks. 
  • PL/SQL allows sending an entire block of statements to the database at one time. This reduces network traffic and provides high performance for the applications.
  • PL/SQL give high productivity to programmers as it can query, transform, and update data in a database.
  • PL/SQL saves time on design and debugging by strong features, such as exception handling, encapsulation, data hiding, and object-oriented data types.
  • Applications written in PL/SQL are fully portable.
  • PL/SQL provides high security level.
  • PL/SQL provides access to predefined SQL packages.
  • PL/SQL provides support for Object-Oriented Programming.
  • PL/SQL provides support for Developing Web Applications and Server Pages.
 PL/SQL is not a stand-alone programming language; it is a tool within the Oracle programming environment. SQL* Plus is an interactive tool that allows you to type SQL and PL/SQL statements at the command prompt. These commands are then sent to the database for processing. Once the statements are processed, the results are sent back and displayed on screen.

PL/SQL Command Prompt

Text Editor

Running large programs from command prompt may land you in inadvertently losing some of the work. So a better option is to use command files. To use the command files:
  • Type your code in a text editor, like Notepad, Notepad+, or EditPlus etc.
  • Save the file with the .sql extension in the home directory.
  • Launch SQL*Plus command prompt from the directory where you created your PL/SQL file.
  • Type @file_name at the SQL*Plus command prompt to execute your program.
If you are not using a file to execute PL/SQL scripts, then simply copy your PL/SQL code and then right click on the black window having SQL prompt and use paste option to paste complete code at the command prompt. Finally, just press enter to execute the code, if it is not already executed.

PL/SQL is a block-structured language, meaning that PL/SQL programs are divided and written in logical blocks of code. Each block consists of three sub-parts:
S.N.Sections & Description
1Declarations
This section starts with the keyword DECLARE. It is an optional section and defines all variables, cursors, subprograms, and other elements to be used in the program.
2Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It consists of the executable PL/SQL statements of the program. It should have at least one executable line of code, which may be just a NULL command to indicate that nothing should be executed.
3Exception Handling
This section section starts with the keyword EXCEPTION. This section is again optional and contains exception(s) that handle errors in the program.
Every PL/SQL statement end with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL blocks using BEGIN and END. Here is the basic structure of a PL/SQL block:

DECLARE
   <declarations section>
BEGIN
   <executable command(s)>
EXCEPTION
   <exception handling>
END;

The 'Hello World' Example:

DECLARE
   message  varchar2(20):= 'Hello, World!';
BEGIN
   dbms_output.put_line(message);
END;
/
The end; line signals the end of the PL/SQL block. To run the code from SQL command line, you may need to type / at the beginning of the first blank line after the last line of the code. When the above code is executed at SQL prompt, it produces following result:
Hello World

PL/SQL procedure successfully completed.

The PL/SQL Identifiers

PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved words. The identifiers consist of a letter optionally followed by more letters, numerals, dollar signs, underscores, and number signs and should not exceed 30 characters.
By default, identifiers are not case-sensitive. So you can use integer or INTEGER to represent a numeric value. You cannot use a reserved keyword as an identifier.


The PL/SQL Comments

Program comments are explanatory statements that you can include in the PL/SQL code that you write and helps anyone reading it's source code. All programming languages allow for some form of comments.
The PL/SQL supports single line and multi-line comments. All characters available inside any comment are ignored by PL/SQL compiler. The PL/SQL single-line comments start with the delimiter -- (double hyphen) and multi-line comments are enclosed by /* and */.


DECLARE
   -- variable declaration
   message  varchar2(20):= 'Hello, World!';
BEGIN
   /*
    *  PL/SQL executable statement(s)
    */
   dbms_output.put_line(message);
END;
/
When the above code is executed at SQL prompt, it produces following result:
Hello World

PL/SQL procedure successfully completed. 
 
 
and i requested to you please do some of the assignments on pl/sql.Here are some of the link
 
http://www.codeproject.com/Articles/38682/Overview-of-SQL-Server-Stored-Procedure

 http://www.mssqltips.com/sqlservertutorial/164/using-try-catch-in-sql-server-stored-procedures/
 



Now comes to our real Topic STORED PROCEDURE:-

A stored procedure is nothing more than prepared SQL code (collection of the sql queries) that you save so you can reuse the code over and over again.  So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a stored procedure and then just call the stored procedure to execute the SQL code that you saved as part of the stored procedure.


In addition to running the same SQL code over and over again you also have the ability to pass parameters to the stored procedure, so depending on what the need is the stored procedure can act accordingly based on the parameter values that were passed.



Stored procedures are more than just tools for performing repetitive tasks. There are two main types of stored procedure – system stored procedures and user-defined stored procedures. We also have extended stored procedures that can reside as either system or user-defined types. Extended stored procedures give functionality that is not necessarily contained within SQL Server, like allowing DOS commands to run and working with e-mail. It is also possible to create your own extended stored procedures. 

Creating a simple stored procedure

As mentioned , a stored procedure is nothing more than stored SQL code that you would like to use over and over again.  In this example we will look at creating a simple stored procedure. 



So the simple T-SQL code would be as follows which will return all rows from this table.

SELECT * FROM Works.Person.Address


To create a stored procedure to do this the code would look like this:

CREATE PROCEDURE uspGetAddress
 
 AS
 
 SELECT * FROM Works.Person.Address
GO
 
 
 
To call the procedure to return the contents from the table specified, the code would be:

EXEC uspGetAddress
--or just simply
uspGetAddress


CREATE PROCEDURE dbo.StoredProcedureName
/*
(
@parameter1 datatype = default value,

@parameter2 datatype OUTPUT

)

*/
AS

/* Place your Query here */
RETURN

Example 1:

Create PROCEDURE dbo.GetAllEmployees
As

Select * from Employee

Execution query :

exec GetAllEmployees

Example 2:

ALTER PROCEDURE dbo.GetEmployee
@empid int
As

Select * from Employee where Employee.EmployeeID=@empid

Execution Query :

exec dbo.GetEmployee 1

Example 3:

Create PROCEDURE dbo.UpdateEmpNationalID

(

@empid int
,@newcontactid int
,@oldcontactno int OUTPUT

)

AS

Select @oldcontactno=[ContactID]
FROM [dbo].[Employee] where [Employee].EmployeeID=@empid

if(@oldcontactno=@newcontactid)
begin

RETURN 0

end

else
begin

update Employee set ContactID=@newcontactid where Employee.EmployeeID=@empid

return 1
end

Execution Query:

Declare @oldcontactno int
Declare @returnvalue int
exec @returnvalue=UpdateEmpNationalID 1,123,@oldcontactno output

Select @oldcontactno 'Old Contact'
Select @returnvalue 'Returned value'


When creating a stored procedure you can either use CREATE PROCEDURE or CREATE PROC.  After the stored procedure name you need to use the keyword "AS" and then the rest is just the regular SQL code that you would normally execute.


On thing to note is that you cannot use the keyword "GO" in the stored procedure.  Once the SQL Server compiler sees "GO" it assumes it is the end of the batch.


Also, you can not change database context within the stored procedure such as using "USE dbName" the reason for this is because this would be a separate batch and a stored procedure is a collection of only one batch of statements.

 HOW TO CALL STORED PROCEDURE?

The simple answer for this question is by passing parameters

How to create a SQL Server stored procedure with parameters:

The real power of stored procedures is the ability to pass parameters and have the stored procedure handle the differing requests that are made.  In this topic we will look at passing parameter values to a stored procedure. 
 ExplanationJust like you have the ability to use parameters with your SQL code you can also setup your stored procedures to except one or more parameter values.

One Parameter
In this example we will query the Person.Address table from the Works database, but instead of getting back all records we will limit it to just a particular city.  This example assumes there will be an exact match on the City value that is passed.

CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT * 
FROM Works.Person.Address
WHERE City = @City
GO

To call this stored procedure we would execute it as follows:

EXEC uspGetAddress @City = 'India'


We can also do the same thing, but allow the users to give us a starting point to search the data.  Here we can change the "=" to a LIKE and use the "%" wildcard.

CREATE PROCEDURE uspGetAddress @City nvarchar(30) 
AS 
SELECT * 
FROM Works.Person.Address 
WHERE City LIKE @City + '%' 
GO

In both of the proceeding examples it assumes that a parameter value will always be passed. If you try to execute the procedure without passing a parameter value you will get an error message such as the following:

Msg 201, Level 16, State 4, Procedure uspGetAddress, Line 0

Procedure or function 'uspGetAddress' expects parameter '@City', which was not supplied.


Default Parameter Values
In most cases it is always a good practice to pass in all parameter values, but sometimes it is not possible.  So in this example we use the NULL option to allow you to not pass in a parameter value.  If we create and run this stored procedure as is it will not return any data, because it is looking for any City values that equal NULL.


CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL
AS
SELECT *
FROM Works.Person.Address
WHERE City = @City
GO

We could change this stored procedure and use the ISNULL function to get around this.  So if a value is passed it will use the value to narrow the result set and if a value is not passed it will return all records.

CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL
AS
SELECT *
FROM Works.Person.Address
WHERE City = ISNULL(@City,City)
GO

Multiple Parameters
Setting up multiple parameters is very easy to do.  You just need to list each parameter and the data type separated by a comma as shown below.

CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL, @AddressLine1 nvarchar(60) = NULL
AS
SELECT *
FROM Works.Person.Address
WHERE City = ISNULL(@City,City)
AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1 ,AddressLine1) + '%'
GO

To execute this you could do any of the following:
EXEC uspGetAddress @City = 'Calgary'
--or
EXEC uspGetAddress @City = 'Calgary', @AddressLine1 = 'A'
--or
EXEC uspGetAddress @AddressLine1 = 'Acardia'
-- etc...
 
 
 User Defined Functions (UDFs)

User defined functions are routines that encapsulates SQL logic inside it. Like stored procedures User
defined functions can also be passed input parameters but user defined functions are compiled and
executed at runtime so pretty slower than stored procedures.

Syntax:

CREATE FUNCTION dbo.Function
(
/*
@parameter1 datatype = default value,
@parameter2 datatype
*/
)
RETURNS /* datatype */
AS

BEGIN
/* sql statement ... */
RETURN /* value */
END

Certain limitations for User defined functions:

i)
  UDF can’t perform DML (data manipulation language) operations like Insertion,  Update and Deletion on the base table.

ii)
  UDF can’t return non deterministic values like GETDATE () etc.

iii) Stored procedure can’t be called from inside a UDF whereas a stored procedure can call a  user defined function or another stored procedure inside it.



There are three types of user defined functions:

1) Scalar Functions (returns a single value)

Example:

CREATE FUNCTION EmployeeContactID(@Empid int)
RETURNS int
AS
BEGIN

Declare @returnvalue int
Select @returnvalue=Employee.ContactID from Employee where
Employee.EmployeeID=@Empid
RETURN
@returnvalue
END

Execution:
select dbo.EmployeeContactID(1)

2) Inline Functions (returns a table)

Example:

CREATE FUNCTION dbo.GetEmployeeFunction(@empid int)
RETURNS TABLE
AS
RETURN SELECT *
FROM employee where employee.EmployeeID=@empid

Execution:

select * from dbo.GetEmployeeFunction(1)

3) Table valued Functions ( multiple operations, complex logic just like Stored procedures)

Example:

CREATE FUNCTION dbo.multi_test(@empid int)
RETURNS @Result TABLE
(
name varchar(20)
)
AS
BEGIN
INSERT INTO @Result
(name)
SELECT [name] from employee where EmployeeID=1

UPDATE @Result
SET name = 'N'

RETURN

END

Exectution :

Select * from dbo.multi_test(1)



Difference between Stored procedures and User defined functions:

i)
A stored procedure is pre compiled while a User defined function is compiled and executed at runtime.

ii)
A Stored procedure is more flexible than user defined function like you can write complex logic (for example exceptional handling using try catch block is possible in stored procedures which is not possible in user defined functions)

iii)
A stored procedure can call another stored procedure or user defined function inside it but a user defined function can’t call stored procedure inside it.

iv)
A stored procedure can return non deterministic values but a user defined function can’t return a non deterministic values like Get Date () function.

v)
A user defined functions does not support DML operations like insertion, deletion and update on the base table but it is possible via stored procedure.

vi)
A user defined function is easier to execute and can be used inside selection and even for joins but stored procedure can’t be used inside selection queries and it can’t be used to join with other tables.