Professional Documents
Culture Documents
Stored Procedure & TF
Stored Procedure & TF
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. )
1. insert product values(1,'Printer',10,4500)
2. insert product values(2,'Scanner',15,3500)
3. insert product values(3,'Mouse',45,500)
1. select * from product
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.
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.
3 GO
4
8
12 GO
13
14 INSERT INTO ProductDescription VALUES (680,'Replacement mountain wheel for entry-level rider.')
17 GO
2 AS
3 BEGIN
4 SET NOCOUNT ON
5
6 SELECT P.ProductID,P.ProductName,PD.ProductDescription FROM
7 Product P
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.
2 (@PID INT)
3 AS
4 BEGIN
5 SET NOCOUNT ON
6
7 SELECT P.ProductID,P.ProductName,PD.ProductDescription FROM
8 Product P
10 WHERE P.ProductID=@PID
11
12 END
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.
3 AS
4 BEGIN
5 SET NOCOUNT ON
6
7 SELECT P.ProductID,P.ProductName,PD.ProductDescription FROM
8 Product P
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.
2 (@Ename varchar(50),
4 AS
5 BEGIN
6 SET NOCOUNT ON
7
9
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.
2
4
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.
2 WITH ENCRYPTION
3 AS
4 BEGIN
5 SET NOCOUNT ON
6
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.
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.
2 AS
3 BEGIN
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.
2 AS
3 BEGIN
5 END
2 AS
3 BEGIN
4 SET NOCOUNT ON
5
6 SELECT P.ProductID,P.ProductName,PD.ProductDescription FROM
7 Product P
9
10 END
1 sp_rename 'GetProductDesc','GetProductDesc_new'
Conclusion
Table Functions in SAP HANA – step by step guide
3546117,312
This inspired me to write the article about Table Functions and share my experience on that topic.
Table functions are used whenever the graphical views are not sufficient i.e. for loops, executing custom functions or complex
queries.
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.
2. Go to Repositories tab:
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“.
VI. [Optional] Apply input parameters in the WHERE clause. Add leading colons (“:”) when calling each parameter.
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.
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.