Creating a View in MS SQL

In Ms Sql, VIEW s or Views are virtual tables. They can be used just like a table, but they do not have the definition or structure of a table.

It is a query that can access many tables or a part of a table.

Some of the reasons for using VIEW are to simplify the work of users using the database structure or to allow users to access data without giving them direct access to the underlying tables.

We create VIEWs as follows..

CREATE VIEW [VIEW_NAME] AS [SELECT QUERY]

We change the VIEW we created as follows.

ALTER VIEW [VIEW_NAME] AS [SELECT QUERY]

Let's look at our PRODUCTS table below..

NAME PRICE
Milk 6.0
Sugar 3.0
Apple 3.0
Water 1.5
Salt 2.0
Pencil 4.0
Oil 20.0
Cheese 15.0

For this table we will create a VIEW named VW_PRODUCTS..

CREATE VIEW VW_PRODUCTS AS SELECT NAME,PRICE, CASE WHEN PRICE > 10 THEN 'Expensive' WHEN PRICE > 5 THEN 'Normal' WHEN PRICE > 1 THEN 'Cheap' END AS PRICE_COMMENT FROM PRODUCTS

We have now created a VIEW named VW_PRODUCTS in the database. We can use it in our query just like a table.

When we run the SELECT * FROM VW_PRODUCTS
query, the result of the query in the VIEW will be returned to us.

NAME PRICE PRICE_COMMENT
Milk 6.0Normal
Sugar 3.0 Cheap
Apple 3.0 Cheap
Water 1.5 Cheap
Salt 2.0 Cheap
Pencil 4.0 Cheap
Oil 20.0 Expensive
Cheese 15.0 Expensive


You May Interest

What is the Bookmark Lookup and RID Lookup in SQL Server ?

What is the Use of Dedicated Admin Connection ?

Making a MS SQL Database Offline

Listing Metadata of MS SQL Server Internal Tables

What is a Control Flow Inside SSIS ?