Click here to Skip to main content
Click here to Skip to main content

Overview of Views in SQL Server 2005

By , 28 Jul 2009
 

Table of Contents

Introduction

In this article, I am going to describe about Views in SQL Server 2005. This is a simple topic. I hope this article will help you just like my ASP.NET articles. Please give me your valuable suggestions and feedback to improve my articles.

What is a View

A View is a "Virtual Table". It is not like a simple table, but is a virtual table which contains columns and data from different tables (may be one or more tables). A View does not contain any data, it is a set of queries that are applied to one or more tables that is stored within the database as an object. After creating a view from some table(s), it used as a reference of those tables and when executed, it shows only those data which are already mentioned in the query during the creation of the View.

View1.JPG

In the above diagram, we have created a View (View_Table1_Table2) from Table1 and Table2. So the View_Table1_Table2 will only show the information from those columns. Let's checkout the basic syntax for creating a View:

CREATE VIEW  [View Name]
AS
[SELECT Statement]

Use of a View

Views are used as security mechanisms in databases. Because it restricts the user from viewing certain column and rows. Views display only those data which are mentioned in the query, so it shows only data which is returned by the query that is defined at the time of creation of the View. The rest of the data is totally abstract from the end user.

Along with security, another advantage of Views is data abstraction because the end user is not aware of all the data in a table.

General syntax for Views

In this section, I will describe how to create Views, select data from Views, and deleting Views. I have created a database named ViewDemo. It has a table called EmpInfo as shown below:

EmpTable.jpg

which contains the following data:

EmpTableData.jpg

All the examples I have described are from this database.

Creating a View

Below is the general syntax for creating a View:

CREATE VIEW [View_Name]
 AS
 [SELECT Statement]

For example:

CREATE VIEW SampleView
As
SELECT EmpID, EmpName  FROM EmpInfo

which will create a View with the name SampleView that will only contain EmpID, EMPName.

Get result from a View

This is similar to a Select statement:

select * from SampleView

Now have a look at the output of SampleView:

SampleViewOutput.jpg

Drop a View

DROP VIEW SampleView

Now if we want to select data from SampleView, we will get the following error:

dropview.jpg

Different types of Views

There are two different types of Views:

  • System Views
    • Information Schema View
    • Catalog View
    • Dynamic Management View (DMV)
  • User Defined Views
    • Simple View
    • Complex View

Now we will take a look at the different types of Views in SQL Server 2005.

System Views

In SQL Server, there are a few system databases like Master, Temp, msdb, and tempdb. Each and every database has its own responsibility, like Master data is one of the template databases for all the databases which are created in SQL Server 2005. Similarly, System Views are predefined Microsoft created Views that already exist in the Master database. These are also used as template Views for all new databases. These system Views will be automatically inserted into any user created database. There are around 230 system Views available.

We can explore system Views from the SQL Server Management Studio. Expand any database > View > System View.

SystemView.jpg

In SQL Server, all system Views are divided into different schemas. These are used for the security container of the SQL Server database. We can categorize system Views in the following way:

  • Information Schema View
  • Catalog View
  • Dynamic Management View (DMV)

Now all the above categories are themselves huge topics, so I will not go into the details of them. Let us go through an overview of those View types:

Information View

These are one of the most important system grouped Views. There are twenty different schema Views in this group. These are used for displaying most physical information of a database, such as table and columns. The naming convention of this type of Views is INFORMATION_SCHEMA.[View Name]. From the system View image, we can get the names of a few Information Schema Views.

Let's see this with an example.

I have create a database named ViewDemo. It has a table called EmpInfo and the below diagram shows you the design of the table:

EmpTable.jpg

Now if we want to know detailed information on the columns of the table Empinfo using the View, we have to run the following query:

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
Where TABLE_NAME='EmpInfo'

The following will be the output:

EmpTableViewInfo.jpg

Similarly we can use other schema Views to read database information.

Catalog View

This type of Views were introduced in SQL Server 2005. Catalog Views are categorized in to different groups also. These are used to show database self describing information.

For example:

select * from sys.tables

and following is a sample output:

Catalogview.jpg

Dynamic Management View

This is newly introduced in SQL Server 2005. These Views give the database administrator information about the current state of the SQL Server machine. These values help the administrator to diagnose problems and tune the server for optimal performance. In SQL Server 2005, there are two types of DMVs:

  1. Server-scoped DMV: Stored in the Master database.
  2. Database-scoped DMV: Specific to each database.

For example, if we want to check all SQL Server connections, we can use the following query:

SELECT
connection_id,
session_id,client_net_address,
auth_scheme
FROM sys.dm_exec_connections

And the following is the sample output:

DMV.jpg

If you want to know the details on DMV, here is a complete article on CodeProject: Dynamic Management Views [DMV] - A SQL Server 2005 Feature [^].

Note: There are many things to learn on system Views, I have just introduced them for beginners. If anyone has more interest, look into this article: System Views in SQL Server 2005 [^].

User Defined View

Up till now I described about system Views, now we will take a look at user defined Views. These Views are created by a user as per requirements. There is no classification for UDVs and how to create them, I have already explained the syntax. Now we can take a look at another View creation.

CREATE VIEW DemoView
AS
SELECT EmpID, EmpName, Phone
FROM EmpInfFROM EmpInfo

When to Use a View

There are a number of scenarios where we will like to create our own View:

  1. To hide the complexity of the underlying database schema, or customize the data and schema for a set of users.
  2. To control access to rows and columns of data.

View Creation Option

There are two different options for creating a View:

  • Schema Binding Option
  • Encryption

Schema BindSchema Binding Option

If we create a View with the SCHEMABINDING option, it will lock the tables being referred to by the View and restrict all kinds of changes that may change the table schema (no Alter command). While creating a schema binding View, we can't mention "Select * from tablename" with the query. We have to mention all column names for reference.

For example:

CREATE VIEW DemoSampleView
With SCHEMABINDING
As
SELECT
          EmpID,
          EmpName,
FROM DBO.EmpInfo

And one more thing that we need to remember, while specifying the database name, we have to use Dbo.[DbName]. After creating the View, try to alter the table EmpInfo, we won't be able to do it! This is the power of the SCHEMABINDING option.

If we want to change/alter the definition of a table which is referred by a schema bound View, we will get the following error message:

SchemaBinding.jpg

Encryption

This option encrypts the definition. This option encrypts the definition of the View. Users will not be able to see the definition of the View after it is created. This is the main advantage of the View where we can make it secure:

CREATE VIEW DemoView
With ENCRYPTION.EmpInfo

Note: Once the View is encrypted, there is no way to decrypt it again.

Use SSMS for Creating a View

SQL Server Management Studio provides a handy GUI for creating and managing Views. In the Object Explorer tab, it lists all the Views corresponding to a database. In this section, we will just quickly check how SSMS is used to create and maintain a View.

First expand ViewDemoDB > Move to View. Right click on the View folder.

NewViewSSMS.jpg

When we will click on New View, the following screen will appear. In ViewDemoDB, we have two datatables. Now I am going to create a View from the EmpInfo table.

AddTableSSMS.jpg

Select EmpInfo, click on Add. You will be redirected to the Create View screen where you can configure the View creation. Check the following image:

NewViewCreate.jpg

The above image shows three sections where we can select the table name or in the below section, we can write the query for the View. When done, just click on the Save button on the toolbar. Give the name of the View and click on OK.

ViewNameSSMS.jpg

Now go to ViewDemoDB > View > Expand View folder. Here, along with system Views, you can see the View that we created right now.

NewCreatedView.jpg

So this is our user defined View. If we right click on it, we will get the option of opening the View and which will show the result of the View.

PropertiesView.jpg

We can also create a View from a View itself in a similar way that we have done with a table.

Summary

View is a "Virtual Table" which is stored as an object in a database. This can be used as a security container of the database. We can encrypt a View definition for making it secure. There are more than 230 system Views available which have their own responsibilities. We can create a View by either writing a T-SQL statement or by using SQL Server Management Studio.

Hope I have explained it well. Please give your feedback and suggestions to improve my article.

Topic to be covered on next article

  • Parameterized View
  • Indexing a View
  • View FAQ's

Reference and future study

Points of interest

I have published only a few articles on SQL Server, and this was written after a long time. I have learned a lot while studying and exploring Views.

History

  • 27 July 2009: Initial post.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Abhijit Jana
Software Developer (Senior)
India India
Member
.NET Consultant | Former Microsoft MVP - ASP.NET | CodeProject MVP, Mentor, Insiders| Technology Evangelist | Author | Speaker | Geek | Blogger | Husband
 
Blog : http://abhijitjana.net
Web Site : http://dailydotnettips.com
Twitter : @AbhijitJana
My Kinect Book : Kinect for Windows SDK Programming Guide

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberamitavin_Sharma27 Feb '13 - 1:37 
nice article sir it reduce my time a lot
GeneralMy vote of 5membergdwn3 Jan '13 - 19:15 
Excellent explanationThumbs Up | :thumbsup:
GeneralMy vote of 4memberaankitpal28 Nov '12 - 22:58 
explanation is good
QuestionWhere Views are used in sql server --memberVelkumar Kannan22 Oct '12 - 19:20 
Hi,

I want to about the real use of views in sql server. In which situation i can prefer views for my project also In which situation views are used?. Can you explain this with one real time example.

Most of them are said views are used to restrict some users to see the contents of real tables.

But I have a doubt... When we creating a web application the database user of this application may be a single user. Then how this views are used in web applications.

 
The database user of web application should be a administrator then we will restrict which user to prevent to see the original tables.

 

Thanks,
Velkumar.
GeneralMy vote of 5memberArpan Guin22 Oct '12 - 3:04 
Excellent explanation
GeneralMy vote of 3membersaerluvla Arul9 Oct '12 - 22:55 
ok
Questionview in sql servermemberjgrumy14 Sep '12 - 2:14 
Your way of explain is so much fine. I thanks to you and hope you will answer more question similarly.
GeneralMy vote of 5memberpradiprenushe1 Aug '12 - 23:44 
best article for fresher to experience
GeneralMy vote of 5membersaikumar172327 Jul '12 - 10:47 
it cover basics good
GeneralMy vote of 5memberAkiii0011 Jun '12 - 19:47 
good article !
GeneralMy vote of 4memberMember 79955425 Mar '12 - 1:05 
Nice Articles
for begginers
GeneralMy vote of 5memberaytharavi24 Nov '11 - 0:22 
easy to understand for beginners
GeneralMy vote of 5memberchirag.makwana198928 Mar '11 - 21:32 
Thats really good for the understanding. Thank You Abhijit.
GeneralMy vote of 5memberSChristmas3 Mar '11 - 3:32 
Good article. If you provide more example/useful commands in Information and catalog views it will be helpful.
 
Ex.
select table_name,column_name from information_schema.columns
where column_name like '%tax%'

GeneralMy vote of 5memberVishnuSharmila5 Jan '11 - 0:52 
Very Nice Article
GeneralMy vote of 5memberrinatyagi19 Sep '10 - 18:25 
great artical...very nice
GeneralMy vote of 5memberarun potti2 Sep '10 - 23:50 
Great Article
GeneralMy vote of 5memberdl4gbe24 Jul '10 - 22:47 
nice introduction
GeneralNice Articemember9TailFox20 Mar '10 - 21:40 
hey thanks that was a very good article looking forward for u forthcoming article on views
GeneralGood Articlemembermukeshbela27 Nov '09 - 20:09 
This article helped me a lot in knowing a basic information about view's. Can u plz post some code snippet, how to use views in C#.Net code.
 
Thanks
Mukesh
Generalnice ideagroupMd. Marufuzzaman29 Jul '09 - 9:11 
It's nice specially for the beginners, I just love the way of your presentation, i always found that your content is very rich..Smile | :)
 

 
Thanks
Md. Marufuzzaman
GeneralRe: nice ideamvpAbhijit Jana29 Jul '09 - 9:30 
Thanks mate. Thanks for Voting Thumbs Up | :thumbsup: Smile | :)
 
I will published the next version shortly Big Grin | :-D
 
Abhijit Jana | Codeproject MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.
View My Latest Article

GeneralRe: nice ideagroupMd. Marufuzzaman29 Jul '09 - 11:13 
That's cool,, waiting for the next one...Thumbs Up | :thumbsup:
 

 
Thanks
Md. Marufuzzaman
GeneralConceptual Articlemembervivek_viv28 Jul '09 - 19:33 
Good Job again Smile | :) ,
Nice article. Covered most of the part. Waiting for the next parameterized view article. Hope we can find it shortly. Laugh | :laugh:
 
Regards,
Vivek
 
Vivek
GeneralRe: Conceptual ArticlemvpAbhijit Jana28 Jul '09 - 19:40 
Thanks Mate Thumbs Up | :thumbsup:
Regarding next part. I will published very soon Smile | :)
 
Abhijit Jana | Codeproject MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.
View My Latest Article

NewsSmall Mistake [ Encryption of View ]mvpAbhijit Jana28 Jul '09 - 11:08 
There is a Small Mistake in Encryption of View Syntax.
Tt should like
 
CREATE VIEW DemoSampleView
With ENCRYPTION
As
SELECT
          EmpID,
          EmpName,
FROM DBO.EmpInfo
 
I will update the article soon.
 
Sorry for the Inconvenience D'Oh! | :doh:
 
Thanks Smile | :)
 
Abhijit Jana | Codeproject MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.
View My Latest Article

GeneralRe: Small Mistake [ Encryption of View ]memberAbhishek Sur28 Jul '09 - 21:40 
Yes.
 
I always use With Encryption for Stored Procedures in Production databases, to hide business logic.
 
Great to see View also supports that ..
 
Thumbs Up | :thumbsup: Thumbs Up | :thumbsup:
 

GeneralRe: Small Mistake [ Encryption of View ]groupMd. Marufuzzaman29 Jul '09 - 11:17 
Well that's good , be careful to make sp / view as encrypted when you are using SQL server 2000 / later..
 
Don't forget to click "Good Answer" on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

GeneralRe: Small Mistake [ Encryption of View ]mvpAbhijit Jana29 Jul '09 - 11:37 
Md. Marufuzzaman wrote:
be careful to make sp / view as encrypted when you are using SQL server 2000 / later..

Do you have any more input on this ?
 
Abhijit Jana | Codeproject MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.
View My Latest Article

GeneralRe: Small Mistake [ Encryption of View ]groupMd. Marufuzzaman29 Jul '09 - 12:15 
Don't Encrypt Unless Absolutely Necessary
 
When you distribute SQL Server-based applications to customers and other third parties, you may be tempted to encrypt the source to your stored procedures, functions, and similar objects. Obviously this protects your code from prying eyes and keeps people from making changes to your code without your knowledge.
 
That said, unless you have real concerns about confidential or proprietary information being stolen, I recommend against encrypting your SQL Server objects. To me, encrypting SQL Server objects is usually more trouble than it's worth. There are a number of disadvantages to encrypting the source code to SQL Server objects. Let's discuss a few of them.
 
One, encrypted objects cannot be scripted, even by Enterprise Manager. That is, once a procedure or function is encrypted, you cannot retrieve its source from SQL Server. The well-known but undocumented methods of decoding encrypted source in earlier versions of SQL Server no longer work, and other methods one might discover are not supported by Microsoft. To make matters worse, if you attempt to script an encrypted object via Enterprise Manager using the default options, your new script will have a DROP statement for the object, but not a CREATE. Instead, all you'll see is a helpful comment informing you that scripting encrypted objects isn't supported (whereas, obviously, dropping them is). If you run this script, your object will be lost. It will be dropped, but not recreated.
 
Two, encrypted objects cannot be published as part of a SQL Server replication. If your customers set up replication operations to keep multiple servers in synch, they'll run into problems if you encrypt your code.
 
Three, you can't check encrypted source code for version info (such as that inserted by a source code management system). Because customers can load backups that may reinstall an older version of your code over a newer one, it's extremely handy to be able to check the code for version info on the customer's server. If your code is encrypted, you can't easily do this. If it's not, and if you've included version information in the source code, you should be able to easily determine the exact version of an object the customer is using.
 
Listing 4-2 shows a procedure that you can use to list the version information in your SQL Server objects. Basically, it scans a database's syscomments table for the keyword tags supported by VSS and produces a columnar report of the objects with these embedded keywords. Running this procedure can give you a quick bird's-eye view of the version info for all the Transact-SQL source code in a database.
 
Don't forget to click "Good Answer" on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

GeneralRe: Small Mistake [ Encryption of View ]groupMd. Marufuzzaman29 Jul '09 - 12:21 
Try the following for more detail...
http://www.developmentnow.com/g/113_2005_8_0_0_578918/Advantages-and-disadvantages-of-stored-proc-encryption.htm
 

 
Thanks
Md. Marufuzzaman
GeneralRe: Small Mistake [ Encryption of View ]mvpN a v a n e e t h30 Jul '09 - 6:22 
Abhishek Sur wrote:
I always use With Encryption for Stored Procedures in Production databases, to hide business logic.

 
Hide business logic? Do your stored procedures have business logic?
 

GeneralRe: Small Mistake [ Encryption of View ]memberAbhishek Sur30 Jul '09 - 21:28 
Yes, of course..
all the database related business logic is embedded in stored procedures, so that whenever a minor changes occur, we could just run the stored proc and the other tiers remain intact(at least we dont have to compile a dll).
 
In my recent project I am creating a dynamic database structure, where the admin can customize business logic, even the database structure. They can define workflows of the entire system for their users .. from the UI.
 
If I give you such database, you cant even understand what is the actual structure of the database!! Its the Stored proc that can stores data and also retrieve data from that database. Our DBA did those stored procedure who actually know where the data actually is. So it is very essential to encrypt those stored proc. Actually I heard Encrypting database stored proc doesnt hampers performance, so I use it often.
 
Any suggestion?
 
Thumbs Up | :thumbsup: Thumbs Up | :thumbsup:
 

GeneralRe: Small Mistake [ Encryption of View ]mvpN a v a n e e t h31 Jul '09 - 7:39 
Abhishek Sur wrote:
business logic is embedded in stored procedures, so that whenever a minor changes occur, we could just run the stored proc and the other tiers remain intact(at least we dont have to compile a dll).

 
I am not a proponent of stored procedures. I strongly believe that embedding business logic into stored procedures is a sign of bad design. You may need to recompile the application when data type changes or some extra column needs to be returned. I agree that small fixes are easy to do in SP, but IMO, the number of times you can fix something big just changing the SP is very less.
 
Few cons of keeping business logic in SP which I felt are
 
1 - Code will be tough to maintain.
2 - Poor refactoring support
3 - Unable to write automated tests for the business logic.
4 - Can't step into the code and debug it.
 
Using any good ORM tool for data access combined with your business entity classes will provide more maintainable and clean code than stored procedures.
 
I am not saying to stop using stored procedures. There may be exceptional cases where a SP makes more sense and can have business logic. It is just another tool in the box and use it wisely.
 
I don't know the problem domain you are working on and all the above said are my views about this and I may be totally wrong. I would like to hear if you have any other good reasons to keep the BL in SP.
 
Smile | :)
 

GeneralRe: Small Mistake [ Encryption of View ]mvpAbhijit Jana31 Jul '09 - 9:24 
FYI :
Business Logic In Stored Procedures
and
The Worst Possible Way to use a Stored Procedure
 
Abhijit Jana | Codeproject MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.
View My Latest Article

GeneralCoolmemberAbhishek Sur28 Jul '09 - 10:35 
Very interesting.
I never about using VIEW ever.
 
Well nice to see such a nice article here.
 
Abhijit, you are doing great. Rose | [Rose] Rose | [Rose]
 
Keep it up.Thumbs Up | :thumbsup:
 

GeneralRe: CoolmvpAbhijit Jana28 Jul '09 - 10:43 
Thanks Abhishek.
 
I will try to published the next one on Parameterized view and Indexing View Very soon Wink | ;)
 
Hope that will be more interesting Thumbs Up | :thumbsup:
 
Thanks Big Grin | :-D
 
Abhijit Jana | Codeproject MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.
View My Latest Article

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 28 Jul 2009
Article Copyright 2009 by Abhijit Jana
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid