Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Store Procedure KT

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

SQL Variables: Basics and usage

In SQL Server, local variables are used to store data during the batch execution period. The local
variables can be created for different data types and can also be assigned values. Additionally,
variable assigned values can be changed during the execution period. The life cycle of the
variable starts from the point where it is declared and has to end at the end of the batch. On the
other hand, If a variable is being used in a stored procedure, the scope of the variable is limited
to the current stored procedure.
USE OF SP:

Stored procedures are used for various different things. Some of the uses of stored procedures are
as follows:

 Stored procedures are often used as access control mechanism and for data validation.
 The logic applied in this application is centralized and is stored in the application.
 Procedures are used to process the huge amount of data for complex procedures and
functionalities and for logic implementation access of their data.
 These procedures are used to store data in them and can be accessed by procedures.
 They support modular programming.
 Faster execution takes place.
 It can also be used as a security mechanism.
 They are used for reducing network traffic.
Repetitive tasks are being performed by the recursive stored procedures. By default this function
is disabled but can be activated using a particular command. The command is as follows-

Max_sp_recursion_depth;
After using this, the system variable should be renamed to a non-zero variable.

The differences between stored procedure and view in SQL server are as follows:

 A stored procedure accepts parameters. Whereas, views do not accept parameters.


 In any large query, a stored procedure cannot be used as a building block. Whereas, a
view can be used as a building block.
 A stored procedure can contain several statements. Whereas, a view can contain only one
single select query.
 Using stored procedures, one or more tables can be modified. Whereas, using view no
table can be modified.
 A view can be used within a stored procedure. Whereas, a stored procedure cannot be
used inside a view.

Following are some differences between stored procedures and triggers:


 Event and actions needs to be identified at the time of creating a trigger. Whereas, at the
time of creating a stored procedure, it is not important.
 Trigger can be run automatically when any event occurs. Whereas, stored procedures
have to be run manually.
 A stored procedure can be called within a trigger. Whereas, a trigger cannot be called in a
stored procedure.
 Triggers execute implicitly. Whereas, stored procedures execute explicitly.
 A trigger cannot be called from front end. Whereas, a stored procedure can be.

Why we need the stored procedure?

This is one of the most frequently asked SQL Server Stored Procedure Interview Questions in
the SQL Server Interview. So let’s discuss this question in details
Whenever we want to execute a SQL query from an application the SQL query (statement) what
we send from an application will be first compiled(parsed) for execution, where the process of
compiling(parsing) is time-consuming because compilation occurs each time when we execute
the query or statements.
To overcome the above problem, we write SQL statements or query under the stored procedure
and execute because a stored procedure is a pre-compiled block of code, without
compiling(parsing) the statements get executed whenever the procedures are called which can
increase the performance of database server which ultimately increases the performance of the
application.
If we have a situation where we write the same query again and again, we can save that specific
query as a stored procedure and call it’s just by its name whenever required that query to
execute.
The Parameters of a stored procedure can be of two types

1. Input parameters

2. Output parameters

The Input parameters are basically used for bringing value into the procedure for execution
whereas the output parameters are used for carrying a value out of the procedure after execution.
If a parameter is declared as output, we only require assigning a value to the parameter inside the
procedure so that the procedure will send that value at the end of procedure execution.

Have you ever created or used recursive stored procedure? Give example?
Ans: I created a recursive stored procedure for calculating the factorial of a number.
CREATE PROCEDURE [dbo].[Factorial_ap]
( @Number Integer,@RetVal Integer OUTPUT )

AS
    DECLARE @In Integer
    DECLARE @Out Integer
    IF @Number != 1
        BEGIN
        SELECT @In = @Number – 1
        EXEC Factorial_ap @In, @Out OUTPUT
        SELECT @RetVal = @Number * @Out
    END
        ELSE
            BEGIN
                SELECT @RetVal = 1
            END
RETURN
GO
How to Optimize Stored Procedure Optimization? 

Ans: There are many tips and tricks for the same. Here are few:

 Include SET NOCOUNT ON statement.


 Use schema name with object name.
 Do not use the prefix "sp_" in the stored procedure name.
 Use IF EXISTS (SELECT 1) instead of (SELECT *).
 Use the sp_executesql stored procedure instead of the EXECUTE statement.
 Try to avoid using SQL Server cursors whenever possible.
 Keep the Transaction as short as possible.
 Use TRY-Catch for error handling.

How you will execute the stored procedure as a different user?

Ans: I will use

EXECUTE AS

Example-
EXECUTE AS user = 'special_user'
EXECUTE YourProcerdure

Can we create Stored Procedure without "Begin" and "End" refer the below image and
try to answers?

Ans: Yes, We can


Can we return NULL value using stored proc?

Ans: No, Stored procedures are not allowed to return the NULL value.
If you will try to return null value the you will get message as shown in the above screenshot.

Get only Year part of "JoiningDate".

Ans: SELECT DATEPART(YEAR, JoiningDate) FROM [EmployeeDetail]

Get the first name, current date, joiningdate and diff between current date and joining
date in months.

Ans: SELECT FirstName, GETDATE() [Current Date], JoiningDate,
DATEDIFF(MM,JoiningDate,GETDATE()) AS [Total Months] FROM [EmployeeDetail]
 Display first name and Gender as M/F.(if male then M, if Female then F)

Ans: SELECT FirstName, CASE  WHEN Gender = 'Male' THEN 'M'
WHEN Gender = 'Female' THEN 'F' END AS [Gender]
FROM [EmployeeDetail]

Select first name from "EmployeeDetail" table prifixed with "Hello "

Ans: SELECT 'Hello ' + FirstName FROM [EmployeeDetail]

Select second highest salary from "EmployeeDetail" table.

Ans: SELECT TOP 1 Salary FROM
(SELECT TOP 2 Salary FROM [EmployeeDetail] ORDER BY Salary DESC) T ORDER BY Sa
lary ASC

Write down the query to fetch Project name assign to more than one Employee

Ans: Select ProjectName,Count(*) [NoofEmp] from [ProjectDetail] GROUP BY ProjectName H
AVING COUNT(*)>1
1. Local Temporary Tables
2. Global Temporary Tables

2). What is the difference between Local and Global Temporary Tables?

Local Temporary Tables:

Prefixed with a single pound sign (#).


Local temporary tables are visible to that session of SQL Server which has created it/Exists only
for duration of the connection/compound statement.
Local temporary tables are automatically dropped when the session that created the temporary
tables is closed.

Global Temporary Tables:

Prefixed with two-pound signs (##).


Global temporary tables are visible to any user and any connection after being created.
Global temporary tables are also automatically dropped, when the session that created the
temporary tables is closed.
4). In which database, the temporary tables get created?
TEMPDB database.

5). How can I check for the existence of a temporary table?


IF object_id('tempdb..##TEMPTABLE') IS NOT NULL

6). Table Variables vs. Temp Tables?


Table var doesn't have to be memory-resident. Its pages can be moved to tempdb if memory is
low
Rollback doesn't affect table vars
Table vars don't participate in transactions or locking
Any DML operations done on table variables are not logged
No statistics are maintained on table variables

7). Can you create foreign key constraints on temporary tables?


No

8). Do you have to manually delete temporary tables?


No, temporary tables are automatically dropped, when the session that created the temporary
tables is closed. But if you maintain a persistent connection or if connection pooling is enabled,
then it is better to explicitly drop the temporary tables you have created.
However, It is generally considered a good coding practice to explicitly drop every temporary
table you create.

You might also like