Top Banner
Prentice Hall © 2004 1 Chapter 8: Views and Chapter 8: Views and Synonyms Synonyms SQL for SQL Server SQL for SQL Server Bijoy Bordoloi and Douglas Bock Bijoy Bordoloi and Douglas Bock
33

Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Dec 30, 2015

Download

Documents

Judith Williams
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 1

Chapter 8: Views and SynonymsChapter 8: Views and Synonyms

SQL for SQL ServerSQL for SQL ServerBijoy Bordoloi and Douglas BockBijoy Bordoloi and Douglas Bock

Page 2: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 2

ObjectivesObjectives• Create a single table view.• Create a join table view—include functions.• Insert, update, and delete table rows using a view.• Create a view with errors.• Drop a view.• Create a table with column specifications that

include the identity property.• Insert data rows into tables with a column

specified with the identity property.• Use SCOPE_IDENTITY function to insert data

rows into tables related to a table that has a column specified with the identity property.

Page 3: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 3

VIEWSVIEWS• A database view is a A database view is a logical logical oror virtual table virtual table based on based on

a query. It is useful to think of a a query. It is useful to think of a viewview as a stored as a stored query that can contain columns from one or more query that can contain columns from one or more tables.tables.

Page 4: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 4

VIEWS Cont.VIEWS Cont.

• Views are created through use of a Views are created through use of a CREATE VIEW command that CREATE VIEW command that incorporates use of the SELECT statement. incorporates use of the SELECT statement.

• Views are queried just like tables—to a Views are queried just like tables—to a system user, they appear to be tables. system user, they appear to be tables.

• View definitions and execution plans are View definitions and execution plans are stored in the SQL Server database – the data stored in the SQL Server database – the data for a view is gathered each time a view is for a view is gathered each time a view is queried.queried.

Page 5: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 5

VIEWS Cont.VIEWS Cont.

• Why use views?Why use views?– Views are simple to use.Views are simple to use.– Views enable a system designer to custom Views enable a system designer to custom

model data in a database – a user’s “view.”model data in a database – a user’s “view.”– They provide a form of security by limiting They provide a form of security by limiting

access to columns certain employees need to access to columns certain employees need to access while other data, such as employee access while other data, such as employee salary figures are hidden.salary figures are hidden.

– Views can also be used to update one or more Views can also be used to update one or more tables.tables.

Page 6: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 6

An Example CREATE VIEW CommandAn Example CREATE VIEW Command

• The columns are renamed from the table The columns are renamed from the table column names to match the way that system column names to match the way that system users think about the data. users think about the data.

/* SQL Example 8.1 */

CREATE VIEW employee_parking

(parking_space, last_name,

first_name, ssn) AS

SELECT emp_parking_space, emp_last_name,

emp_first_name, emp_ssn

FROM employee

Page 7: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 7

Selecting from a ViewSelecting from a View

• Notice that the only columns in the query are those Notice that the only columns in the query are those defined as part of the view. Also, a view can be sorted defined as part of the view. Also, a view can be sorted with the ORDER BY clause just like a table.with the ORDER BY clause just like a table.

/* SQL Example 8.2 */ SELECT * FROM employee_parking ORDER BY last_name, first_name;

parking_space last_name first_name ssn ––––-–––––––––– –––––––-––– -––––––––-––– –––––––-– 422 Amin Hyder 999222222 542 Bock Douglas 999111111 1 Bordoloi Bijoy 999666666 more rows will be displayed . . .

  

Page 8: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 8

CREATE VIEW SyntaxCREATE VIEW Syntax

• The general syntax has several options as The general syntax has several options as shown here.shown here.

CREATE VIEW [ <database_name>.]

[< owner>.] view_name

[(column_name1 [,column_name2 ...

column_name_n ] ) ]

[WITH <view_attribute1>

[, view_attribute2,…view_attribute_n] ]

AS

SELECT

[ WITH CHECK OPTION ]

Page 9: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 9

View Syntax RulesView Syntax Rules

• The database name and owner name specification The database name and owner name specification is optional.is optional.

• View names must comply with SQL Server View names must comply with SQL Server naming rules.naming rules.

• Columns included in a view can be optionally Columns included in a view can be optionally renamed. Renaming is required if:renamed. Renaming is required if:– a column is derived by an arithmetic expression, a column is derived by an arithmetic expression,

function, or constant.function, or constant.

– a JOIN causes the selection of two column from a JOIN causes the selection of two column from different tables with the same name—rename one of different tables with the same name—rename one of the columns.the columns.

Page 10: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 10

View Syntax Rules Contd.View Syntax Rules Contd.• The AS keyword is required.The AS keyword is required.• The SELECT statement defines the columns in a The SELECT statement defines the columns in a

view.view.• The SELECT can select from one or more tables The SELECT can select from one or more tables

including a JOIN operation or select columns from including a JOIN operation or select columns from other views.other views.

• The SELECT cannot include:The SELECT cannot include:– COMPUTE or COMPUTE BY clauses.COMPUTE or COMPUTE BY clauses.– ORDER BY clauses unless TOP is used.ORDER BY clauses unless TOP is used.– The INTO keyword.The INTO keyword.– A temporary table or table variable.A temporary table or table variable.– More than 1,024 columns.More than 1,024 columns.

Page 11: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 11

Example CREATE VIEW with Columns RenamedExample CREATE VIEW with Columns Renamed

/* SQL Example 8.3 */CREATE VIEW empview7 (SSN, FirstName, LastName, Dept) ASSELECT emp_ssn, emp_first_name, emp_last_name, emp_dpt_numberFROM employeeWHERE emp_dpt_number=7WITH CHECK OPTION

Page 12: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 12

Selecting from Empview7Selecting from Empview7• The column names from the view are probably more The column names from the view are probably more

meaningful to system users than the original meaningful to system users than the original employeeemployee table column names.table column names.

/* SQL Example 8.4 */

SELECT *

FROM empview7;

SSN FirstName LastName Dept

––––––––– –––––––––--––––– ––––--––––––––– –––––

999111111 Douglas Bock 7

999333333 Dinesh Joshi 7

999444444 Waiman Zhu 7

999888888 Sherri Prescott 7

Page 13: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 13

A View with the Same Structure as a TableA View with the Same Structure as a Table

• The column names are more meaningful.The column names are more meaningful.• The manager’s SSN is already formatted.The manager’s SSN is already formatted.

/* SQL Example 8.5 */

CREATE VIEW dept_view (DepartmentNo,

Name, ManagerSSN, StartDate) AS

SELECT dpt_no, dpt_name,

LEFT(dpt_mgrssn,3)+'-'

+SUBSTRING(dpt_mgrssn,4,2)+'-'+

RIGHT(dpt_mgrssn,4),

CAST(dpt_mgr_start_date As CHAR(11))

FROM department

Page 14: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 14

Selecting from the Dept_ViewSelecting from the Dept_View

/* SQL Example 8.6 */

SELECT *

FROM dept_view;

DepartmentNo Name ManagerSSN StartDate

–––––––––––— –––—–––––––—–––––– ––––––––––– –––––––––––

1 Headquarters 999-66-6666 Jun 19 1981

3 Admin and Records 999-55-5555 Jan 1 2001

7 Production 999-44-4444 May 22 1998

Page 15: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 15

FUNCTIONS AND VIEWS:FUNCTIONS AND VIEWS:JOIN VIEWSJOIN VIEWS

• Views can contain simple row functions Views can contain simple row functions and also JOIN tables.and also JOIN tables.

/* SQL Example 8.8 */

CREATE VIEW dept_salary

(Name, MinSalary, MaxSalary, AvgSalary) AS

SELECT d.dpt_name, MIN(e.emp_salary),

MAX(e.emp_salary), AVG(e.emp_salary)

FROM employee e JOIN department d ON

(e.emp_dpt_number=d.dpt_no)

GROUP BY d.dpt_name

Page 16: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 16

Selecting from the Dept_Salary ViewSelecting from the Dept_Salary View /* SQL Example 8.9 */ SELECT * FROM dept_salary;

Name MinSalary MaxSalary AvgSalary ––––––––––––––––— ––––——––-–– ––––––-–––– ––––––-––– Admin and Records 25000.0000 43000.0000 31000.0000 Headquarters 55000.0000 55000.0000 55000.0000 Production 25000.0000 43000.0000 34000.0000

Page 17: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 17

DROPPING VIEWSDROPPING VIEWS

• A Database Administrator or View Owner A Database Administrator or View Owner can drop a view with the DROP VIEW can drop a view with the DROP VIEW statement.statement.

/* SQL Example 8.10 */

DROP VIEW dept_view;

Page 18: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 18

View StabilityView Stability

• Views do not store data – only the view definition Views do not store data – only the view definition is stored, and view data is only temporary.is stored, and view data is only temporary.

• When a table underlying a view is dropped, the When a table underlying a view is dropped, the view becomes invalid.view becomes invalid.

• The server message for a SELECT from an invalid The server message for a SELECT from an invalid view is: view is: Msg 208, Procedure <view Msg 208, Procedure <view name>, Line #, Invalid Object name>, Line #, Invalid Object <table name>.<table name>.

• If the table is recreated, the view will again work If the table is recreated, the view will again work satisfactorily.satisfactorily.

Page 19: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 19

INSERTING, UPDATING, and INSERTING, UPDATING, and DELETING ROWS THROUGH VIEWSDELETING ROWS THROUGH VIEWS

• Inserting and updating table rows through views is Inserting and updating table rows through views is complex; deleting rows is simpler.complex; deleting rows is simpler.

• To execute DML on a view, the view must be To execute DML on a view, the view must be updateable:updateable:– No aggregate functions are specified in the SELECT No aggregate functions are specified in the SELECT

list.list.– Cannot use the TOP, GROUP BY, DISTINCT, or Cannot use the TOP, GROUP BY, DISTINCT, or

UNION clauses.UNION clauses.– No derived columns in the SELECT list.No derived columns in the SELECT list.– Views created with a JOIN can only modify or insert Views created with a JOIN can only modify or insert

rows in one table at a time.rows in one table at a time.

Page 20: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 20

Inserting RowsInserting Rows• The INSERT statement cannot violate any constraints on The INSERT statement cannot violate any constraints on

underlying tables.underlying tables.

• Here, the Here, the departmentdepartment table has four columns and the view only table has four columns and the view only has two columns, but the other two table columns can be has two columns, but the other two table columns can be

NULL.NULL. /* SQL Example 8.21 */

CREATE VIEW dept_view2 AS

SELECT dpt_no, dpt_name

FROM department

/* SQL Example 8.22 */

INSERT INTO dept_view2 VALUES (18, 'Department 18');

INSERT INTO dept_view2 VALUES (19, 'Department 20');

Page 21: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 21

Updating RowsUpdating Rows• The UPDATE statement updates existing rows through The UPDATE statement updates existing rows through

a view. Here, a department name is changed from a view. Here, a department name is changed from Department 20 to Department 19.Department 20 to Department 19.

/* SQL Example 8.24 */ UPDATE dept_view2 SET dpt_name = 'Department 19' WHERE dpt_no = 19; (1 row(s) affected)

/* SQL Example 8.25 */ SELECT * FROM department;

dpt_no dpt_name dpt_mgrssn dpt_mgr_start_date ––-––– ––––—–––––-–––––– –-–––––––– ––––––––––––––––––––––– 1 Headquarters 999666666 1981-06-19 00:00:00.000 3 Admin and Records 999555555 2001-01-01 00:00:00.000 7 Production 999444444 1998-05-22 00:00:00.000 18 Department 18 NULL NULL 19 Department 19 NULL NULL

Page 22: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 22

Deleting RowsDeleting Rows

• This example deletes rows for departments 18 and 19.This example deletes rows for departments 18 and 19./* SQL Example 8.26 */DELETE dept_view2 WHERE dpt_no = 18 OR dpt_no = 19;(2 row(s) affected)

/* SQL Example 8.27 */SELECT *FROM department;

dpt_no dpt_name dpt_mgrssn dpt_mgr_start_date–––––– ––––––––––—–––––- –––––––—-- –––––-----------------–1 Headquarters 999666666 1981-06-19 00:00:00.0003 Admin and Records 999555555 2001-01-01 00:00:00.0007 Production 999444444 1998-05-22 00:00:00.000

Page 23: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 23

TABLES and the IDENTITY PROPERTYTABLES and the IDENTITY PROPERTY

• Suppose a furniture store needs to generate unique Suppose a furniture store needs to generate unique numbers to identify sales orders – how are these numbers to identify sales orders – how are these numbers produced?numbers produced?

• Solution – let the computer generate them from a Solution – let the computer generate them from a sequence of numbers.sequence of numbers.

• SQL Server provides this capability through tables SQL Server provides this capability through tables that have a column defined with the that have a column defined with the IdentityIdentity property clause.property clause.

• The general syntax of the IDENTITY clause is:IDENTITY [ ( initial_value , increment ) ]

Page 24: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 24

CREATE TABLE Syntax with CREATE TABLE Syntax with Identity ColumnIdentity Column

• The The sales_ordersales_order table example. table example.• The IDENTITY clause causes automatic generation The IDENTITY clause causes automatic generation

of of so_numberso_number column values with an initial value of column values with an initial value of 100 and increment of 1.100 and increment of 1.

/* SQL Example 8.28 */

CREATE TABLE sales_order (

so_number INTEGER IDENTITY(100,1)

CONSTRAINT pk_sales_order PRIMARY KEY,

so_value DECIMAL(9,2),

so_emp_ssn CHAR(9),

CONSTRAINT fk_so_emp_ssn

FOREIGN KEY (so_emp_ssn)

REFERENCES employee );

Page 25: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 25

Inserting Sales_Order RowsInserting Sales_Order Rows

• The INSERT statement shown here inserts three The INSERT statement shown here inserts three rows into the rows into the sales_ordersales_order table. table.

• Notice that a value is not inserted for the Notice that a value is not inserted for the so_numberso_number column. column.

/* SQL Example 8.29 */INSERT INTO sales_order VALUES (155.59, '999111111');

INSERT INTO sales_order VALUES (450.00, '999444444');

INSERT INTO sales_order VALUES (16.95, '999444444');

Page 26: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 26

Selecting Sales_Order RowsSelecting Sales_Order Rows

• SQL Example 8.30 shows the results of the SQL Example 8.30 shows the results of the three INSERT statements.three INSERT statements.

/* SQL Example 8.30 */SELECT *FROM sales_order;so_number so_value so_emp_ssn–––—––––––– ––––—–––-– ––––––––––100 155.59 999111111101 450.00 999444444102 16.95 999444444

Page 27: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 27

The Related Order_Details TableThe Related Order_Details Table

• The The sales_ordersales_order table is related in a one-to- table is related in a one-to-many fashion with the many fashion with the order_detailsorder_details table. table.

• The The order_detailsorder_details table has a table has a Composite Composite PRIMARY KEYPRIMARY KEY that includes the that includes the od_numberod_number and and od_rowod_row columns – columns – od_rowod_row is a way of numbering each item on an is a way of numbering each item on an order while order while od_number od_number is system generated is system generated and serves as a and serves as a FOREIGN KEYFOREIGN KEY link to the link to the sales_ordersales_order table. table.

Page 28: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 28

The Related Order_Details Table Cont.The Related Order_Details Table Cont.

/* SQL Example 8.31 */CREATE TABLE order_details ( od_number INTEGER, od_row INTEGER, od_product_desc VARCHAR(15), od_quantity_ordered INTEGER, od_product_price DECIMAL(9,2),CONSTRAINT pk_order_details PRIMARY KEY (od_number, od_row),CONSTRAINT fk_order_number FOREIGN KEY (od_number) REFERENCES sales_order );

Page 29: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 29

Inserting Rows in Sales_Order and Inserting Rows in Sales_Order and Order_DetailsOrder_Details

• Assume the first two Assume the first two sales_ordersales_order rows have been rows have been deleted.deleted.

/* Insert a new sales_order row and two order_detail rows */

INSERT INTO sales_order VALUES(200.00, '999111111' );GOBEGIN DECLARE @so_number INTEGER SELECT @so_number = (SELECT SCOPE_IDENTITY() ) INSERT INTO order_details VALUES (@so_number, 1, 'End Table', 1, 100.00); INSERT INTO order_details VALUES (@so_number, 2, 'Table Lamp', 2, 50.00);END

Page 30: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 30

Inserting Rows in Sales_Order and Inserting Rows in Sales_Order and Order_Details Contd.Order_Details Contd.

• SQL Example 8.32 defines a variable with a SQL Example 8.32 defines a variable with a DECLARE statement -- DECLARE statement -- @so_number@so_number..

• The The SCOPE_IDENTITYSCOPE_IDENTITY function, a pre-defined function, a pre-defined SQL Server function returns from the database SQL Server function returns from the database system tables the value of the last identity number system tables the value of the last identity number generated by the system generated by the system withinwithin the same the same procedure—here the value for the PRIMARY procedure—here the value for the PRIMARY KEY for the new KEY for the new sales_ordersales_order row. row.

• The variable value of The variable value of @so_number@so_number is inserted into is inserted into the the order_detailsorder_details rows in order to create the rows in order to create the necessary referential integrity link.necessary referential integrity link.

Page 31: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 31

Results of the Row InsertionsResults of the Row Insertions/* SQL Example 8.33 */SELECT *FROM sales_order;

so_number so_value so_emp_ssn–––-––––––– ––––-–––-– ––––––––––103 200.00 999111111

/* SQL Example 8.34 */SELECT od_number "So Number", od_row "Row", od_product_desc "Description", CAST(od_quantity_ordered As CHAR(3)) "Qty", od_product_price "Price"FROM order_details;

So Number Row Description Qty Price–––—–––—––– –––-– ––—–––––––––– –––– ––––––103 1 End Table 1 100.00103 2 Table Lamp 2 50.00

Page 32: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 32

Reviewing the Row InsertionsReviewing the Row Insertions

• The The IdentityIdentity property of the property of the so_numberso_number column column of the of the sales_ordersales_order table automatically generated table automatically generated the next identity number (the next identity number (103103). ).

• The The SCOPE_IDENTITYSCOPE_IDENTITY function enabled function enabled accessing this value from database system tables accessing this value from database system tables in order to insert the value into the in order to insert the value into the od_numberod_number column of the column of the order_detailsorder_details table. table.

• The two tables are linked through these columns The two tables are linked through these columns and their common values.and their common values.

Page 33: Prentice Hall © 20041 Chapter 8: Views and Synonyms SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 33

SummarySummary• Views are an important mechanism to facilitate the Views are an important mechanism to facilitate the

display of selected table columns.display of selected table columns.• Views provide a form of database security by Views provide a form of database security by

limiting access to columns displayed.limiting access to columns displayed.• Views can be used for DML of underlying tables Views can be used for DML of underlying tables

if they are “updateable” views.if they are “updateable” views.• Identity columns can be used to generate primary Identity columns can be used to generate primary

key values automatically.key values automatically.• The SCOPE_IDENTITY property enables The SCOPE_IDENTITY property enables

retrieval of identity number values from database retrieval of identity number values from database system tables to enforce referential integrity system tables to enforce referential integrity between two or more tables.between two or more tables.