Table of Contents
MS SQL Server: VIEW in SQL Server is easier to understand when the core ideas are paired with practical examples. The sections below explain the topic clearly, highlight useful steps, and point out details that can prevent common errors.
The article explains how to create, update and delete VIEW in SQL Server with syntax and examples.
What is VIEW in SQL Server?
Basically, VIEW is a virtual table that doesn't really exist in SQL Server. It is generated by a query that combines 1 or more tables.
Create VIEW in SQL Server
Syntax
CREATE VIEW[ten_schema.]ten_view AS[WITH { ENCRYPTION | SCHEMABINDING | VIEW_METADATA}SELECT bieu_thucFROM bang[WHERE dieu_kien];
ten_schema
This is the name of the schema (translating as schema or namespace) that the table belongs to.
ten_view
Name of VIEW wants to create.
ENCRYPTION
Encrypt the text of the ALTER VIEW command in sys.syscomments.
SCHEMABINDING
Make sure the table definitions are not modified to not affect VIEW.
VIEW_METADATA
Ensure SQL Server has metadata of VIEW.
bieu_thuc
Calculated columns or values want to add to VIEW.
state
Table definition VIEW. Must have at least 1 table in the FROM clause.
WHERE dieu_kien
Option. Conditions must meet so that the record is displayed in VIEW.
For instance,
CREATE VIEW sp_htk ASSELECT sanpham.id_sanpham, sanpham.ten_sanpham, hangtonkho.chatluongFROM sanphamINNER JOIN hangtonkhoON sanpham.id_sanpham = hangtonkho.id_sanphamWHERE sanpham.id_sanpham> = 1000;
The above CREATE VIEW command will create a virtual table based on the result set of the SELECT statement. This VIEW will be named sp_htk.
You can now query VIEW as below.
SELECT *FROM sp_htk;
Updated VIEW
You can edit VIEW in SQL Server without deleting the new creation using the ALTER VIEW command.
Syntax
ALTER VIEW [ten_schema.] ten_view AS[WITH {ENCRYPTION | SCHEMABINDING | VIEW_METADATA}SELECT bieu_thucFROM bangWHERE dieu_kien;
For instance,
ALTER VIEWsp_htk ASSELECT sanpham.ten_sanpham, hangtonkho.soluongFROM sanphamINNER JOIN hangtonkhoON sanpham.id_sanpham = hangtonkho.id_sanphamWHERE sanpham.id_sanpham >= 500AND sanpham.id_sanpham <= 1000;
For example, the above ALTER VIEW command will update VIEW named sp_htk without deleting. VIEW needs to exist before it can execute the update command.
Delete VIEW
FAQ
What is VIEW in SQL Server?
Basically, VIEW is a virtual table that doesn't really exist in SQL Server. It is generated by a query that combines 1 or more tables.
What should you know about updated VIEW?
You can edit VIEW in SQL Server without deleting the new creation using the ALTER VIEW command.
What is MS SQL Server: VIEW in SQL Server?
The article explains how to create, update and delete VIEW in SQL Server with syntax and examples.
Reader Comments 0
Sign in with email or Google to join the discussion.