Tag Archives: Sql

Difference between Stored Procedure and User Defined Function in Sql Server

Below are the some of the major differences between User Defined Function and Stored Procedure in Sql Server.

To know more on the User-Defined functions with examples please visit the article: User-Defined function.
To know more on the Stored Procedure with examples please visit the articleStored Procedure.

Sl. No. User Defined function Stored Procedure
1 Function must return a value. Stored procedure may or not return values.
2 Will allow only Select statement, it will not allow us to use DML statements. Can have select statements as well as DML statements such as insert, update, delete
etc
3 It will allow only input parameters, doesn’t support output parameters. It can have both input and output parameters.
4 It will not allow us to use try-catch blocks. For exception handling we can use try catch blocks.
5 Transactions are not allowed within functions. Can use transactions within Stored procefures.
6 We can use only table variables, it will not allow using temporary tables. Can use both table variables aswell as temporary table in it.
7 Stored procedures can’t be called from function. Stored Procedures can call functions.
8 Functions can be called from select statement. Procedures can’t be called from Select/Where/Having etc statements. Execute/Exec
statement can be used to call/execute stored procedure.
9 UDF can be used in join clause as a result set. Procedures can’t be used in Join clause

[ALSO READ] You may like to read below other popular articles on differences
Varchar Vs NVarchar
Varchar Vs Varchar(MAX)
Char Vs Varchar
Union Vs Union All
DateTime Vs DateTime2
SET QUOTED_IDENTIFIER ON Vs OFF
Primary Key Vs Unique Key
RAISERROR Vs THROW
Temporary Table Vs Table Variable
LEN() Vs DATALENGTH()
Sequence Vs Identity

Difference Between SET QUOTED_IDENTIFIER ON and OFF setting in SQL Server

In this article we will discuss on the difference between SET QUOTED_IDENTIFIER ON and SET QUOTED_IDENTIFIER OFF. Please go through the article SET QUOTED_IDENTIFIER ON/OFF Setting in Sql Server to have detailed information on this setting. As a better practice we should always use SET QUOTED_IDENTIFIERS ON setting.

SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER OFF
Characters Enclosed within double quotes is treated as Identifier is treated as Literal
Try using Characters Enclosed within double quotes as identifier Works
Example: Below statement to create a table with table name “Table” succeeds.

SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE dbo."Table"
(id int,
"Function" VARCHAR(20)) 
GO
Fails
Example: Below statement to create a table with table name “Table” Fails.

SET QUOTED_IDENTIFIER OFF
GO
CREATE TABLE dbo."Table"
(id int,
"Function" VARCHAR(20)) 
GO

Error Message:
Msg 102, Level 15, State 1,
Line 1 Incorrect syntax near ‘Table’.

Try using Characters Enclosed within double quotes as Literal. Fails
Example: Below statement fails.

SET QUOTED_IDENTIFIER ON
GO
SELECT "BIRADAR"

Error Message:
Msg 207, Level 16, State 1,
Line 1 Invalid column name ‘BIRADAR’.

Works
Example: Below Statement Works.

SET QUOTED_IDENTIFIER OFF
GO
SELECT "BIRADAR"
Characters Enclosed within single quotes is treated as Literal
Example:

SET QUOTED_IDENTIFIER ON
GO
SELECT 'BIRADAR'
is treated as Literal
Example:

SET QUOTED_IDENTIFIER OFF
GO
SELECT 'BIRADAR'
How to find all the objects which are created with SET QUTOED IDENTIFIER ON/OFF Below Statement can be used to find all the objects created with SET QUTOED_IDENTIFIER setting as ON:

SELECT OBJECT_NAME(object_id) 
FROM sys.sql_modules 
WHERE uses_quoted_identifier = 1
Below Statement can be used to find all the objects created with SET QUTOED_IDENTIFIER setting as OFF:

SELECT OBJECT_NAME(object_id) 
FROM sys.sql_modules
WHERE uses_quoted_identifier = 0
Which One to USE? Best practice is to use the SET QUOTED_IDENTIFIER ON setting. Try to avoid using SET QUOTED_IDENTIFIER OFF setting. As more and more new features require this setting value to be ON. For example while working with Filtered Indexes SET QUOTED_IDENTIFIER setting should be ON otherwise we will get into an exception as demonstrated in the article INSERT/UPDATE failed because the following SET options have incorrect settings: ‘QUOTED_IDENTIFIER’ ….

[ALSO READ] You may like to read below other popular articles on differences
Varchar Vs NVarchar
Varchar Vs Varchar(MAX)
Char Vs Varchar
Union Vs Union All
DateTime Vs DateTime2
Stored Procedure Vs User Defined Function
Primary Key Vs Unique Key
RAISERROR Vs THROW
Temporary Table Vs Table Variable
LEN() Vs DATALENGTH()
Sequence Vs Identity

Please correct me, if my understanding is wrong. Comments are always welcome.

Views in Sql Server

Views are nothing but saved SQL statements, and are sometimes referred as Virtual Tables. Keep in mind that Views cannot store data rather they only refer to data present in tables.

Benefits of Views:

A view can be useful when there are multiple users with different levels of access, who all need to see portions of the data in the database (but not necessarily all the data). Views can do the following:

  • Restrict access to specific rows in a table
  • Restrict access to specific columns in a table
  • Join columns from multiple tables and present them as though they are part of a single table
  • Present aggregate information (such as the results of the COUNT function)

Syntax: Creating a view

CREATE VIEW <View_Name>
AS
<SELECT Statement>

Let us create a Sample DataBase with Tables to understand Views Concepts:

By using the below script we are creating a Sample DataBase Named:ViewDemo. Then in this database we are creating two tables Customers and Orders  and in these tables populating the sample data.

Create DataBase SqlHintsViewDemo
GO
USE SqlHintsViewDemo
GO
Create Table dbo.Customers
( CustomerID int Identity(1,1),
  FirstName Varchar(50), LastName VarChar(50),
 Phone varchar(50), City Varchar(50) )
GO
Create Table Orders
(
OrderId int Identity(1,1),
CustomerId int
)
GO
Insert INTO dbo.Customers
Values ('Kalpana', 'Biradar', '2727272727', 'Bangalore'),
	('Basavaraj','Biradar','1616161616','Mysore')
GO
INSERT INTO Orders
Values(1), (2), (2), (2), (2)

Create Simple View:

The below script creates a view named vwSample:

CREATE VIEW dbo.vwSample
As
 SELECT CustomerID, FirstName, LastName
 FROM dbo.Customers
GO

We can use a statement like below to return all the customer records with three columns: CustomerID, FirstName, LastName.

SELECT * from dbo.vwSample

We can use the statement like below to see the content of view:

Sp_helptext vwGetCustomers

Different Uses of Views:

Views can also be used to insert, update and delete data from a table.

Example 1: Insert View Example

INSERT INTO dbo.vwSample
VALUES ('Test1','Test1')

SELECT * from dbo.vwSample
SELECT * from dbo.Customers

Example 2: Update View Example

UPDATE dbo.vwSample
SET LastName = 'B'
WHERE CustomerID = 1

SELECT * from dbo.vwSample
SELECT * from dbo.Customers

Example 3: Delete View Example

DELETE FROM dbo.vwSample 
Where CustomerID > 2

SELECT * from dbo.vwSample
SELECT * from dbo.Customers

Difference Between Views and User Defined Functions:

Views and User-Defined Functions almost serve the same purpose. But the major difference is that User-Defined Function can accept parameters, where as Views cannot. And also the output of the User Defined Function can be directly used in the SELECT clause, whereas you cannot do it with a View.

Addition of New Column’s in the Underlying Table will not automatically reflect in the existing views:

Let us prove this behaviour by creating a view vwGetCustomers  which returns all customer details with all the columns in the customer table:

 

Create View dbo.vwGetCustomers
AS
SELECT *
FROM Customers
GO
Select * FROM vwGetCustomers

Now add one more column Country to the Customers table:

ALTER Table Customers
ADD Country Varchar(30)

Execute the below statement and observe that the new column country added in the Customers table is not present in the result.

SELECT * From dbo.vwGetCustomers

The only way to reflect this new column in the view is to drop and create back the view as below:

Drop View dbo.vwGetCustomers
GO
Create View dbo.vwGetCustomers
AS
 SELECT *
 FROM dbo.Customers
GO
SELECT * From dbo.vwGetCustomers
GO

Below is an example view where it returns the data from multiple tables by joining:

Create View dbo.vwGetCustomerOrders
AS
 SELECT C.FirstName,O.OrderId
 FROM dbo.Customers C 
   INNER JOIN dbo.Orders O
    ON C.CustomerId = O.CustomerId
GO
Select * from dbo.vwGetCustomerOrders

[ALSO READ] How to check if a VIEW exists in Sql Server