databases and sql · databases and sql case study: server database example adam harewood january...

62
Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

Upload: others

Post on 24-Jun-2020

20 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

Databases and SQL

Case Study: Server Database Example

Adam Harewood

January

2008

Page 2: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

ABSTRACT

This report has been produced to provide the basis of action concerning the

design of a retail company’s database system.

i

Page 3: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

ACKNOWLEDGMENTS I am grateful to a number of people for their comments and assistance during the

production of this document. In particular, thanks are due to Anne Siedle for her

Report Writing Booklet (UoT), Mansha Nawaz for his guidance and knowledge

and Game Stores Group plc for allowing the analysis of their entire system.

ii

Page 4: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

CONTENTS 1  CASE STUDY................................................................................................. 4 

1.1  Case Study Scenario .............................................................................. 4 1.2  Additional Considerations ..................................................................... 4 1.3  Deliverables............................................................................................. 5 

2  MS SQL Server Database ............................................................................. 6 2.1  Database Diagrams................................................................................. 6 

2.1.1  ERD – Physical View (Full model)....................................................... 6 

2.1.2  Customers........................................................................................... 7 

2.1.3  Staff..................................................................................................... 8 

2.1.4  Products.............................................................................................. 9 

2.1.5  Couriers ............................................................................................ 10 

2.1.6  Suppliers ........................................................................................... 10 

2.2  Management Studio.............................................................................. 11 2.2.1  Tables (physical) with sample data ................................................... 11 

2.2.2  Views (logical) with sample data ...................................................... 26 

3  DEMONSTRATION OF SQL Code .............................................................. 27 3.1  DATA DEFINITION LANGUAGE ........................................................... 27 

3.1.1  CREATE TABLE ............................................................................... 27 

3.1.2  CREATE INDEX................................................................................ 27 

3.1.3  DROP TABLE ................................................................................... 27 

3.1.4  CONSTRAINT................................................................................... 28 

3.1.5  CREATE VIEW ................................................................................. 28 

3.1.6  CREATE TRIGGER .......................................................................... 28 

3.2  DATA MANIPULATION LANGUAGE .................................................... 30 3.2.1  SELECT & FROM ............................................................................. 30 

3.2.2  WHERE............................................................................................. 31 

3.2.3  ORDER BY ....................................................................................... 31 

3.2.4  DISTINCT ......................................................................................... 32 

3.2.5  BETWEEN and LIKE......................................................................... 33 

3.2.6  IN and NOT IN Joining Tables .......................................................... 34 

3.2.7  Aliases for Tables.............................................................................. 35 

3.2.8  Sub-Queries...................................................................................... 35 

iii

Page 5: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

3.2.9  INSERT............................................................................................. 36 

3.2.10  DELETE ......................................................................................... 37 

3.2.11  UPDATE ........................................................................................ 37 

4  SQL: Advance Server - Client Features .................................................... 39 4.1  MS SQL Server Attach and Detach...................................................... 39 

4.1.1  Detaching the database. ................................................................... 39 

4.1.2  Attaching the database ..................................................................... 40 

4.2  MS SQL Server Web Development ...................................................... 43 4.2.1  Connection between the database and website................................ 43 

4.2.2  Website design ................................................................................. 44 

5  Critical Review ............................................................................................ 47 5.1  Conclusion ............................................................................................ 47 5.2  Critical Review of ICA Assessment..................................................... 47 

5.2.1  Report/Case Study/Critical Review ................................................... 47 

5.2.2  SQL Implementation : ERD development ......................................... 47 

5.2.3  SQL Implementation : Tables and Views .......................................... 47 

5.2.4  SQL Implementation : Test Data....................................................... 47 

5.2.5  SQL : Additional and Advanced Features ......................................... 48 

5.3  Critical Review of ICA........................................................................... 48 5.3.1  ICA Goals.......................................................................................... 48 

5.3.2  ICA Achievements............................................................................. 48 

5.3.3  ICA Non-Achievements..................................................................... 48 

5.3.4  ICA Evaluation .................................................................................. 48 

5.4  Critical Review of Product.................................................................... 48 5.4.1  Database Achievements ................................................................... 48 

5.4.2  Database Non-Achievements ........................................................... 48 

5.4.3  Database Evaluation ......................................................................... 49 

6  References................................................................................................... 50 6.1  Bibliography .......................................................................................... 50 6.2  Websites ................................................................................................ 50 

7  Appendix...................................................................................................... 51 7.1  Hyperlinks to database files................................................................. 51 7.2  All script files for section 3 and 4........................................................ 51 

iv

Page 6: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

v

7.2.1  SELECT and FROM.......................................................................... 51 

7.2.2  WHERE............................................................................................. 51 

7.2.3  ORDER BY ....................................................................................... 51 

7.2.4  DISTINCT ......................................................................................... 52 

7.2.5  BETWEEN ........................................................................................ 52 

7.2.6  LIKE .................................................................................................. 52 

7.2.7  IN ...................................................................................................... 52 

7.2.8  NOT IN.............................................................................................. 52 

7.2.9  Aliases .............................................................................................. 53 

7.2.10  Subqueries..................................................................................... 53 

7.2.11  INSERT.......................................................................................... 53 

7.2.12  UPDATE ........................................................................................ 53 

7.3  Code for the Adobe Macromedia Dreamweaver link.......................... 53 7.3.1  Image upload code............................................................................ 53 

7.3.2  Main page - sqlretailsite/Page1......................................................... 54 

7.3.3  PC listing page – PCFULL.aspx........................................................ 56 

7.3.4  PS2 listing page – PS2FULL.aspx .................................................... 58 

7.3.5  Displaying the images – get_files.aspx ............................................. 59 

Page 7: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

4

1 CASE STUDY

1.1 Case Study Scenario

A retail company, with a number of branches, wishes to implement a computer

based database system that will encompass all parts of the business.

The current system has no availability for record keeping and also lacks a basic

control. No management information, for pro-active and re-active commercial

decisions, exists and even simple tasks such as payroll are on an ad hoc basis.

Customers at the moment are not rewarded for their repeat custom and discounts

are at the discretion of the management – with no head office input and with no

uniformity.

1.2 Additional Considerations

The database system is to be utilised by a number of different methods – via the

internet (for customer ordering purposes), an EPoS (Electronic Point-of-Sale)

tilling system (by shop staff) and a bespoke interface program (for use by

administrative staff).

The company gives customers discounts based on previous spending patterns.

These savings are in the form of discount against future purchases. For this

purpose the database model must contain customer details, purchase history and

discounts achieved. Delivery details and payment options need to be created,

utilised and stored.

Previous systems have had no dealings with stock or price management – these

needs are to be bought under the control of the management at store and head

office level. Stock inventory needs to be logged as does the actual products

themselves, full costing for that product (and historical data) and supplier details.

Purchase orders for the suppliers should be properly generated and recorded.

Page 8: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

5

All items sold are subject to VAT. Different rates exist (depending on the category

that product falls in), and these need to be recorded.

Staff details need to be registered for basic functions such as payroll. This should

also lead to greater store security – through the use of individual personal till

access numbers – and allow an information system for the management of staff

performance.

The new implementation will be a basic design and in no way constitutes a

complete finished system. However, the design will and allow for changes and

expansion into a viable, complete system.

This report aims to outline a design for the system according to the requirements

outlined above.

1.3 Deliverables

For this report a full Entity Relationship Diagram (“ERD”) will be produced

showing the relationships between the different parts of the proposed system.

This will also be used as the basis for defining the database itself. As the ERD

takes shape so does the database - and vice versa.

By using Microsoft’s SQL Server Management Studio program, the

implementation can be shown through pictorial evidence (such as the ERD) and

that of replication of code. This code will show how the database records can be

altered, updated and deleted as and when is necessary.

Also included will be a section showing a link to a web-based system. This will

include a dynamic data link and the storage and retrieval of images to and from

the database.

Page 9: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

2 MS SQL Server Database

2.1 Database Diagrams

2.1.1 ERD – Physical View (Full model)

Customerscustomer_id

customer_sname

customer_fname

customer_phone

customer_mobile

customer_fax

customer_email

Customer_Addressescustomer_id

address_id

date_from

address_type_code

date_to

Addressesaddress_id

line_1

line_2

line_3

line_4

city

zip_postcode

state_province_county

country

Basketscustomer_id

sale_number

basket_sale_type

staff_id

store_id

date_of_sale

Productsproduct_id

product_type_code

product_name

product_description

product_cost_price

product_sale_price

product_vat_rate_code

product_BBFC_rating

product_PEGI_rating

Ref_Product_Typesproduct_type_code

product_type_description

Product_Suppliersproduct_id

supplier_id

value_supplied_to_date

qty_supplied_to_date

delivery_lead_time

minimum_order_qty

maximum_order_qty

Customer_Detailscustomer_id

customer_dob

customer_sex

customer_no_of_children

Loyalty_Detailscustomer_id

card_number

points_total

discount_code

Discountsdiscount_code

discount_description

discount_amount

Ref_Vat_Ratesproduct_vat_rate_code

product_vat_rate

Storesstore_id

address_id

store_name

store_grade

store_phone

store_fax

store_email

sales_area

Store_Employeesstore_id

staff_id

Employeesstaff_id

staff_sname

staff_fname

address_id

staff_phone

staff_mobile

staff_email

staff_ni_number

date_started

date_of_birth Employee_Jobsstaff_id

job_id

Job_Descriptionsjob_id

job_name

job_hourly_rate

discount_code

holiday_entitlement

security_level

Store_Typestore_grade

no_of_bays

no_of_tills

grade_multiplier

Ref_Sale_Typesbasket_sale_type

basket_sale_description

Ref_Dispatch_Codedispatch_code

delivery_hours

dispatch_cost

Courierscourier_id

courier_name

courier_phone

courier_fax

courier_email

Courier_Addressescourier_id

address_id

address_type_code

Supplierssupplier_id

supplier_name

supplier_phone

supplier_fax

supplier_email

Dispatchessale_number

courier_id

date_sent

dispatch_code

Purchase_Orderspurchase_order_number

store_id

date_of_order

date_fulfilled

Returnsreturns_number

customer_id

sale_number

product_id

quantity

return_code

Supplier_Addressessupplier_id

address_id

address_type_code

Ref_Address_Typesaddress_type_code

address_type_description

Operator_Codesstaff_id

TAN

Ref_Returns_Reasonsreturn_code

return_code_description

Basket_Itemssale_number

product_id

product_qty

ImageFilesproduct_id

myfilename

myfile

filetype

Purchase_Order_Itemspurchase_order_number

product_id

order_quantity

Stock_Holdingsstore_id

product_id

quntity_on_hand

FIG A – Complete ERD

From the diagram above, it is possible to see that system is a large and complex

one. For the ease of understanding how one part of the system relates to other

6

Page 10: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

parts of the system we can split it down into sections based on the main entities.

These are:

• Customers

• Staff

• Products

• Couriers

• Suppliers

2.1.2 Customers

Customerscustomer_id

customer_sname

customer_fname

customer_phone

customer_mobile

customer_fax

customer_email

Customer_Addressescustomer_id

address_id

date_from

address_type_code

date_to

Addressesaddress_id

line_1

line_2

line_3

line_4

city

zip_postcode

state_province_county

country

Basketscustomer_id

sale_number

basket_sale_type

staff_id

store_id

date_of_sale

Customer_Detailscustomer_id

customer_dob

customer_sex

customer_no_of_children

Loyalty_Detailscustomer_id

card_number

points_total

discount_code

Discounts *discount_code

discount_description

discount_amount

Ref_Sale_Typesbasket_sale_type

basket_sale_description

Returnsreturns_number

customer_id

sale_number

product_id

quantity

return_code

Ref_Address_Typesaddress_type_code

address_type_description

Ref_Returns_Reasonsreturn_code

return_code_description

FIG B – Customer ERD

This part of the main ERD shows all of the relationships that are immediately

concerned with the customer. Note the relationships between the different tables

and how it is possible, for example, for each customer to have a number of

different addresses – such as a billing address, a delivery address etc... For this

7

Page 11: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

reason the primary key has been set to an address identity number (address_id)

which is the only way a unique identifier could be shown.

2.1.3 Staff

Addressesaddress_id

line_1

line_2

line_3

line_4

city

zip_postcode

state_province_county

country

Basketscustomer_id

sale_number

basket_sale_type

staff_id

store_id

date_of_sale

Discountsdiscount_code

discount_description

discount_amount

Store_Employeesstore_id

staff_id

Employeesstaff_id

staff_sname

staff_fname

address_id

staff_phone

staff_mobile

staff_email

staff_ni_number

date_started

date_of_birth Employee_Jobsstaff_id

job_id

Job_Descriptionsjob_id

job_name

job_hourly_rate

discount_code

holiday_entitlement

security_level

Operator_Codesstaff_id

TAN

FIG C – Staff ERD

It can be seen that an overlap exists between the Staff ERD and that of the

Customer. The Addresses, Baskets and Discounts tables are duplicated in both

models and it is therefore necessary to ensure that the data to be held in these

three tables are compatible with each of the entities’ sides.

8

Page 12: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

2.1.4 Products

Basketscustomer_id

sale_number

basket_sale_type

staff_id

store_id

date_of_sale

Productsproduct_id

product_type_code

product_name

product_description

product_cost_price

product_sale_price

product_vat_rate_code

product_BBFC_rating

product_PEGI_rating

Ref_Product_Typesproduct_type_code

product_type_description

Product_Suppliersproduct_id

supplier_id

value_supplied_to_date

qty_supplied_to_date

delivery_lead_time

minimum_order_qty

maximum_order_qty

Ref_Vat_Ratesproduct_vat_rate_code

product_vat_rate

Purchase_Orderspurchase_order_number

store_id

date_of_order

date_fulfilled

Basket_Itemssale_number

product_id

product_qty

ImageFilesproduct_id

myfilename

myfile

filetype

Purchase_Order_Itemspurchase_order_number

product_id

order_quantity

Stock_Holdingsstore_id

product_id

quntity_on_hand

FIG D – Products ERD

9

This model was the “easiest” to produce – at first. Though like all ERDs, one table

will ultimately lead to another. The Ref_Product_Types table was introduced to

create “categories” for products – to help in Management Information System

(“MIS”) reporting, provide ease of use when applying a “department” discount or

even for simple referencing.

Page 13: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

Note also the table ImageFile. This has been developed using the CREATE

command (shown later) to implement graphical processing with a web-based

element.

2.1.5 Couriers

Customerscustomer_id

customer_sname

customer_fname

customer_phone

customer_mobile

customer_fax

customer_email

Customer_Addressescustomer_id

address_id

date_from

address_type_code

date_to

Addressesaddress_id

line_1

line_2

line_3

line_4

city

zip_postcode

state_province_county

country

Basketscustomer_id

sale_number

basket_sale_type

staff_id

store_id

date_of_sale

Productsproduct_id

product_type_code

product_name

product_description

product_cost_price

product_sale_price

product_vat_rate_code

product_BBFC_rating

product_PEGI_rating

Ref_Dispatch_Codedispatch_code

delivery_hours

dispatch_cost

Courierscourier_id

courier_name

courier_phone

courier_fax

courier_email

Courier_Addressescourier_id

address_id

address_type_code

Dispatchessale_number

courier_id

date_sent

dispatch_code

Returnsreturns_number

customer_id

sale_number

product_id

quantity

return_code

Ref_Address_Typesaddress_type_code

address_type_description

Ref_Returns_Reasonsreturn_code

return_code_description

Basket_Itemssale_number

product_id

product_qty

FIG E – Courier ERD

This proved a complicated ERD as there were a number of considerations to be

taken into account, i.e. the other ERDs. The need to ensure compatibility

between different parts of the model was imperative as was the need to ensure

that there was not any duplication of data or redundant tables. Note that the

Addresses table has been used once again for this very reason.

2.1.6 Suppliers

10

Page 14: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

Addressesaddress_id

line_1

line_2

line_3

line_4

city

zip_postcode

state_province_county

country

Productsproduct_id

product_type_code

product_name

product_description

product_cost_price

product_sale_price

product_vat_rate_code

product_BBFC_rating

product_PEGI_rating

Product_Suppliersproduct_id

supplier_id

value_supplied_to_date

qty_supplied_to_date

delivery_lead_time

minimum_order_qty

maximum_order_qty

Supplierssupplier_id

supplier_name

supplier_phone

supplier_fax

supplier_email

Purchase_Orderspurchase_order_number

store_id

date_of_order

date_fulfilled

Supplier_Addressessupplier_id

address_id

address_type_code

Ref_Address_Typesaddress_type_code

address_type_description

Purchase_Order_Itemspurchase_order_number

product_id

order_quantity

FIG F – Suppliers ERD

By far the most simple of the ERDs to produce, the model only required one

original table (Product_Suppliers), with the rest being amended from previous

ERDs or actually included in those previous models.

2.2 Management Studio

2.2.1 Tables (physical) with sample data

The following sections give the Physical Table data for each of the tables.

Following on from the table data is a sample of the data that is carried in that

table. At the end of each section you will find the hyperlink to the SQL code to

generate each of the tables.

The data for these tables could have been inputted using the INSERT command.

However, the data was added to the tables when they were “open” in the

Management Studio window. This allowed for speed of input and required no

writing of code – for either direct SQL input or an intermediary program (such as

Microsoft Access)

11

Page 15: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

2.2.1.1 Addresses

SQL code

2.2.1.2 Basket_Items

12

Page 16: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

SQL Code

2.2.1.3 Baskets

SQL Code

2.2.1.4 Courier_Addresses

SQL Code

13

Page 17: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

2.2.1.5 Couriers

SQL Code

2.2.1.6 Customer_Addresses

SQL Code

2.2.1.7 Customer_Details

14

Page 18: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

SQL Code

2.2.1.8 Customers

SQL Code

2.2.1.9 Discounts

SQL Code

15

Page 19: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

2.2.1.10 Dispatches

SQL Code

2.2.1.11 Employee_Jobs

SQL Code

2.2.1.12 Employees

16

Page 20: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

SQL Code

2.2.1.13 ImageFiles

SQL Code

2.2.1.14 Job_Descriptions

17

Page 21: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

SQL Code

2.2.1.15 Loyalty_Details

SQL Code

2.2.1.16 Operator_Codes

18

Page 22: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

SQL Code

2.2.1.17 Product_Suppliers

SQL Code

2.2.1.18 Products

19

Page 23: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

SQL Code

2.2.1.19 Purchase_Orders

SQL Code

2.2.1.20 Purchase_Order_Items

SQL Code

2.2.1.21 Ref_Address_Types

20

Page 24: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

SQL Code

2.2.1.22 Ref_Dispatch_Code

SQL Code

2.2.1.23 Ref_Product_Types

21

Page 25: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

SQL Code

2.2.1.24 Ref_Returns_Reasons

SQL Code

2.2.1.25 Ref_Sale_Types

22

Page 26: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

SQL Code

2.2.1.26 Ref_Vat_Rates

SQL Code

2.2.1.27 Returns

SQL Code

2.2.1.28 Stock_Holdings

SQL Code

23

Page 27: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

2.2.1.29 Store_Employees

SQL Code

2.2.1.30 Store_Type

SQL Code

24

Page 28: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

2.2.1.31 Stores

SQL Code

2.2.1.32 Supplier_Addresses

SQL Code

2.2.1.33 Suppliers

SQL Code

25

Page 29: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

2.2.2 Views (logical) with sample data

Courier Details

SELECT dbo.Couriers.courier_name, dbo.Addresses.line_1,

dbo.Addresses.line_2, dbo.Addresses.line_3,

dbo.Addresses.line_4, dbo.Addresses.city,

dbo.Addresses.zip_postcode,

dbo.Addresses.state_province_county, dbo.Addresses.country,

dbo.Couriers.courier_phone

FROM dbo.Addresses

INNER JOIN dbo.Courier_Addresses ON dbo.Addresses.address_id =

dbo.Courier_Addresses.address_id

INNER JOIN dbo.Couriers ON dbo.Courier_Addresses.courier_id =

dbo.Couriers.courier_id

By using the SQL code above, the following View can be obtained.

By creating new Views (right click on the Views folder and then New View) a

number of different tasks can be achieved. A database of this size has almost

limitless possibilities.

26

Page 30: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

3 DEMONSTRATION OF SQL Code

The usage of SQL code can be broken down into two clear sections –

i) the creation of the database and all it’s elements and

ii) the manipulation of that data.

3.1 DATA DEFINITION LANGUAGE

The following are the main parts of the language, from which a database can be

created and populated with data.

3.1.1 CREATE TABLE

The code to create all of the tables can be found in the individual sub-sections of

2.2.1.

3.1.2 CREATE INDEX

An index is a quick way for SQL to get the data back from the database.

This code produces an index on the customer_id column in the Customers table.

The corresponding message received is displayed below.

3.1.3 DROP TABLE

A table can be deleted from the database by using the DROP command.

The table and all associated relationships will be removed from the database.

The corresponding message received is displayed below.

27

Page 31: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

3.1.4 CONSTRAINT

The only use of constraints (a device by which inappropriate data is excluded

from the tables) within the database relates to Primary and Foreign Keys.

The SQL generated code for the Primary Key in the Customer table is this: CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED ([customer_id] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]

The SQL generated code for one of the Foreign Keys in the

Purchase_Order_Items table is written as: CONSTRAINT [FK_Purchase_Order_Items_Products] FOREIGN KEY([product_id]) REFERENCES [dbo].[Products] ([product_id])

3.1.5 CREATE VIEW

A View is a temporary table created from the data held with the main (“base”)

tables. See section 2.2.2 for the CREATE VIEW command and output.

3.1.6 CREATE TRIGGER

A Trigger is a stored procedure that runs when something happens inside the

database. CREATE TRIGGER NoChanges ON DATABASE FOR DROP_TABLE, ALTER_TABLE, CREATE_TABLE AS PRINT 'NO CHANGES ARE ALLOWED - PLEASE DISABLE THIS TRIGGER' ROLLBACK

The above command creates a new procedure “NoChanges” that displays a

message if anyone attempts to delete, change or create a table. When the

command is executed the following message is displayed.

By entering this code: CREATE TABLE Employee_Sales (ID int PRIMARY KEY, product_id nchar(13))

The following output is received:

28

Page 32: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

Triggers are useful when a response or notification is necessary to an internal or

external stimuli. This allow the database administrator to secure the system and

record events (triggers can be used in procedures to do this automatically).

29

Page 33: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

3.2 DATA MANIPULATION LANGUAGE

The following are the main parts of the language, from which a data held within

the database can be manipulated to achieve the results requested from the end-

user.

3.2.1 SELECT & FROM

Selecting data from the database is a tool that can be used to great effect in

obtaining a variety of data.

A basic use of the SELECT FROM statement, shown above, has displayed all of

the fields of the table Products. Not all of the data may be necessary – for

example, a website might only want the customer to see the product_id,

product_name and the product_sale_price. That can be achieved by using the

code below.

As is seen, the three parts of the table required is shown.

30

Page 34: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

To show information from another table is a relatively easy task. For example, we

want the data already selected but want to add the product type. We have to join

the two tables together to so the system does not throw up an error; this can be

achieved by using the JOIN command.

3.2.2 WHERE

Following on from the previous query, we can use the WHERE clause to narrow

the selection down even further.

For example, if we were to only select those products that were £19.99 or less,

we could use the following code:

3.2.3 ORDER BY

The current query result is in ascending order of barcode (product_id) – as the

table file is saved. By using the ORDER BY clause we can change the way the

31

Page 35: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

results are sorted. The following example sorts the products by alphabetical

name order.

3.2.4 DISTINCT

The DISTINCT command removes the duplication of field data. Consider the

following:

We can see that there is duplication in row 1 & 2, 3 & 4 and 5 & 6. By using the

SELECT DISTINCT command we can remove that repetition.

32

Page 36: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

3.2.5 BETWEEN and LIKE

The BETWEEN clause, used in conjunction with the WHERE statement is used

for range matching. If the products between £4.50 and £17.50 were to be

selected the following code would be used.

The LIKE clause, once again used with WHERE, can be used for range

matching. This clause can specify searches like string matches. For example, if

we wanted to search for any “Tennis” products we would use the LIKE clause.

33

Page 37: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

3.2.6 IN and NOT IN Joining Tables

IN and NOT IN are just like the other operands; i.e. fairly easy to understand. IN

looks for an attribute match for a set of variables. NOT IN does the opposite.

To list all the products that sell at £4.99 or £9.99 we would use the following:

To list all the products that sell for prices other than £4.99 or £9.99, the following

would be used:

34

Page 38: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

3.2.7 Aliases for Tables

If we wish to make multiple SELECTs from the same table, we need to use an

alias for the table. This stops the program suffering from ambiguity and can also

reduce the length of the SQL statement.

If we wanted to find the VAT rate for Learning Ladder and display all of the titles

that are not in the rate the following code can be used:

3.2.8 Sub-Queries

Sub-queries can be used instead of the JOIN command. Consider that we would

like to know all of the names of the products sold. We could use the JOIN

statement, but the processing time (moving a lot of data around) could be

35

Page 39: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

prohibitive. We use a sub-query (just like a nested function in other languages) to

produce a set of results before using those results to produce the final, required,

result.

3.2.9 INSERT

The INSERT command will allow us to add just one row into the table.

To add another discount level to the Discount table we would use this code:

On execution the message is displayed and the new Discount table looks like

this:

36

Page 40: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

Note the new values in at row 9.

3.2.10 DELETE

The reverse of INSERT is DELETE by using the following code:

Executing the code displays the above message and the Discount table looks like

this:

.

Note the row with the SPECL discount code in has been deleted.

3.2.11 UPDATE

If we want to change the amount of discount the store's staff members have –

increasing it from 25% to 30% we would use the UPDATE command.

37

Page 41: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

The message informs us that the row was “affected”. The updated table now

looks like this:

Note the STORE discount rate has been changed in both the

discount_description and discount_amount.

38

Page 42: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

4 SQL: Advance Server - Client Features

4.1 MS SQL Server Attach and Detach

The database was developed on two different computers. This required the

movement of the files from one machine to the other. The following methods for

detaching and attaching the database to the SQL server program can be followed

should the files need to be transferred to another machine due to site relocation

or upgrade.

4.1.1 Detaching the database.

Right-clicking on the database you wish to move (in the Object Explorer) will bring

up a menu.

Selecting Tasks/Detach… will bring up the following window:

39

Page 43: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

Selecting “OK” will detach the required database. The database files (*.mdf and

*.ldf) can now be copied over to the new system. These files usually reside in

C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data for a standalone

workstation.

4.1.2 Attaching the database

Before starting the Microsoft SQL Server it is necessary to copy over the two file

(*.mdf and *.ldf) to the Data folder on the new system. As stated above the

directory path is usually C:\Program Files\Microsoft SQL

Server\MSSQL.1\MSSQL\Data.

Once this has been completed it is necessary to right-click on “Databases” and

selecting “Attach…”:

40

Page 44: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

A window will then open:

Clicking on the Add.. button will open a further window:

41

Page 45: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

Highlighting your required database and clicking on “OK” will return you to the

previous window – with the necessary information entered:

Clicking on “OK” will attach your database to the server:

42

Page 46: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

4.2 MS SQL Server Web Development

To implement the database in a website we first had to create a table to hold the

images of the products. The table ImageFiles was created to hold the binary data

which was uploaded using an ASP file supplied by Mansha Nawaz.

4.2.1 Connection between the database and website

The website development was undertaken by using Adobe Dreamweaver 9. To

use the data in the database a link has to be established between the two

programs. By following the instructions as laid out in the document at:

http://www.scm.tees.ac.uk/m.nawaz/HND_DD2/_sql2005/10.sql2005linktoMacro

mediaDreamweaver.doc it was possible to connect to the server and utilise the

data therein. The following screen shot shows the database linked in with

Dreamweaver.:

43

Page 47: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

4.2.2 Website design

The design of the website was not paramount in this work. It is only necessary for

the link to be shown working. With that in mind, the front page looked like this:

44

Page 48: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

By clicking on the “Click on listings” tag underneath the main picture groupings

the user is taken to a further page (the example below is for the PS2 category):

45

Page 49: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

This information displayed is taken from the Products table. There is a display

problem with the price – but this is just for demonstration purposes and is not the

finished article. Selecting one of the “Click for more details” takes the user to a

further page that displays the product image (taken from the ImageFiles table):

46

Page 50: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

47

5 Critical Review

5.1 Conclusion

The report has been a learning process for me – and one which I have enjoyed.

5.2 Critical Review of ICA Assessment

5.2.1 Report/Case Study/Critical Review

The report itself has been quite a task to produce. The sheer amount of

information that had to be included made the report longer (by more than double)

than I had expected. I should learn to stop getting “carried away” with examining

the problem in hand in too much depth.

Having said that, the guide supplied for the case study report has helped

compartmentalise the task at hand and allowed a structured report to be

produced.

5.2.2 SQL Implementation : ERD development

By using the ERD to develop my tables and ultimately the completed database, I

feel that result is quite comprehensive. I work better on a pictorial level – being

able to see the “bigger picture” allows me to focus on the overall result and

achieve the goals set out.

5.2.3 SQL Implementation : Tables and Views

The creation of the tables, by use of the ERD, made it so much easier to develop

the relationships within the database and therefore Primary and Foreign Keys. I

feel that there times when I had to step back and look at each relationship, but

that only served to reinforce the strength of the database.

5.2.4 SQL Implementation : Test Data

Inputting the data “by hand” allowed me to create some tests that would highlight

any faults with the model. The only problems that surfaced from the test data,

was that when I created the database I did not input the data until the

relationships were formed. This caused an error in data not being accepted. If I

had input the data when creating each individual table, I would have seen the

error when drawing the relationships – and saved some time as well.

Page 51: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

48

5.2.5 SQL : Additional and Advanced Features

The step-by-step guides to attaching and detaching the database were quite

valuable as I needed to complete the work on two different PCs. The

Dreamweaver guide was possibly the most important help I received, as this

showed me the power of using SQL, ASP and the whole .NET environment.

5.3 Critical Review of ICA

5.3.1 ICA Goals

I aimed to produce a piece of work that would be inline with the rest of those that I

have produced so far on the course – I believe that I have achieved that.

5.3.2 ICA Achievements

Of the tasks laid down in the ICA, I believe that I have succeeded in a majority of

them.

5.3.3 ICA Non-Achievements

I have failed by leaving the report to the last minute (spending too much time on

actually developing the database model).

5.3.4 ICA Evaluation

The report has forced me to learn a considerable amount about SQL server

software, data modelling and design of large scale systems. As I am always

ready for a challenge, I feel that this has certainly achieved its goal.

5.4 Critical Review of Product

5.4.1 Database Achievements

As a first attempt at database development, I think it is not a bad one. The

database fulfils all of the criteria laid down in the brief. It is a robust system that

could be fully operational with only a few minor changes.

5.4.2 Database Non-Achievements

The lack of a fully functional end-user interface (both via the internet and a direct

connection) is something which I could have completed – had I had more time.

Some of the field lengths could be looked at to trim the size of the database.

Page 52: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

49

5.4.3 Database Evaluation

It is a robust system that could be fully operational with only a few minor changes.

Page 53: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

50

6 References

6.1 Bibliography

Nawaz M. (2007) MS SQL Server 2005 PRACTICALS 1 (UoT)

Siedle A. (2006) Writing Formal Reports (UoT)

Watt A. (2006) Microsoft SQL Server 2005 For Dummies (Wiley)

6.2 Websites

DatabaseAnswers (2004)

http://www.databaseanswers.com/[Accessed October 2007]

Jupitermedia Corporation (2008)

http://www.databasejournal.com/[Accessed January 2008]

Her Majesty’s Customs and Revenue

http://www.hmcr.gov.uk/ [Accessed November 2007]

Microsoft Corp. (2007)

SQL Server Management Studio [Accessed October 2007 – January 2008]

Simple Talk Publishing (2007)

http://www.SQLServerCentral.com/[Accessed December 2007 – January 2008]

Page 54: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

51

7 Appendix

7.1 Hyperlinks to database files

EPOS.MDF and EPOS.LDF are the two files associated with this database

report.

7.2 All script files for section 3 and 4

7.2.1 SELECT and FROM

7.2.1.1

USE Retail SELECT * FROM Products

7.2.1.2

USE Retail SELECT product_id, product_name, product_sale_price FROM Products

7.2.1.3

USE Retail SELECT Products.product_id, Ref_Product_Types.product_type_description, Products.product_name, Products.product_sale_price FROM Products INNER JOIN Ref_Product_Types ON (Products.product_type_code = Ref_Product_Types.product_type_code)

7.2.2 WHERE

USE Retail SELECT Products.product_id, Ref_Product_Types.product_type_description, Products.product_name, Products.product_sale_price FROM Products INNER JOIN Ref_Product_Types ON (Products.product_type_code = Ref_Product_Types.product_type_code) WHERE product_sale_price <= 19.99

7.2.3 ORDER BY

USE Retail SELECT Products.product_id, Ref_Product_Types.product_type_description, Products.product_name, Products.product_sale_price FROM Products INNER JOIN Ref_Product_Types ON (Products.product_type_code = Ref_Product_Types.product_type_code) WHERE product_sale_price <= 19.99 ORDER BY product_name ASC

Page 55: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

52

7.2.4 DISTINCT

USE Retail SELECT DISTINCT Ref_Product_Types.product_type_description FROM Products INNER JOIN Ref_Product_Types ON (Products.product_type_code = Ref_Product_Types.product_type_code)

7.2.5 BETWEEN

USE Retail SELECT Products.product_id, Ref_Product_Types.product_type_description, Products.product_name, Products.product_sale_price FROM Products INNER JOIN Ref_Product_Types ON (Products.product_type_code = Ref_Product_Types.product_type_code) WHERE product_sale_price BETWEEN 4.50 AND 17.50 ORDER BY product_name ASC

7.2.6 LIKE

USE Retail SELECT Products.product_id, Ref_Product_Types.product_type_description, Products.product_name, Products.product_sale_price FROM Products INNER JOIN Ref_Product_Types ON (Products.product_type_code = Ref_Product_Types.product_type_code) WHERE product_name LIKE '%Tennis%' ORDER BY product_name ASC

7.2.7 IN

USE Retail SELECT Products.product_id, Ref_Product_Types.product_type_description, Products.product_name, Products.product_sale_price FROM Products INNER JOIN Ref_Product_Types ON (Products.product_type_code = Ref_Product_Types.product_type_code) WHERE product_sale_price IN (4.99,9.99);

7.2.8 NOT IN

USE Retail SELECT Products.product_id, Ref_Product_Types.product_type_description, Products.product_name, Products.product_sale_price FROM Products INNER JOIN Ref_Product_Types ON (Products.product_type_code = Ref_Product_Types.product_type_code) WHERE product_sale_price NOT IN (4.99,9.99);

Page 56: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

53

7.2.9 Aliases

USE Retail SELECT p2.product_name,p2.product_vat_rate_code FROM Products p1, Products p2 WHERE p1.product_name = 'Learning Ladder 3' AND p2.product_vat_rate_code <> p1.product_vat_rate_code;

7.2.10 Subqueries

USE Retail SELECT product_name FROM Products WHERE product_id IN (SELECT product_id FROM Basket_Items);

7.2.11 INSERT

INSERT INTO Discounts VALUES ('SPECL','10% off hardware','10');

7.2.12 UPDATE

UPDATE Discounts SET discount_description = '30% off all items', discount_amount = 30 WHERE discount_code = 'STORE';

7.3 Code for the Adobe Macromedia Dreamweaver link

7.3.1 Image upload code

<% @Page Language="C#" %> <% @Import Namespace="System.IO" %> <% @ Import Namespace="System.Data" %> <% @ Import Namespace="System.Data.SqlClient" %> <script runat="server"> public void UploadBtn_Click (Object sender, EventArgs e){ //Get the posted file Stream fileDataStream = MyFile.PostedFile.InputStream; //Get length of file int fileLength = MyFile.PostedFile.ContentLength; //Create a byte array with file length byte[] fileData = new byte[fileLength]; //Read the stream into the byte array fileDataStream.Read(fileData,0,fileLength); //get the filename string fileTitle = MyFileName.Value; //get the barcode string barcodeTitle = product_id.Value; //get the file type string fileType = MyFile.PostedFile.ContentType;

Page 57: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

54

SqlConnection connection = new SqlConnection("server=localhost; uid='sa'; pwd='f6932945'; Database='Retail'"); SqlCommand command = new SqlCommand ("INSERT INTO dbo.ImageFiles (product_id,MyFileName,MyFile,FileType)" + "VALUES (@product_id,@MyFileName,@MyFile,@FileType)", connection); SqlParameter paramTitle2 = new SqlParameter ("@product_id", SqlDbType.NChar,13); paramTitle2.Value = barcodeTitle; command.Parameters.Add(paramTitle2); SqlParameter paramTitle = new SqlParameter ("@MyFileName", SqlDbType.VarChar,35); paramTitle.Value = fileTitle; command.Parameters.Add(paramTitle); SqlParameter paramData = new SqlParameter ("@MyFile", SqlDbType.Image); paramData.Value = fileData; command.Parameters.Add(paramData); SqlParameter paramType = new SqlParameter ("@FileType", SqlDbType.VarChar,25); paramType.Value = fileType; command.Parameters.Add(paramType); //open the connection and execute the query connection.Open(); command.ExecuteNonQuery(); connection.Close(); //now do some cleanup Message.Text="Your file has uploaded"; MyFileName.Value = ""; } </script> <hr> <asp:label id="Message" Text="Select a file and filename" runat="server"/> <hr> <form method="post" enctype="multipart/form-data" runat="server"> <b>Barcode:</b><br> <input id="product_id" type="text" runat="server"> <P> <b>File Name:</b><br> <input id="MyFileName" type="text" runat="server"> <P> <b>File:</b><br> <input id="MyFile" type="file" runat="server"> <br><br> <input type=submit value="Upload!" OnServerclick="UploadBtn_Click" runat="server"> <br><br><br> </form>

7.3.2 Main page - sqlretailsite/Page1

<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="utf-8" %> <%@ Register TagPrefix="MM" Namespace="DreamweaverCtrls" Assembly="DreamweaverCtrls,version=1.0.0.0,publicKeyToken=836f606ede05d46a,culture=neutral" %> <MM:DataSet id="DataSet1" runat="Server"

Page 58: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

55

IsStoredProcedure="false" ConnectionString='<%# System.Configuration.ConfigurationSettings.AppSettings("MM_CONNECTION_STRING_sqlretailsite") %>' DatabaseType='<%# System.Configuration.ConfigurationSettings.AppSettings("MM_CONNECTION_DATABASETYPE_sqlretailsite") %>' CommandText='<%# "SELECT product_name FROM dbo.Products" %>' Debug="true" ></MM:DataSet> <MM:PageBind runat="server" PostBackBind="true" /> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Entertainment - Catalog</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="mm_entertainment.css" type="text/css" /> </head> <body bgcolor="#14285f"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr bgcolor="02021e"> <td width="400" colspan="2" rowspan="2" nowrap="nowrap"><img src="mm_entertainment_image.jpg" alt="Header image" width="400" height="140" border="0" /></td> <td width="360" height="58" nowrap="nowrap" id="logo" valign="bottom">Games Channel</td> <td width="100%">&nbsp;</td> </tr> <tr bgcolor="02021E"> <td height="57" nowrap="nowrap" id="tagline" valign="top">The software showcase</td> <td width="100%">&nbsp;</td> </tr> <tr> <td colspan="4" bgcolor="#cc3300"><img src="mm_spacer.gif" alt="" width="1" height="2" border="0" /></td> </tr> <tr> <td colspan="4"><img src="mm_spacer.gif" alt="" width="1" height="2" border="0" /></td> </tr> <tr> <td colspan="4" bgcolor="#cc3300"><img src="mm_spacer.gif" alt="" width="1" height="1" border="0" /></td> </tr> <tr> <td colspan="5" id="dateformat">&nbsp;<br /> &nbsp; &nbsp; <a href="javascript:;">home</a><br /> </td> </tr> <tr> <td width="50" valign="top">&nbsp;</td> <td colspan="2" valign="top"><br /> <table border="0" cellspacing="0" cellpadding="2" width="610"> <tr> <td colspan="7" class="subHeader">Product Listing</td> </tr> <tr> <td width="22%" height="110"><img src="pc.jpg" alt="PC" width="110" height="110" border="0" /></td> <td>&nbsp;</td> <td width="22%" height="110"><img src="ps2.jpg" alt="PS2" width="110" height="110" border="0" /></td> <td>&nbsp;</td> <td width="22%" height="110"><img src="xbox360.jpg" alt="XBOX 360" width="110" height="110" border="0" /></td> <td>&nbsp;</td>

Page 59: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

56

<td width="22%" height="110"><img src="wii.jpg" alt="Wii" width="110" height="110" border="0" /></td> </tr> <tr> <td class="detailText" valign="top" nowrap="nowrap"><a href="PCFULL.aspx">Click for listings</a><br /> </td> <td>&nbsp;</td> <td class="detailText" valign="top" nowrap="nowrap"><a href="PS2FULL.aspx">Click for listings</a><br /> </td> <td>&nbsp;</td> <td class="detailText" valign="top" nowrap="nowrap"><a href="javascript:;">Click for listings</a><br /> </td> <td>&nbsp;</td> <td class="detailText" valign="top" nowrap="nowrap"><a href="javascript:;">Click for listings</a><br /> </td> </tr> <tr> <td colspan="7">&nbsp;</td> </tr> </table> </td> <td>&nbsp;</td> </tr> <tr> <td width="50">&nbsp;</td> <td width="350">&nbsp;</td> <td width="360">&nbsp;</td> <td width="100%">&nbsp;</td> </tr> </table> <br /> <form runat="server"> </form> </body> </html>

7.3.3 PC listing page – PCFULL.aspx

<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="utf-8" %> <%@ Register TagPrefix="MM" Namespace="DreamweaverCtrls" Assembly="DreamweaverCtrls,version=1.0.0.0,publicKeyToken=836f606ede05d46a,culture=neutral" %> <MM:DataSet id="DataSet1" runat="Server" IsStoredProcedure="false" ConnectionString='<%# System.Configuration.ConfigurationSettings.AppSettings("MM_CONNECTION_STRING_sqlretailsite") %>' DatabaseType='<%# System.Configuration.ConfigurationSettings.AppSettings("MM_CONNECTION_DATABASETYPE_sqlretailsite") %>' CommandText='<%# "SELECT product_name FROM dbo.Products" %>' Debug="true" ></MM:DataSet> <MM:PageBind runat="server" PostBackBind="true" /> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Entertainment - Catalog</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="mm_entertainment.css" type="text/css" />

Page 60: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

57

</head> <body bgcolor="#14285f"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr bgcolor="02021e"> <td width="400" colspan="2" rowspan="2" nowrap="nowrap"><img src="mm_entertainment_image.jpg" alt="Header image" width="400" height="140" border="0" /></td> <td width="360" height="58" nowrap="nowrap" id="logo" valign="bottom">Games Channel</td> <td width="100%">&nbsp;</td> </tr> <tr bgcolor="02021E"> <td height="57" nowrap="nowrap" id="tagline" valign="top">The software showcase</td> <td width="100%">&nbsp;</td> </tr> <tr> <td colspan="4" bgcolor="#cc3300"><img src="mm_spacer.gif" alt="" width="1" height="2" border="0" /></td> </tr> <tr> <td colspan="4"><img src="mm_spacer.gif" alt="" width="1" height="2" border="0" /></td> </tr> <tr> <td colspan="4" bgcolor="#cc3300"><img src="mm_spacer.gif" alt="" width="1" height="1" border="0" /></td> </tr> <tr> <td colspan="5" id="dateformat">&nbsp;<br /> &nbsp; &nbsp; <a href="javascript:;">home</a><br /> </td> </tr> <tr> <td width="50" valign="top">&nbsp;</td> <td colspan="2" valign="top"><br /> <table border="0" cellspacing="0" cellpadding="2" width="610"> <tr> <td colspan="7" class="subHeader">Product Listing</td> </tr> <tr> <td width="22%" height="110"><img src="pc.jpg" alt="PC" width="110" height="110" border="0" /></td> <td>&nbsp;</td> <td width="22%" height="110"><img src="ps2.jpg" alt="PS2" width="110" height="110" border="0" /></td> <td>&nbsp;</td> <td width="22%" height="110"><img src="xbox360.jpg" alt="XBOX 360" width="110" height="110" border="0" /></td> <td>&nbsp;</td> <td width="22%" height="110"><img src="wii.jpg" alt="Wii" width="110" height="110" border="0" /></td> </tr> <tr> <td class="detailText" valign="top" nowrap="nowrap"><a href="PCFULL.aspx">Click for listings</a><br /> </td> <td>&nbsp;</td> <td class="detailText" valign="top" nowrap="nowrap"><a href="PS2FULL.aspx">Click for listings</a><br /> </td> <td>&nbsp;</td> <td class="detailText" valign="top" nowrap="nowrap"><a href="javascript:;">Click for listings</a><br /> </td> <td>&nbsp;</td> <td class="detailText" valign="top" nowrap="nowrap"><a href="javascript:;">Click for listings</a><br /> </td>

Page 61: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

58

</tr> <tr> <td colspan="7">&nbsp;</td> </tr> </table> </td> <td>&nbsp;</td> </tr> <tr> <td width="50">&nbsp;</td> <td width="350">&nbsp;</td> <td width="360">&nbsp;</td> <td width="100%">&nbsp;</td> </tr> </table> <br /> <form runat="server"> </form> </body> </html>

7.3.4 PS2 listing page – PS2FULL.aspx

<% @Page Language="C#" %> <% @Import Namespace="System.IO" %> <% @ Import Namespace="System.Data" %> <% @ Import Namespace="System.Data.SqlClient" %> <script runat="server"> private void Page_Load(Object sender, EventArgs e) { string sql="SELECT * FROM ImageFiles JOIN Products ON (ImageFiles.product_id = Products.product_id) WHERE Products.product_type_code = 'SP2F' "; SqlConnection connection = new SqlConnection("server=localhost; uid='sa'; pwd='f6932945'; Database='Retail'"); SqlCommand command = new SqlCommand(sql, connection); connection.Open(); FileList.DataSource = command.ExecuteReader(); FileList.DataBind(); connection.Close(); } </script> <form runat="server"> <asp:DataGrid id="FileList" runat="server" BorderColor="orange" BorderWidth="2" CellPadding="4" AutoGenerateColumns="false" ShowHeader="true" Align="center"> <HeaderStyle BorderColor="White" BackColor="black" ForeColor="White" Font-Bold="True" Font-Name="Arial" Font-Size="9" HorizontalAlign="Center"/> <Columns> <asp:TemplateColumn HeaderText="Item"> <ItemTemplate> <b> <font face="arial" size="4">

Page 62: Databases and SQL · Databases and SQL Case Study: Server Database Example Adam Harewood January 2008

59

<%# DataBinder.Eval(Container.DataItem, "product_name") %> </b> </font> </ItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn HeaderText="Price"> <ItemTemplate> <b> <font face="arial" size="4"> £ <%# DataBinder.Eval(Container.DataItem, "product_sale_price") %> </b> </font> </ItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn HeaderText=""> <ItemTemplate> <b> <font face="arial" size="4"> <a href="get_files.aspx?product_id=<%# DataBinder.Eval(Container.DataItem, "product_id") %>"> Click For more details</a> </b> </font> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> </form>

7.3.5 Displaying the images – get_files.aspx

<% @Page Language="C#" %> <% @Import Namespace="System.IO" %> <% @ Import Namespace="System.Data" %> <% @ Import Namespace="System.Data.SqlClient" %> <script runat="server"> private void Page_Load(Object sender, EventArgs e) { string sql="SELECT * FROM ImageFiles WHERE product_id = '" + Request.QueryString["product_id"] + "'"; SqlConnection connection = new SqlConnection("server=localhost; uid='sa'; pwd='f6932945'; Database='Retail'"); SqlCommand command = new SqlCommand(sql, connection); connection.Open(); SqlDataReader dr = command.ExecuteReader(); if(dr.Read()){ Response.Clear(); Response.AddHeader("Content-Type",dr["FileType"].ToString()); Response.BinaryWrite( (byte[]) dr["MyFile"] ); } dr.Close(); connection.Close(); } </script>