35
© Copyright 2004 J. B. Gallaher 1 ETEC 4601 Database Systems Chapter 7: SQL for Database Construction and Application Processing

ETEC 430 Database Systems - Computer Engineering ...jgallaher/download/ETEC4601...A stored procedure is a program that is stored within the database and compiled when used. They can

Embed Size (px)

Citation preview

© Copyright 2004 J. B. Gallaher 1

ETEC 4601 Database Systems

Chapter 7: SQL for Database Construction and Application Processing

2

View Ridge Gallery

Application requirementsTrack customers and their artist interestsRecord gallery's purchasesRecord customers' art purchasesList the artists and works that have appeared in the galleryReport how fast an artist's works have sold and at what marginShow current inventory in a Web page

3

View Ridge Gallery (continued) View Ridge Data Model

We will use the View Ridge Gallery as an example for this chapter.Database Design with Data Keys

4

View Ridge Gallery (continued) Surrogate Key Database Design

Note that all Primary Keys have been replaced with Surrogate Keys. (The Identity constraint identifies Surrogate Kys and defines the starting number and increment to assign to these keys.)

5

View Ridge Gallery (continued) Referential Integrity Actions for M-O Relationships

6

SQL DDL, DML, And Joins

Managing Table Structure with SQL DDL

7

SQL DDL, DML, And Joins

Creating the Artist Table

8

SQL DDL, DML, And Joins

SQL Data Types in DBMS Products

9

SQL DDL, DML, And JoinsCreating the Work Table and the 1:N Artist/Work Relationship

You must create the parent tables before the child table.Tables must be deleted in the opposite order

10

SQL DDL, DML, And JoinsCasual Relationships

Table has a Foreign Key column but not a FOREIGN KEY constraint.Used to process tables with missing data as the Foreign Key does not have to be the parent table Primary Key.

Summary of Relationship Definitions Using CREATE TABLE

11

SQL DDL, DML, And Joins

Creating Default Values and Data Constraints with SQL

12

SQL DDL, DML, And JoinsCreating Default Values and Data Constraints with SQL

Default value

13

Creating the View Ridge DatabaseSQL for creating all of the tables in the View Ridge Database

14

Alter StatementThe ALTER statement is a SQL DDL statement used to change the structure of an existing table.Adding and Dropping Columns

ALTER TABLE CUSTOMER ADD MyColumn Char(5) Null;ALTER TABLE CUSTOMER DROP COLUMN MyColumn;

Adding and Dropping ConstraintsALTER TABLE CUSTOMER ADD CONSTRAINT MyConstraint CHECK([Name] NOT IN ('Robert No Pay'));ALTER TABLE CUSTOMER DROP CONSTRAINT MyConstraint;

Removing tablesDROP TABLE [TRANSACTION];To remove a table with constraints you will need several statements:

DROP TABLE CUSTOME_ARTIST_INT;DROP TABLE [TRANSACTION];DROP TABLE CUSTOMER;

15

SQL DMLUsing SQL to maintain data:SQL INSERT Using Column Names

INSERT INTO ARTIST([Name], Nationality, Birthdate, DeceasedDate) VALUES (“Tamayo', 'Mexican', 1927, 1998);

Bulk INSERTUse a SQL SELECT statement to provide values:INSERT INTO ARTIST([Name], Nationality, Birthdate) SELECT [Name], Nationality, Birthdate FROM IMPORTED_ARTIST;

16

SQL DMLSQL UPDATE Command

UPDATE CUSTOMER SET City = 'New York City' WHERE CustomerID = 1000;UPDATE CUSTOMER SET City = 'New York City', State = 'NY' WHERE customerID = 1000;

Bulk UpdatesUPDATE CUSTOMER SET City = 'New York City';UPDATE CUSTOMER SET AreaCode = '303' WHERE city = 'Denver';

Updating Using Values from Other TablesUPDATE PURCHASE_ORDER SET TaxRate = (SELECT Tax from TAX_TABLE WHERE TAX_TABLE.City = 'Bodega Bay') WHERE PURCHASE_ORDER.City = “BodegaBay';UPDATE PURCHASE_ORDER SET TaxRate = SELECT Tax from TAX_TABLE WHERE TAX_TABLE.City = PURCHASE_ORDER.City) Where PURCHASE_ORDER.Number = 1000;

17

SQL DML

SQL DELETE StatementDELETE FROM CUSTOMER WHERE CustomerID = 1000;If you do not use the WHERE clause you will delete all rows in the table.

18

New Forms of JoinJoin On Syntax

SELECT * FROM ARTIST, WORK WHERE ARTIST.ArtistID = WORK.ArtistID;Is equivalent to:SELECT * FROM ARTIST JOIN WORK ON ARTIST.ArtistID = WORK.ArtistID;To join three or more tables:

SELECT CUSTOMER.Name, ARTIST.Name FROM CUSTOMER JOIN CUSTOMER_ARTIST_INT ON CUSTOMER.CustomerID = CUSTOMER_ARTIST_INT.CustomerID JOIN ARTIST ON CUSTOMER_ARTIST_INT.ArtistID = ARTIST.ArtistID;

19

New Forms of JoinOuter Joins

SELECT C.Name, T.SalesPrice FROM CUSTOMER AS C JOIN [TRANSACTION] AS T ON C.CustomerID = T.CustomerID;This statement only shows part of the data. Some customers are missing. (See figure on left below.) Use a LEFT OUTER Join:

SELECT C.Name, T.Sales Price FROM CUSTOMER AS C LEFT JOIN [TRANSACT] AS T ON C.CustomerID = T.CustomerID;This shows all artists. (See figure on the right below.)

20

Using SQL Views

A SQL view is a virtual table that is constructed from other tables or views.It has no data of its ownWe construct views from SQL SELECT statements.However, some DBMSs will not allow the ORDER BY clauseCreate View statement:

CREATE VIEW CustomerNameView AS SELECT [Name] AS CustomerName FROM CUSTOMER;

We can use the view just like a table:SELECT * FROM CustomerNameView ORDER BY CustomerName;

21

Using SQL Views

Using Views to Hide Columns and RowsBy limiting the columns we can hide column data:

CREATE VIEW BasicCustomerData AS SELECT [Name], AreaCode, PhoneNumber FROM CUSTOMER;

By using a WHERE clause we can hide some rows:CREATE VIEW BasicCustomerData_WA AS SELECT Name, AreaCode, PhoneNumber FROM CUSTOMER WHERE State = 'WA';

Uses for SQL Views

22

Using SQL Views

Using Views to Display Results of Computed ColumnsCREATE VIEW CustomerPhone AS SELECT Name, ('('+ AreaCode + ')' + PhoneNumber) AS Phone FROM CUSTOMER;

Result of SELECT statement on this View

23

Using SQL Views

Using Views to Hide Complicated SQL SyntaxCREATE VIEW CustomerInterests As SELECT c.Name as Customer, A.Name as Artist FROM Customer AS C JOIN CUSTOMER_ARTIST_INT AS CI ON C.CustomerID = CI.CustomerID JOINT ARTIST A on CI.ARtistID = A.ArtistID;

Using a SELECT statement on the view is simpleSELECT * FROM CustomerInterests ORDER BY Customer;

24

Using SQL Views

Layering Built-In FunctionsYou can construct a view that computes a variable and then write SQL on that view that uses the computed variable in a WHERE clause.CREATE VIEW ArtistWorkNet AS SELECT W.WorkID, Name, Title, Copy, AcquisitionPrice, SalesPrice, (SalesPrice-AcquisitionPrice) AS NetPrice FROM [TRANSACTION] AS T JOIN WORK AS W ON T.WorkID = W.WorkID JOIN ARTIST AS A ON W.ArtistID = A.ArtistID;Now use the view in a WHERE clause:

SELECT Name, NetPrice FROM ArtistWorkNet WHERE NetPrice > 10000;

25

Using SQL Views

Using Views for Isolation, Multiple Permissions, and Multiple TriggersIsolating data tables from application code:

CREATE VIEW CustomerTable1 AS SELECT * FROM CUSTOMER;

To implement multiple permissions, we can use views to let users read and write to the view but not to the underlying tables.Multiple Triggers can be implement on different views of the same underlying tables. This allows enforcing O-M and M-M relationships

26

Using SQL Views

Updating ViewsRequires special consideratin since the underlying table must be updated from the views.Computed values cause problems since they don't exist in the underlying tables.Aliases for column names are also a problem

Guidelines for Updating Views

27

Embedding SQL in Program CodeSQL statements can be embedded in application programs, triggers, and stored procedures.Some problems must be addressed:

Some means of assigning the results of SQL statements to program variables must be available. Paradigm mismatch: SQL is table oriented

SQL is table oriented: SELECT statements result in tablesProgramming languages are variable oriented.

Results of SQL statements are treated as pseudofiles with a cursor to a particular row – moving the cursor selects a row that can then be assigned to a variable.

Pseudocode for using SQL:Open SQL (SELECT * FROM CUSTOMER);Move cursor to first row;

While cursor not past end of result {Set custName = Name;.... other statements .....Advance cursor to next row;

};

28

Using TriggersA trigger is a stored program that is executed by the DBMS whenever a specified event occurs.A trigger is attached to a table or view. (A table may have many triggers, but a trigger is attached to only one table.) Triggers are invoked by: INSERT, UPDATE, or DELETETypes of triggers:

Before: (not supported by SQL Server) executes before eventInstead of: executes instead of normal eventAfter: executes after the event has processed

Uses for Triggers

29

Using TriggersUsing Triggers to Provide Default Values

Example: Setting the asking price to either the acquisition price or acquisition price + average net gain

30

Using TriggersUsing Triggers to Enforce Data Constraints

Example: Mexican painters are never discounted so the sales price must always be at least the asking price.

31

Using Triggers

Updating ViewsExample: We can update a view using an INSTEAD OF trigger:

32

Using TriggersA Trigger on Delete Employee (Referential Integrity Issue)

First check to be sure it is not the last employeeDelete if not the last employee, do nothing otherwise

33

Using Triggers

A Trigger on DeleteEmployeeDepartmentChecks to see If the employee is the last in the departmentIt deletes department if the employee is the lastThe employee is deleted in either case.

34

Using Stored Procedures

A stored procedure is a program that is stored within the database and compiled when used.They can receive input parameters and return results.Stored procedures are attached to the databaseThey can be executed by any process that has the proper permissions

Triggers Versus Stored Procedures

35

Stored Procedures

The Add_Work Stored Procedure

This procedure checks for several conditions fixes them then inserts the data.