Pages

Thursday, 27 February 2014

Difference between View and Stored Procedure

Difference between View and Stored Procedure

 View in SQL Server

A view represents a virtual table. By using view we can join multiple tables and present the data as coming from a single table.

For example consider we have two tables

      1)    UserInformation table with columns userid, username
      2)    SalaryInformation table with columns salid, userid, salary

Create VIEW by joining above two tables 
 
CREATE VIEW VW_UserInfo
AS
BEGIN
SELECT a.userid,a.username,b.salary from UserInformation a INNER JOIN SalaryInformation b ON a.userid=b.userid
END

 CREATE PROCEDURE GetUserInfo
@uid INT
AS
BEGIN
SELECT username from VW_UserInfo WHERE userid=@uid
END

Stored Procedure

 A stored procedure is a group of sql statements that has been created and stored in the database. Stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data. Stored procedure will reduce network traffic and increase the performance. If we modify stored procedure all the clients will get the updated stored procedure

 USE AdventureWorks2008R2;
GO
CREATE PROCEDURE dbo.sp_who
AS
    SELECT FirstName, LastName FROM Person.Person;
GO
EXEC sp_who;
EXEC dbo.sp_who;
GO
DROP PROCEDURE dbo.sp_who;
GO

No comments:

Post a Comment