Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

What is a procedure:

A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over
again. So if you have an SQL query that you write over and over again, save it as a stored procedure, and
then just call it to execute it.
A stored procedure is a set of SQL statements, which has been created and stored in the database
as an object. Stored procedure will accept the input and output parameters, so that a single
procedure can be used over the network by several users, using different input. Stored procedure will
reduce the network traffic and increase the performance.
Real time scenario
Step 1: Create a table to describe and create the stored procedure.

1. create table Product  
2. (  
3.       ProductId int primary key,  
4.       ProductName varchar(20) unique,  
5.       ProductQty int,  
6.       ProductPrice float  
7. )  

Step 2: Insert some value to the describe scenario.

1. insert product values(1,'Printer',10,4500)  
2. insert product values(2,'Scanner',15,3500)  
3. insert product values(3,'Mouse',45,500)   

Step 3: Check your table with the inserted value.

1. select * from product   

Step 4: Real time scenario is given below:


Create a stored procedure, which is used to perform the requirements, given below:

1. Before inserting, check the detail about the product name. If the product name is available,
update an existing product qty + inserted product qty,
2. Before inserting, check the detail about the product name. If the product name is available,
check the product price. If the existing product price is less, the inserted product product price
replaces the existing product price with the inserted product price.
3. If first and second conditions are not satisfied, insert the product information, as new record into
the table.

1. create procedure prcInsert   
2. @id int,  
3. @name varchar(40),  
4. @qty int,  
5. @price float  
6. as  
7. begin  
8.  declare @cnt int  
9.  declare @p float  
10.  select @cnt=COUNT(ProductId)from Product where pname=@name  
11.  if(@cnt>0)  
12.  begin  
13.   update Product set ProductQty=ProductQty+@qty where ProductName=@name  
14.   select @p=ProductPrice from Product where ProductName=@name  
15.   if(@p<@price)  
16.   begin  
17.    update Product set ProductPrice=@price where ProductName=@name  
18.   end  
19.  end  
20.  else  
21.  begin  
22.   insert Product values(@id,@name,@qty,@price)  
23.  end  
24. end   

That's it. Thank you. If any suggestion or clarification is required, kindly revert back with the
comments. 
SQL Server stored procedures for beginners
July 29, 2019 by Ranga Babu

In this article, we will learn how to create stored procedures in SQL Server with different examples.

SQL Server stored procedure is a batch of statements grouped as a logical unit and stored in the database. The
stored procedure accepts the parameters and executes the T-SQL statements in the procedure, returns the result set
if any.

To understand differences between functions and stored procedures in SQL Server, you can refer to this
article, Functions vs stored procedures in SQL Server and to learn about Partial stored procedures in SQL Server,
click Partial stored procedures in SQL Server.

Benefits of using a stored procedure


It can be easily modified: We can easily modify the code inside the stored procedure without the need to restart or
deploying the application. For example, If the T-SQL queries are written in the application and if we need to change
the logic, we must change the code in the application and re-deploy it. SQL Server Stored procedures eliminate such
challenges by storing the code in the database. so, when we want to change the logic inside the procedure we can
just do it by simple ALTER PROCEDURE statement.

Reduced network traffic: When we use stored procedures instead of writing T-SQL queries at the application level,
only the procedure name is passed over the network instead of the whole T-SQL code.

Reusable: Stored procedures can be executed by multiple users or multiple client applications without the need of
writing the code again.

Security: Stored procedures reduce the threat by eliminating direct access to the tables. we can also encrypt the
stored procedures while creating them so that source code inside the stored procedure is not visible. Use third-party
tools like ApexSQL Decrypt to decrypt the encrypted stored procedures.

Performance: The SQL Server stored procedure when executed for the first time creates a plan and stores it in the
buffer pool so that the plan can be reused when it executes next time.

I am creating sample tables that will be used in the examples in this article.

1 CREATE TABLE Product

2 (ProductID INT, ProductName VARCHAR(100) )

3 GO

4  

5 CREATE TABLE ProductDescription

6 (ProductID INT, ProductDescription VARCHAR(800) )


7 GO

8  

9 INSERT INTO Product VALUES (680,'HL Road Frame - Black, 58')

10 ,(706,'HL Road Frame - Red, 58')

11 ,(707,'Sport-100 Helmet, Red')

12 GO

13  

14 INSERT INTO ProductDescription VALUES (680,'Replacement mountain wheel for entry-level rider.')

15 ,(706,'Sturdy alloy features a quick-release hub.')

16 ,(707,'Aerodynamic rims for smooth riding.')

17 GO

Creating a simple stored procedure


We will create a simple stored procedure that joins two tables and returns the result set as shown in the following
example.

1 CREATE PROCEDURE GetProductDesc

2 AS

3 BEGIN

4 SET NOCOUNT ON

5  

6 SELECT P.ProductID,P.ProductName,PD.ProductDescription  FROM

7 Product P

8 INNER JOIN ProductDescription PD ON P.ProductID=PD.ProductID

9  

10 END

We can use ‘EXEC ProcedureName’ to execute stored procedures. When we execute the procedure GetProductDesc,
the result set looks like below.
Creating a stored procedure with parameters
Let us create a SQL Server stored procedure that accepts the input parameters and processes the records based on
the input parameter.

Following is the example of a stored procedure that accepts the parameter.

1 CREATE PROCEDURE GetProductDesc_withparameters

2 (@PID INT)

3 AS

4 BEGIN

5 SET NOCOUNT ON

6  

7 SELECT P.ProductID,P.ProductName,PD.ProductDescription  FROM

8 Product P

9 INNER JOIN ProductDescription PD ON P.ProductID=PD.ProductID

10 WHERE P.ProductID=@PID

11  

12 END

1 EXEC GetProductDesc_withparameters 706

While executing the stored procedure we need to pass the input parameter. Please refer to the below image for the
result set.
Creating a stored procedure with default parameters values
Following is the example of a stored procedure with default parameter values.

1 CREATE PROCEDURE GetProductDesc_withDefaultparameters

2 (@PID INT =706)

3 AS

4 BEGIN

5 SET NOCOUNT ON

6  

7 SELECT P.ProductID,P.ProductName,PD.ProductDescription  FROM

8 Product P

9 INNER JOIN ProductDescription PD ON P.ProductID=PD.ProductID

10 WHERE P.ProductID=@PID

11  

12 END

When we execute the above procedure without passing the parameter value, the default value 706 will be used. But
when executed passing the value, the default value will be ignored and the passed value will be considered as a
parameter.
Creating a stored procedure with an output parameter
Below is the example of a stored procedure with an output parameter. The following example retrieves the EmpID
which is an auto identity column when a new employee is inserted.

1 CREATE TABLE Employee (EmpID int identity(1,1),EmpName varchar(500))

1 CREATE PROCEDURE ins_NewEmp_with_outputparamaters

2 (@Ename varchar(50),

3 @EId int output)

4 AS

5 BEGIN

6 SET NOCOUNT ON

7  

8 INSERT INTO Employee (EmpName) VALUES (@Ename)

9  

10 SELECT @EId= SCOPE_IDENTITY()

11  

12 END

Executing the stored procedures with output parameters is bit different. We must declare the variable to store the
value returned by the output parameter.

1 declare @EmpID INT

3 EXEC ins_NewEmp_with_outputparamaters 'Andrew', @EmpID OUTPUT

5 SELECT @EmpID
Creating an encrypted stored procedure
We can hide the source code in the stored procedure by creating the procedure with the “ENCRYPTION” option.

Following is the example of an encrypted stored procedure.

1 CREATE PROCEDURE GetEmployees

2 WITH ENCRYPTION

3 AS

4 BEGIN

5 SET NOCOUNT ON

7 SELECT EmpID,EmpName from Employee

8 END

When we try to view the code of the SQL Server stored procedure using sp_helptext, it returns “The text for object
‘GetEmployees’ is encrypted.”
When you try to script the encrypted stored procedure from SQL Server management studio, it throws an error as
below.

Creating a temporary procedure


Like the temporary table, we can create temporary procedures as well. There are two types of temporary procedures,
one is a local temporary stored procedure and another one is a global temporary procedure.

These procedures are created in the tempdb database.

Local temporary SQL Server stored procedures: These are created with # as prefix and can be accessed only in the
session where it created. This procedure is automatically dropped when the connection is closed.

Following is the example of creating a local temporary procedure.

1 CREATE PROCEDURE #Temp

2 AS

3 BEGIN

4 PRINT 'Local temp procedure'

5 END

Global temporary SQL Server stored procedure: These procedures are created with ## as prefix and can be
accessed on the other sessions as well. This procedure is automatically dropped when the connection which is used
to create the procedure is closed.
Below is the example of creating a global temporary procedure.

1 CREATE PROCEDURE ##TEMP

2 AS

3 BEGIN

4 PRINT 'Global temp procedure'

5 END

Modifying the stored procedure


Use the ALTER PROCEDURE statement to modify the existing stored procedure. Following is the example of
modifying the existing procedure.

1 ALTER PROCEDURE GetProductDesc

2 AS

3 BEGIN

4 SET NOCOUNT ON

5  

6 SELECT P.ProductID,P.ProductName,PD.ProductDescription  FROM

7 Product P

8 INNER JOIN ProductDescription PD ON P.ProductID=PD.ProductID

9  

10 END

Renaming the stored procedure


To rename a stored procedure using T-SQL, use system stored procedure sp_rename. Following is the example that
renames the procedure “GetProductDesc” to a new name “GetProductDesc_new”.

1 sp_rename 'GetProductDesc','GetProductDesc_new'

Conclusion
Table Functions in SAP HANA – step by step guide
3546117,312

SAP HANA Table Functions


Recently I spoke to multiple developers working on SAP HANA Native system for developing reports. What really surprised
me was the fact, that most of them are still using calculation views of a SQL Script type instead of Table Functions. What is
more, some of them were even not aware that these type of views are deprecated and replaced by Table Functions. I also
haven’t found any step by step tutorial describing when to create Table Functions, how to do that, what are the benefits and how
to consume them in calculation views.

This inspired me to write the article about Table Functions and share my experience on that topic.

What are Table Functions?


Since SP11 calculation views of SQL Script type are deprecated. As an alternative SAP introduced new development artifact
called Table Function. HANA provides Migration tool, which enables automatic conversion script-based Calculation View into
Table Function.

Table functions are used whenever the graphical views are not sufficient i.e. for loops, executing custom functions or complex
queries.

What are the Pros and Cons of using Table Functions?


Pros:

 SQL Script gives much more functionality and flexibility (more functions available, complex logic can be implemented
in easier way, SQL can be combined with Application Function Library – AFL giving even more functions for complex
analysis)

Cons:

 Maintenance is much more difficult (preserving order and data types of output columns; data preview for part of code
is not so straightforward comparing to previewing nodes in graphical views; when changing output – both Table
Function and view on top of it needs to be adjusted; etc.)
 Multiple-value input parameters are not supported (there is no easy way of passing multiple values into single input
parameter to Table Function, however there is workaround for that)
 By definition graphical views provide better performance thanks to HANA’s optimizer
 No GUI available – SQL Script knowledge is necessary

Generally Table Functions should are used in case if the logic cannot be covered by graphical view or the logic is too complex
to model it graphically.

How to create Table Function?


Scenario: Business wants to display a report showing number of working days between “ORDERDATE” and
“SHIPPEDDATE“. To calculate it we need to use WORKDAYS_BETWEEN SQL function, which is not available in graphical
view. Additionally this function should display orders only for specific period of time which will be provided by the user.

1. To start developing database objects, go to Development Perspective:


  

2. Go to Repositories tab:

3. Right click on destination package and select New -> Other

4. In wizard type Table Function, select it and click Next

5. Provide Table Function name and click Finish


6. Table function window will open.

7. Adjust the code to the requirements


I. [Optional] Provide input parameters including data types. This is needed when you want to parametrize Table Function.

II. [Mandatory] Set TABLE as the output type.

III. [Optional] Provide default schema for the query. This is needed when you transport the function between instances with
different schemas i.e. in development system you are using “DEV” schema, but on production all tables are placed in “PROD”
schema. If you provide the default schema in the definition of Table Function, then while transporting this schema will be
automatically replaced with the schema of target system (based on schema mapping). When applying default value for schema
mapping, in the query you should use table names without schemas i.e simply use “ORDERS” instead of “DEV“.”ORDERS“.

IV. [Mandatory] Add RETURN phrase before the final select statement.

V. [Mandatory] Add select statement.

VI. [Optional] Apply input parameters in the WHERE clause. Add leading colons (“:”) when calling each parameter.

VII. [Mandatory] Add semicolon (“;”) at the end of the statement.

VIII. [Mandatory] List all the output columns. Preserve the columns order, column names (case sensitive) and their data types
consistent with the select statement

8. After writing Table Function definition activate it and make sure that there is no error after activation.

Be aware that any of Data Definition (CREATE, ALTER, etc.) or Data Manipulation (INSERT, UPDATE etc.) operators are not
allowed in Table Functions.

How to query Table Functions?


Calling table Functions in SQL console is very easy. They are executed in the FROM clause. When executing the function,
provide whole name of the function. In brackets provide values for input parameters. If there are no input parameters – leave the
brackets empty ( they are always mandatory!!! ).

How to consume Table Function in Calculation View?


Using Table Function as a source in Calculation View is also very simple. Create a new calculation view, and when adding
object for the projection, type name of the Table Function:

If Table Function is using input parameters you need to recreate them also in the view. Go to Parameters/Variables tab, click
on Input Parameter Manage Mapping and select Data sources.

Click Auto Map By Name button to automatically copy input parameters from the Table Functions to the view.

Now when previewing data on the view, there will be pop up with input parameters. Once values are inputted they will be
passed directly to the table function and results will be displayed.
What are the limitations of Table Functions?
The main limitation of table function is that you can pass only single values for each input parameter, which can be very
annoying, because in most cases user wants to have possibility to pass multiple values in selection criteria of his report.

You might also like