This document provides information about an AAZ Books database including:
- Tables for customers, books, authors, genres, publishers and other entities
- Stored procedures for common tasks like adding data, updating information, and retrieving data
- Table structures including attributes and data types for each table
- A user manual outlining the stored procedures and their parameters/purpose
Mediotype White Paper - Magento Enterprise Gift CardsMediotype .
Magento Enterprise offers an extensive suite of tools for creating gift cards and managing store credit for customers. Administrators can create accounts, gift card products, and offer credit to consumers to boost sales and keep customers returning.
2013_06_11 Union City DB Presentation Revision 04-For DistributionHoward Der
The Dumbarton Express bus service connects areas of Alameda, San Mateo, and Santa Clara counties via the Dumbarton Bridge. AC Transit administers the service and the Dumbarton Bridge Regional Operations Consortium provides oversight. Funding was previously split between consortium members but is now provided by $2.2 million in regional funds. The service operates on two routes with frequencies of every 30-45 minutes. Ridership has increased to nearly 1,200 daily passengers following service enhancements including increased frequency, extended hours and routes, and marketing initiatives.
El documento proporciona información sobre las características del guepardo. Señala que es el único felino que no puede trepar árboles y que posee una velocidad increíble, pudiendo alcanzar hasta 75 millas por hora. Además, cada guepardo tiene un patrón único de manchas que los identifica.
Internet es una red informática global que utiliza líneas telefónicas para transmitir información. Ofrece servicios como la World Wide Web para acceder a páginas, correo electrónico para enviar mensajes entre usuarios de una red, y chat para conversaciones en línea entre varias personas.
The document discusses the author's experience completing animation and design projects for their online course. They ran into issues with photo sizes and premium features when publishing their site. They were able to complete tasks like animating text, images, and shapes by using programs like GIMP and Giotto. However, they could not add some of the larger files to their site and had to provide them through an alternate file sharing method instead. Overall, the projects helped them learn new skills even if some elements did not publish as intended to their site.
Mediotype White Paper - Magento Enterprise Gift CardsMediotype .
Magento Enterprise offers an extensive suite of tools for creating gift cards and managing store credit for customers. Administrators can create accounts, gift card products, and offer credit to consumers to boost sales and keep customers returning.
2013_06_11 Union City DB Presentation Revision 04-For DistributionHoward Der
The Dumbarton Express bus service connects areas of Alameda, San Mateo, and Santa Clara counties via the Dumbarton Bridge. AC Transit administers the service and the Dumbarton Bridge Regional Operations Consortium provides oversight. Funding was previously split between consortium members but is now provided by $2.2 million in regional funds. The service operates on two routes with frequencies of every 30-45 minutes. Ridership has increased to nearly 1,200 daily passengers following service enhancements including increased frequency, extended hours and routes, and marketing initiatives.
El documento proporciona información sobre las características del guepardo. Señala que es el único felino que no puede trepar árboles y que posee una velocidad increíble, pudiendo alcanzar hasta 75 millas por hora. Además, cada guepardo tiene un patrón único de manchas que los identifica.
Internet es una red informática global que utiliza líneas telefónicas para transmitir información. Ofrece servicios como la World Wide Web para acceder a páginas, correo electrónico para enviar mensajes entre usuarios de una red, y chat para conversaciones en línea entre varias personas.
The document discusses the author's experience completing animation and design projects for their online course. They ran into issues with photo sizes and premium features when publishing their site. They were able to complete tasks like animating text, images, and shapes by using programs like GIMP and Giotto. However, they could not add some of the larger files to their site and had to provide them through an alternate file sharing method instead. Overall, the projects helped them learn new skills even if some elements did not publish as intended to their site.
Interatividade : Definições, estudos e tendênciasAlysson neves
O documento discute os conceitos de interatividade segundo diferentes autores, definindo-a como a relação entre veículos de comunicação e público e distinguindo dois tipos: a interatividade seletiva, em que o público escolhe os conteúdos, e a interatividade comunicativa, que permite a comunicação e expressão do público.
Online Communities: Revenue Drivers or Dead Zones?Influitive
New research from analyst firm Demand Metric finds that while a majority of organizations have communities, only a small fraction are satisfied with their results. In this webinar, chief analyst Jerry Rackley walks through some results from the research and shares his recommendations for ensuring online communities are revenue drivers instead of dead zones.
This document is a National Producer Agreement between Ryan Services Group (RSG) and an unnamed producer. It establishes the producer's authority to obtain specialty insurance products through RSG and its subsidiaries and affiliates (Providers). Key points:
- RSG markets insurance services on behalf of its subsidiaries and affiliates who offer specialized insurance products to independent agents.
- The agreement allows the producer to place business with any current or future RSG subsidiaries without needing separate agreements.
- It outlines representations and responsibilities of both parties regarding licenses, errors & omissions coverage, premium collection, and termination of the agreement.
- The producer retains ownership of expirations and records for any policies placed through the Providers
Colombia necesita mejorar la calidad de su educación. Actualmente invierte más en la guerra que en la educación y ofrece una educación de baja calidad que no permite a los estudiantes desarrollar habilidades básicas. Esto ha llevado a malos resultados en pruebas internacionales. Se necesitan reformas como mejorar los salarios de los docentes para atraer a los mejores profesores y asegurar que la evaluación de estudiantes sea formativa en lugar de punitiva.
The document outlines the City of Pittsburgh's policy for employee mutual commitment benefits, also known as domestic partnership benefits. It details the process for city employees and their partners to declare a mutual commitment, including filing paperwork and fees. Upon declaring a mutual commitment, the partner and dependents are entitled to enroll in benefits provided to other city employee families. It notes tax implications, and that terminating a mutual commitment requires notification to adjust benefits and taxation.
Do I Have to Pay My Employees for That? Common and Not-So Common Workplace Sc...ADP, LLC
http://bit.ly/1Ik8gBC
Key Takeaways:
-Ensure workers are properly classified
-Pay non-exempt employees for all hours worked
-Pay exempt employees a fixed salary each week
-Maintain records of all hours worked and pay calculations
-Ensure you have an accurate and reliable timekeeping process
- The document discusses how military experience is directly transferable to project management skills and there is a growing demand for project managers globally and in the US.
- It provides examples of skills that translate from military to project management such as leadership, budgeting, scheduling and conflict resolution.
- It recommends earning the PMP certification which is the most recognized credential for project managers and highlights resources to assist with the career transition.
The OAuth 2.0 Authorization Framework enables a third-party application to obtain limited access to an HTTP service on behalf of a resource owner. This specification replaces OAuth 1.0 and describes how a third-party application can obtain access to a protected resource by orchestrating an approval interaction between the resource owner and the HTTP service. It defines flows for authorization codes, implicit, resource owner password credentials, and client credentials grants and outlines protocols for access token issuance and refresh.
Este documento describe el propósito de la vida humana y el trabajo del hombre. Explica que el hombre trabaja para obtener alimentos que le permitan sobrevivir biológicamente y adquirir experiencias. También describe cómo el desarrollo de la agricultura y el calendario permitieron al hombre prever eventos climáticos y asegurar su subsistencia. Finalmente, señala que los cambios en la vida nómada a sedentaria modificaron la estructura familiar y social del hombre.
The document describes an E-SPACE web server project that maintains information about web servers, customers, URLs, products, sales, payments, and generates various reports. The project tracks server information, customer information, URL memory allocation, products, sales, payments, deliveries, renewals, and provides reports on customer information, products, date-wise, month-wise, year-wise and payment details. It is developed using a celeron processor, 4GB hard disk, 64MB RAM and runs on Windows with Apache Tomcat web server and SQL Server 2000 database. Front-end uses HTML and back-end uses JSP with JavaScript for client-side scripting.
This document describes an online organic vegetable and fruit delivery system. It outlines the existing manual system where customers must travel to markets to purchase produce. The new proposed system allows customers to order organic produce online and have it delivered to their doorstep for convenience. The document includes sections on system modules, entity relationship diagrams, data flow diagrams, and a data dictionary defining the tables and fields in the database.
This document describes a courier management system project developed in VB.NET 2010 and SQL Server 2008. There are five modules - booking, delivery, expenses, reports, and settings. The system aims to computerize the manual processes of a courier franchise to reduce errors and make work more efficient. Testing was performed on each module individually and after integration to ensure proper functionality. The project was successfully completed per requirements and will help users with an easy-to-use system to manage their courier operations.
This document outlines the project details for an online book store. It includes definitions, feasibility reports, key features, modules, data flow diagrams, entity relationship diagrams, and screen shots. The online book store will allow users to search for books, view details, add books to a wish list or cart, and make purchases online. It will also include administrative features to manage books, categories, authors, orders and user accounts.
This document describes a bookstore management system project that was developed over 3 months. It includes details on the project definition, system environment using HTML, CSS, Bootstrap, PHP and MySQL, and the spiral system development strategy. It provides information on the system design including data dictionary, data flow diagram, use case diagram, activity diagram, E-R diagram, and screenshots of the system. It also describes gray box testing and lists bibliographic references.
The proposed system is a web-based tour and travel management system that allows users to view tour package information, book tickets, make online payments, and generate reports. It provides an online registration system for customers with search capabilities. The system is divided into modules for administration, travelers, customers, and visitors. The administration module manages user accounts, tour packages, bookings, cancellations, and feedback. Customers can view packages, search, and book tours. Travelers can add packages and visitors can view information and provide feedback. The system aims to improve on manual processes and provide more options to customers through an online portal.
The proposed system is a web-based tour and travel management system that allows users to view tour package information, book tickets, make online payments, and generate reports. It provides an online registration system for customers with search capabilities. The system is divided into modules for administration, travelers, customers, and visitors. It allows easy access to travel information and arrangements through an online portal.
Order Management provides tools to manage sales orders and streamline the order fulfillment process from order entry to shipment. It includes functions like order promising, order capture, transportation management, and integration with EDI, XML, and web storefronts. This can help businesses reduce costs, improve order accuracy, and increase on-time delivery rates. Order and line information is stored in tables like OE_ORDER_HEADERS_ALL, OE_ORDER_LINES_ALL, and MTL_ONHAND_QUANTITIES to track items, pricing, statuses and fulfillment progress.
This document describes a library management system database project. It includes entity relationship diagrams and SQL code to define the database tables, insert sample data, and perform queries. The database tracks books, customers, branches, staff authentication, and book issue statuses. Views are created to display specific subsets of data for staff and customers.
Interatividade : Definições, estudos e tendênciasAlysson neves
O documento discute os conceitos de interatividade segundo diferentes autores, definindo-a como a relação entre veículos de comunicação e público e distinguindo dois tipos: a interatividade seletiva, em que o público escolhe os conteúdos, e a interatividade comunicativa, que permite a comunicação e expressão do público.
Online Communities: Revenue Drivers or Dead Zones?Influitive
New research from analyst firm Demand Metric finds that while a majority of organizations have communities, only a small fraction are satisfied with their results. In this webinar, chief analyst Jerry Rackley walks through some results from the research and shares his recommendations for ensuring online communities are revenue drivers instead of dead zones.
This document is a National Producer Agreement between Ryan Services Group (RSG) and an unnamed producer. It establishes the producer's authority to obtain specialty insurance products through RSG and its subsidiaries and affiliates (Providers). Key points:
- RSG markets insurance services on behalf of its subsidiaries and affiliates who offer specialized insurance products to independent agents.
- The agreement allows the producer to place business with any current or future RSG subsidiaries without needing separate agreements.
- It outlines representations and responsibilities of both parties regarding licenses, errors & omissions coverage, premium collection, and termination of the agreement.
- The producer retains ownership of expirations and records for any policies placed through the Providers
Colombia necesita mejorar la calidad de su educación. Actualmente invierte más en la guerra que en la educación y ofrece una educación de baja calidad que no permite a los estudiantes desarrollar habilidades básicas. Esto ha llevado a malos resultados en pruebas internacionales. Se necesitan reformas como mejorar los salarios de los docentes para atraer a los mejores profesores y asegurar que la evaluación de estudiantes sea formativa en lugar de punitiva.
The document outlines the City of Pittsburgh's policy for employee mutual commitment benefits, also known as domestic partnership benefits. It details the process for city employees and their partners to declare a mutual commitment, including filing paperwork and fees. Upon declaring a mutual commitment, the partner and dependents are entitled to enroll in benefits provided to other city employee families. It notes tax implications, and that terminating a mutual commitment requires notification to adjust benefits and taxation.
Do I Have to Pay My Employees for That? Common and Not-So Common Workplace Sc...ADP, LLC
http://bit.ly/1Ik8gBC
Key Takeaways:
-Ensure workers are properly classified
-Pay non-exempt employees for all hours worked
-Pay exempt employees a fixed salary each week
-Maintain records of all hours worked and pay calculations
-Ensure you have an accurate and reliable timekeeping process
- The document discusses how military experience is directly transferable to project management skills and there is a growing demand for project managers globally and in the US.
- It provides examples of skills that translate from military to project management such as leadership, budgeting, scheduling and conflict resolution.
- It recommends earning the PMP certification which is the most recognized credential for project managers and highlights resources to assist with the career transition.
The OAuth 2.0 Authorization Framework enables a third-party application to obtain limited access to an HTTP service on behalf of a resource owner. This specification replaces OAuth 1.0 and describes how a third-party application can obtain access to a protected resource by orchestrating an approval interaction between the resource owner and the HTTP service. It defines flows for authorization codes, implicit, resource owner password credentials, and client credentials grants and outlines protocols for access token issuance and refresh.
Este documento describe el propósito de la vida humana y el trabajo del hombre. Explica que el hombre trabaja para obtener alimentos que le permitan sobrevivir biológicamente y adquirir experiencias. También describe cómo el desarrollo de la agricultura y el calendario permitieron al hombre prever eventos climáticos y asegurar su subsistencia. Finalmente, señala que los cambios en la vida nómada a sedentaria modificaron la estructura familiar y social del hombre.
The document describes an E-SPACE web server project that maintains information about web servers, customers, URLs, products, sales, payments, and generates various reports. The project tracks server information, customer information, URL memory allocation, products, sales, payments, deliveries, renewals, and provides reports on customer information, products, date-wise, month-wise, year-wise and payment details. It is developed using a celeron processor, 4GB hard disk, 64MB RAM and runs on Windows with Apache Tomcat web server and SQL Server 2000 database. Front-end uses HTML and back-end uses JSP with JavaScript for client-side scripting.
This document describes an online organic vegetable and fruit delivery system. It outlines the existing manual system where customers must travel to markets to purchase produce. The new proposed system allows customers to order organic produce online and have it delivered to their doorstep for convenience. The document includes sections on system modules, entity relationship diagrams, data flow diagrams, and a data dictionary defining the tables and fields in the database.
This document describes a courier management system project developed in VB.NET 2010 and SQL Server 2008. There are five modules - booking, delivery, expenses, reports, and settings. The system aims to computerize the manual processes of a courier franchise to reduce errors and make work more efficient. Testing was performed on each module individually and after integration to ensure proper functionality. The project was successfully completed per requirements and will help users with an easy-to-use system to manage their courier operations.
This document outlines the project details for an online book store. It includes definitions, feasibility reports, key features, modules, data flow diagrams, entity relationship diagrams, and screen shots. The online book store will allow users to search for books, view details, add books to a wish list or cart, and make purchases online. It will also include administrative features to manage books, categories, authors, orders and user accounts.
This document describes a bookstore management system project that was developed over 3 months. It includes details on the project definition, system environment using HTML, CSS, Bootstrap, PHP and MySQL, and the spiral system development strategy. It provides information on the system design including data dictionary, data flow diagram, use case diagram, activity diagram, E-R diagram, and screenshots of the system. It also describes gray box testing and lists bibliographic references.
The proposed system is a web-based tour and travel management system that allows users to view tour package information, book tickets, make online payments, and generate reports. It provides an online registration system for customers with search capabilities. The system is divided into modules for administration, travelers, customers, and visitors. The administration module manages user accounts, tour packages, bookings, cancellations, and feedback. Customers can view packages, search, and book tours. Travelers can add packages and visitors can view information and provide feedback. The system aims to improve on manual processes and provide more options to customers through an online portal.
The proposed system is a web-based tour and travel management system that allows users to view tour package information, book tickets, make online payments, and generate reports. It provides an online registration system for customers with search capabilities. The system is divided into modules for administration, travelers, customers, and visitors. It allows easy access to travel information and arrangements through an online portal.
Order Management provides tools to manage sales orders and streamline the order fulfillment process from order entry to shipment. It includes functions like order promising, order capture, transportation management, and integration with EDI, XML, and web storefronts. This can help businesses reduce costs, improve order accuracy, and increase on-time delivery rates. Order and line information is stored in tables like OE_ORDER_HEADERS_ALL, OE_ORDER_LINES_ALL, and MTL_ONHAND_QUANTITIES to track items, pricing, statuses and fulfillment progress.
This document describes a library management system database project. It includes entity relationship diagrams and SQL code to define the database tables, insert sample data, and perform queries. The database tracks books, customers, branches, staff authentication, and book issue statuses. Views are created to display specific subsets of data for staff and customers.
The document provides an overview of the key tables involved in the procure to pay (P2P) cycle in Oracle Applications, including tables for requisitions, purchase orders, receipts, invoices, payments, and the transfer of transactions to the general ledger. It describes the purpose and structure of tables for requisition headers and lines, purchase order headers and lines, receipt headers and lines, invoice headers and lines, payment schedules, checks, and accounting entries.
SAP master data records like vendor master records and material master records are important for procurement processes. Vendor master records contain vendor details like addresses, payment terms, and contacts. Material master records are the main source of a company's material data used in areas like purchasing, inventory, and invoices. Both vendor and material master records can be created and changed at different organizational levels in SAP using transaction codes.
The document describes the process of converting a logical data model into a physical data model for a life insurance company database. It details changes made such as removing unnecessary tables, normalizing data, and defining entity types, attributes, and data types for the physical model tables. The relationships between tables in the physical model are also specified.
A relational database is a type of database that uses a structure that allows data to be queried and retrieved in a very efficient manner. The relational database model is based on the principles of relational algebra, a mathematical concept for managing data relationships.
Here are some key components and concepts associated with relational databases:
Tables (Relations): In a relational database, data is organized into tables. Each table consists of rows and columns, where each row represents a record, and each column represents a specific attribute or field of the record. Tables are also referred to as relations in the context of relational databases.
Fields (Attributes): Columns in a table are often called fields or attributes. Each field has a data type that defines the kind of data it can store (e.g., text, numbers, dates).
Records (Tuples): Rows in a table are known as records or tuples. Each record represents a unique instance of the entity that the table is modeling.
Keys:
Primary Key: A primary key is a unique identifier for a record in a table. It ensures that each record can be uniquely identified.
Foreign Key: A foreign key is a field in a table that refers to the primary key in another table. It establishes a link between the two tables, representing a relationship.
Relationships:
One-to-One: Each record in the first table is related to one and only one record in the second table.
One-to-Many (or Many-to-One): Each record in the first table can be related to multiple records in the second table, but each record in the second table is related to only one record in the first table.
Many-to-Many: Many records in the first table can be related to many records in the second table, and vice versa. This is typically implemented using an intermediate table.
Normalization: The process of organizing data in a database to reduce redundancy and dependency. Normalization involves dividing large tables into smaller, related tables and defining relationships between them.
SQL (Structured Query Language): SQL is a standard language for interacting with relational databases. It is used to define and manipulate the data, perform queries, and manage the database structure.
Popular relational database management systems (RDBMS) include:
MySQL: An open-source relational database.
PostgreSQL: An open-source object-relational database.
Oracle Database: A commercial database management system.
Microsoft SQL Server: A relational database management system developed by Microsoft.
Relational databases are widely used in various applications and industries due to their flexibility, efficiency, and ability to model complex relationships between data entities.
The document describes a bookstore management system project that will be developed over 3 months. It will allow users to view book details, add books to a cart, and place orders. The system will be developed using HTML, CSS, Bootstrap, PHP and MySQL. It will follow a spiral development strategy. The system design documentation includes data dictionaries, data flow diagrams, use case diagrams, entity-relationship diagrams, and screenshots of the proposed user interface. Testing will use a gray box testing approach.
This document provides a functional specification for generating a Payment Advice Note report in SAP. It details that the report is requested to be generated whenever a client makes a payment to a vendor, and should include payment summary details and vendor vs. customer clear adjustments. It outlines the input details and tables/fields required from various SAP tables including BSAK, BSAD, BSIK, BSID, PAYR, REGUH, WITH_ITEM, and LFA1. The report format is also specified as an attachment.
This document provides an overview of how inventory is tracked in QuickBooks POS, including:
1) Inventory quantities and costs are automatically updated in real-time as items are received and sold.
2) Items can be organized into departments and styles to more easily manage related merchandise.
3) Different POS document types like receipts and vouchers affect inventory in different ways.
4) Setting up items, departments, vendors and attributes allows generating useful reports to manage the business.
The document discusses customer master data in SAP. It explains that customer master data contains key information about customers like addresses, payment terms, and delivery methods. It also describes the different account groups (such as sold-to party, bill-to party) and partner functions used to classify customer master records based on the business relationship. Steps are provided on how to create a new customer master record including entering required fields in the general, company code, and sales area data sections.
The document describes several interfaces for importing data into different Oracle applications from interface tables, including purchase orders, suppliers, invoices, journals, budgets, employees, items, item categories, receipts, and requisitions. Each interface specifies validation rules for the data, relevant interface and base tables, and the import program used.
This document provides an overview of an online book store system project. It includes sections on the definition, project profile, feasibility report, key features, risk analysis, data flow diagram, entity relationship diagram, flow chart, data dictionary, screen shots, and modules. The modules covered include home, shopping cart, admin, user, help, and contact us. It also includes documentation on the tools and technologies used such as ASP.Net and SQL Server, as well as screen shots of the user interface.
3. Executive Summary
In our database we track Customers as they add books to a shopping cart
and purchase them and all the additional data required. In the books table we
track the name, ISBN, quantity, Copyright Date, Cost, Publisher and genre.
Customers are tracked by their CustomerID, Billing Address, Shipping Address,
Credit Card, First Name, Last Name, age, gender, Email, Home phone and work
phone. Whenever a customer would like to purchase a book they add it to their
shopping cart using their email. To actually purchase a book the customer finishes
the transaction and then the data from the purchase is added to purchases. In
addition to the other features of the data base a customer can change their email
address and their hash and salt and many others.
Our assumptions were that a customer can have only one billing address
and one shipping address because this will force them to have an accurate
address that will prevent them from having any reoccurring accidents. We
assumed a book can have more than one author and more than one genre, and
we also assumed that a customer can only have one credit card.
7. Overview of Tables
ADMINISTRATOR – A table that holds administrator information such as username and login
information. The password is stored as a hash and salt from the algorithm in the
code behind. Also tells what admins can add others and which ones cannot.
DISCOUNT – A table will have values that we can pull from in a stored procedure using a
DiscountID to put a discount on the total of a finished shopping cart.
CUSTOMER – A table that holds customer information such as username and login information.
The password is stored as a hash and salt from the algorithm in the code behind.
AUTHOR – A table that holds a surrogate key for an author and their name.
AUTHOR_INTERSECTION – Since a book can have many authors and an author can have many
books, for normalization purposes, we need an intersection table. This table links
authors and books together.
BILLING_ADDRESS - A table that will hold customer's billing address information. A customer
must have a billing address and can have multiple.
CUSTOMER_DATA - A table that will hold information about the customer.
SHIPPING_ADDRESS - A table that will hold the customer's shipping address. A customer must
have a shipping address and can have multiple.
BOOK_DATA - This table will hold all of our information about our books.
PURCHASES - This table will
PUBLISHER - This table will hold all information about the publishers. It holds the name and
address of the publishers.
PUBLISHER_CONTACTS - This table will hold the phone numbers and the names of the
publishers
CREDIT_CARD - This table will hold all credit card information for a user. The expiration date
must be greater than the current date.
SHOPPING_CART - This table will hold the items that the user will buy.
TRANSACTIONS - This is an intersection table for the SHOPPING_CART and BOOK_DATA tables.
GENRE_INTERSECTION – This is an intersection table to join BOOK_DATA and GENRE
GENRE – This is a table to store the different genre names
8. Table Data Dictionary
ADMINISTRATOR
Attribute Data Type Description
AdministratorID Integer (PK) Unique key for Administrator
Username Varchar(20) Login username for Administrator
Hash Varchar(45) Auto-Generated Value from password
Salt VarChar(45) Auto-Generated Value added to Hash
AdminAccess Bit 0 = Cannot add new admins 1 = Can add new admins
CUSTOMER
Attribute Data Type Description
CustomerID Integer (PK) Unique key for Customer
Hash Varchar(45) Auto-Generated Value from password
Salt VarChar(45) Auto-Generated Value added to Hash
BILLING_ADDRESS
Attribute Data Type Description
BillingAddressID Integer(PK) Unique key for Billing Address
Street Varchar(25) Customer Billing Address
Street2 Varchar(25) If customer has a PO Box
City Varchar(25) Customers city that they wish to be billed at.
Zip Varchar(6) Customers zip that they wish to be billed at
Region Varchar(25) Customers region that they wish to be billed at
Country Varchar(25) Customers country that they wish to be billed at
Discount
Attribute Data Type Description
DiscountID Integer(PK) Unique key for Discount
Name Varchar(25) Name of discount
DiscountPercent Numeric(2,2) The percentage that is be to discounted
AUTHOR_INTERSECTION
Attribute Data Type Description
AuthoerID Integer(PK) Unique key for Author Intersection
BookDataID Integer(PK) Unique key for Author Intersection
9. AUTHOR
Attribute Data Type Description
AuthorID Integer(PK) Unique key for Author
AuthorName Varchar(20) The name of the author
Customer_DATA
Attribute Data Type Description
CustomerDataID Integer(PK) Unique key for Customer Data
CustomerID Integer(FK) Foreign key from Customer
BillingAddressID Integer(FK) Foreign key from Billing Address
ShippingAddressID Integer(FK) Foreign key from Shipping Address
CreditCardID Integer(FK) Foreign key from Credit Card
FirstName Varchar(25) Customers First Name
LastName Varchar(25) Customers Last Name
Age Integer Customers age
Gender Char(1) Customers gender
Email Varchar(40) Customers Email
HomePhone Varchar(25) Customers Homephone
WorkPhone Varchar(25) Customers Workphone
CREDIT_CARD
Attribute Data Type Description
CreditCardID Integer(PK) Unique key for CREDIT_CARD
Name Varchar(25) Name of the credit card holder
ExpirationDate DateTime2 The month and year when the credit card expires
CreditCardNumber Numeric(16) 16-digit number on the credit card
CreditCardType Varchar(25) The type of credit card
SecurityCode Integer 3-digit code on the back of the credit card
SHOPPING_CART
Attribute Data Type Description
ShoppingCartID Integer(PK) Unique key for SHOPPING_CART
TransactionID Integer(FK) Unique key for TRANSACTIONS
CustomerDataID Integer(FK) Unique key for CUSTOMER_DATA
TransactionDateTime DateTime2 Time that the transaction took place
Total Money Total dollar amount of the transaction
10. TRANSACTIONS
Attribute Data Type Description
TransactionID Integer(PK) Unique key for TRANSACTIONS
ShoppingCartID Integer(FK) Unique key for SHOPPING_CART
BookDataID Integer(FK) Unique key for BOOK_DATA
GENRE_INTERSECTION
Attribute Data Type Description
GenreID Integer(PK) Unique key for GENRE
BookDataID Integer(PK) Unique key for BOOK_DATA
GENRE
Attribute Data Type Description
GenreID Integer(PK) Unique key for GENRE
GenreName VarChar(25) Name of the type of genre
Publisher
Attribute Data Type Description
PublisherID Integre(PK) Unique key for Publisher
PublisherName Varchar(30) The publishers name that they go by
Street Varchar(30) The publisher's street that they work at
City Varchar(30) The publisher's city that they work in
Region Varchar(25) The publisher's regioin that they work in
Country Varchar(25) The publisher's country that they work in
Zip Varchar(6) The publisher's zip that they work in
BOOK_DATA
Attribute Data Type Description
BookDataID Integer (PK) Unique key for Book Data
PurchaseID Integer(FK) Foreign key for Purchases
PublisherID Integer(FK) Foreign key for Publisher
Name Varchar(45) The name of the Book
ISBN Varchar(13) The ISBN for the book
Quantity Integer How many books are on stock
CopyrightDate Date The year that the book was written
Cost Numeric(5,2) The cost of the book
11. PURCHASES
Attribute Data Type Description
PurchaseID Integer(PK) Unique key for Purchases
PurchaseDateTime DateTime2 The time that the item was purchased
SellingPrice Money The selling price of the item or items
SHIPPING_ADDRESS
Attribute Data Type Description
ShippingAddressID Integer(PK) Unique key for Shipping Address
Street Varchar(25) Customer's address where they receive mail
Street2 Varchar(20) Customer's PO box
City Varchar(25) Customer's city that the shipping address is in
Zip Varchar(5) Customer's zip that the shipping address is in
Region Varchar(25) Customer's region that the shipping address is in
Country Varchar(25) Customer's country that the shipping address is in
PUBLISHER_CONTACTS
Attribute Data Type Description
ConatctID Integer Unique key for Publisher_Contacts
PublisherID Integer Foreign key for Publisher
ContactName VARCHAR(20) The name of the person from the publishing company
Phone Numeric(11) The phone number to contact the publisher
12. User Manual
Overview of Stored Procedures
uspAddCustomer
Accepts: Hash, Salt, StreetBa, Street2Ba, CityBa, ZipBa, RegionBa, CountryBa, Name,
ExpirationDate, CreditCardNumber, CreditCardType, SecurityCode, StreetSa, Street2Sa, CitySa,
ZipSa, RegionSa, CountrySa, FirstName, LastName, Age, Gender, Email, Homephone, WorkPhone
Description: This procedure adds a new customer with their shipping address, billing address,
and credit card
uspAddAministrator
Accepts: CurrentAdministrator, CurrentSalt, Username, Hash, Salt, AdminAccess
Description: This procedure allows a current administrator to add a new administrator. First, it
checks if the current administrator has permission to add a new administrator, then it checks if
the current administrator user name is exists. If the administrator does have permission and the
administrator's user name exists, then it add the new administrator's user name, hash, salt, and
admin access. Otherwise it will print an error message.
uspAddAuthor
Accepts: AuthorName, CurrentAdministrator, CurrentSalt
Description This procedure allows an administrator to add a new author,
uspAddAuthorToBook
Accepts: AuthorName, ISBN, CurrentAdministrator, CurrentSalt
Description This procedure allow an administrator to link an author to a book.
uspAddBookData
Accepts: CurrentAdministrator, CurrentSalt, Name, ISBN, Quantity, CopyrightDate, Cost,
PublisherName
Description: This procedure allows a current administrator to insert a new book into the
book_data table given the administrator’s name, and salt, and the book’s title, ISBN number,
quantity, copyright date, cost, and the publisher’s name.
uspAddBookToShoppingCart
Accepts: ISBN, Email
Description: This procedure allows link a shopping cart to a book.
13. uspAddGenre
Accepts: GenreName
Description: This procedure allows a user to insert a type of genre
uspAddGenreToBook
Accepts: GenreName, ISBN, CurrentAdministrator, CurrentSalt
Description: This procedure allows a user to link a book to a type of genre.
uspAddPublisher
Accepts: PubName, PubStreet, PubCity, PubRegion, PubCountry, PubZip
Description: This procedure allows a user to create a new publisher contact with all of their
contact information.
uspAddPublisherContact
Accepts: CurrentAdministrator, CurrentSalt, PublisherName, ContactName, Phone
Description: This procedure allows an administrator to create another publisher contact from
the same publishing company.
uspFinishTransaction
Accepts: Email
Description: This procedure allows a user to checkout and saves what they selected to purchase.
This also checks if the customer is eligible for a discount.
uspGetAuthorID
Accepts: Author
Description: This procedure returns an authorID given the author’s name.
uspGetBookID
Accepts: ISBN
Description: This procedure returns the bookDataID given an ISBN.
uspGetCustomerDataID
Accepts: Email
Description Accepts the customer’s Email and returns the CustomerID for that customer.
uspGetCustomerID
Accepts: Email, CurrentSalt
Description Same as uspGetCustomerDataID, but it requires the customer’s salt.
14. uspGetGenreID
Accepts: GenreName
Description: This procedure returns the genreID given a genre name.
uspGetPublisherID
Accepts: PublisherName
Description: This procedure returns the publisherID given the publisher’s name.
uspGetShoppingCartID
Accepts: Email
Description: This procedure returns the shoppingCartID given the customer’s email address.
uspRemoveBookFromShoppingCart
Accepts: Email, ISBN
Description: This procedure.
uspShowPopularBooksByUnitSold
Accepts:
Description: This procedure displays the most popular books by the number of them that has
been sold.
uspShowPopularBooksByVolume
Accepts:
Description: This procedure displays the most popular books by the total dollar amount of them
that has been sold.
uspTotalRevenueTimeFrame
Accepts: BeginDate, EndDate
Description: This procedure allows a user to view the revenue of a specific time frame given a
beginning and end date.
uspUpdateAdminAccess
Accepts: CurrentAdministrator, CurrentSalt, UserStatusChange, ChangeAccess
Description: This procedure allows a current administrator to update and change an
administrator’s access level.
15. uspUpdateAdminHashSalt
Accepts: CurrentAdministrator, CurrentSalt, NewSalt, NewHash
Description: This procedure allows a current administrator to update his or her salt and hash
given their current administrator name and their current salt.
uspUpdateBillingAddress
Accepts: CurrentAdministrator, CurrentSalt, Email, Street1, Street2, City, Zip, Region/State,
Country
Description: This procedure allows an administrator to update the customer’s billing address
given the administrator’s username and salt, and the customer’s email address.
uspUpdateBookInformation
Accepts: CurrentAdministrator, currentSalt, ISBN, Name, NewISBN, Quantity, CopyrightDate,
Cost
Description: This procedure allows an administrator to update a book’s general information
given the administrator’s username and salt, and the book’s ISBN.
uspUpdateCustomerEmail
Accepts: CurrentAdministrator, AdminSalt, CurrentSalt, Email, NewEmail
Description: This procedure allows a current administrator to update and change a customer’s
email address given the current administrator’s name, the administrator’s salt, the customer’s
salt, and the customer’s new email address and old email address.
uspUpdateCustomerHashSalt
Accepts: CurrentAdministrator, CurrentSalt, Email, NewCustomerSalt, NewCustomerHash
Description: This procedure allows a current administrator to update and change a customer’s
hash and salt given the current administrator’s name, salt, the customer’s email, and the
customer’s new salt and hash.
uspUpdateCustomerInformation
Accepts: CurrentAdministrator, CurrentSalt, Email, FirstName, LastName, Age, Gender,
NewEmail, HomePhone, and WorkPhone
Description: This procedure allows an administrator to update the customer’s general I
nformation give the current administrator’s name and salt, and the customer’s current email.
16. uspUpdateShippingAddress
Accepts: CurrentAdministrator, CurrentSalt, Email, Street1, Street2, City, Zip, Region/State,
Country
Description: This procedure allows an administrator to update a customer’s shipping address
given the administrator’s username and salt, and the customer’s email address.
uspVerifyAdministrator
Accepts: CurrentAdministrator, CurrentSalt
Description: This procedure checks that the current administrator exists in the administrator
table. If the administrator exists in the table then it returns 1, otherwise it will print
'Administrator username or salt is incorrect' and return 0.
UspVerifyPublisher
Accepts: PublisherName
Description: This procedure allows a user to verify that a given publisher name exists with the
publisher table.
17. Execution Manual
Because database’s require certain information before it can have other information
there is a certain way the stored procedures have to be executed. We take an outside inside
approach when we execute them meaning that data that has no prerequisites gets executed
first.
First we will execute uspAddAministrator, that way we have an administrator to be able
to create other things. Next we can execute, uspAddAuthor, uspAddBookData, uspAdd
Customer, uspAddGenre, and uspAddPublisher. Next we can execute uspAddAuthorToBook,
uspAddGenreToBook, and uspAddPublisherContact. After that we are able to execute
uspAddBookToShoppingCart. Finally we are able to execute FinishTransaction.
Once those are all executed any stored procedure is able to be executed at any time.
18. Overview of Views
TotalInventoryByGenre
Description: Allows the user to view the total amount of books in each genre.
AvgTrans
Description: Allows the user to view the average transaction price from all of the transactions.
ValueInventoryByPublisher
Description: Allows the user to see the value of the total inventory of each publisher.
PublisherRevenuePerDay
Description: Allows the user to see the revenue made by the different publishers on a particular
day.
19. View Code
TotalInventoryByGenre
CREATE VIEW TotalInventoryByGenre AS
--sum and group by
SELECT g.GenreName, SUM (bd.Quantity) AS 'Total Inventory'
FROM BOOK_DATA bd
JOIN GENRE_INTERSECTION gi
ON bd.BookDataID = gi.BookDataID
JOIN GENRE g ON gi.GenreID = g.GenreID
WHERE bd.BookDataID = gi.BookDataID
AND gi.GenreID = g.GenreID
GROUP BY GenreName
AvgTrans
CREATE VIEW AvgTrans as
SELECT CONCAT ('$',AVG(SellingPrice)) AS 'Average Transaction Amount'
FROM PURCHASES
ValueInventoryByPublisher
CREATE VIEW ValueInventoryByPublisher AS
SELECT CONCAT('$', SUM(COST * Quantity)) AS 'Value of Inventory', PublisherName AS
'Publisher Name'
FROM BOOK_DATA bd
JOIN Publisher p on p.PublisherID = bd.PublisherID
GROUP BY PublisherName
PublisherRevenuePerDay
CREATE VIEW PublisherRevenuePerDay AS
SELECT PublisherName as 'Publisher', sum(SellingPrice) as 'Revenue',
CONVERT(date,PurchaseDateTime,10) as 'Date'
FROM PUBLISHER
JOIN BOOK_DATA AS BK ON PUBLISHER.PublisherID = BK.PublisherID
JOIN PURCHASES AS PK ON BK.BookDataID = PK.BookDataID
GROUP BY PublisherName, CONVERT(date,PurchaseDateTime,10);
20. Trigger
ustPrintAdmistratorCreated
Occurs: After Insert
Description: Prints out that an administrator was created after an administrator has been
inserted.’
Code
CREATE TRIGGER ustPrintAdministratorCreated ON dbo.ADMINISTRATOR
AFTER INSERT
AS
BEGIN
PRINT '******************************'
PRINT 'Administrator has been created'
PRINT '******************************'
END;
21. Stored Procedure Code
/* Adds a Administrator to database*/
CREATE PROCEDURE uspAddAdministrator
(
@CurrentAdministrator VARCHAR(20),
@CurrentSalt VARCHAR(45),
@Username VARCHAR(20),
@Hash VARCHAR(45),
@Salt VARCHAR(45),
@AdminAccess BIT
)
AS
BEGIN
DECLARE @RowCount INT
DECLARE @AdminRowCount INT
/*Check if current administrator can add a admin*/
SELECT @AdminRowCount = COUNT(*)
FROM ADMINISTRATOR
WHERE Username = @CurrentAdministrator
AND Salt = @CurrentSalt
AND AdminAccess = 1
/*Check if username already exist*/
SELECT @RowCount = COUNT(*)
FROM dbo.ADMINISTRATOR
WHERE Username = @Username
IF @AdminRowCount = 1
IF @RowCount = 0
INSERT INTO ADMINISTRATOR(Username, [Hash], Salt, AdminAccess)
VALUES (@Username, @Hash, @Salt, @AdminAccess)
ELSE
PRINT 'UserName Already Exists'
ELSE
PRINT 'Current Administrator Invalid'
END
22. CREATE PROCEDURE uspAddAuthor (
@AuthorName VARCHAR(20),
@CurrentAdministrator VARCHAR(20),
@CurrentSalt VARCHAR(45)
)
AS
BEGIN
DECLARE @RowCount INT
DECLARE @Admin BIT
/*Verify the admin*/
EXEC @Admin = uspVerifyAdministrator @CurrentAdministrator, @CurrentSalt
IF @Admin <> 1
PRINT 'Author not inserted'
ELSE
BEGIN
/*See if the author name exists already*/
SELECT @RowCount = COUNT(*)
FROM Author
WHERE AuthorName = @AuthorName
IF @RowCount = 0
INSERT INTO AUTHOR (AuthorName) VALUES (@AuthorName)
ELSE
PRINT 'AuthorName Already Exists'
END
END
23. CREATE PROCEDURE uspAddAuthorToBook (
@AuthorName VARCHAR(20),
@ISBN VARCHAR(13),
@CurrentAdministrator VARCHAR(20),
@CurrentSalt VARCHAR(45)
)
AS
BEGIN
DECLARE @RowCount INT
DECLARE @Admin BIT
DECLARE @GAuthorID INT
DECLARE @GBookID INT
/*Verify the admin*/
EXEC @Admin = uspVerifyAdministrator @CurrentAdministrator, @CurrentSalt
IF @Admin <> 1
PRINT 'Author not connected with book'
ELSE
BEGIN
/*See if the author is already connected*/
EXEC @GAuthorID = uspGetAuthorID @AuthorName
EXEC @GBookID = uspGetBookID @ISBN
SELECT @RowCount = COUNT(*)
FROM AUTHOR_INTERSECTION
WHERE AuthorID = @GAuthorID
AND BookDataID = @GBookID
IF @RowCount = 0
INSERT INTO AUTHOR_INTERSECTION (AuthorID, BookDataID) VALUES
(@GAuthorID, @GBookID)
ELSE
PRINT 'Connection already exists'
END
END
24. CREATE PROCEDURE uspAddBookData
@CurrentAdministrator VARCHAR(20),
@CurrentSalt VARCHAR(45),
@Name VARCHAR(45),
@ISBN VARCHAR(13),
@Quantity INT,
@CopyrightDate DATE,
@Cost NUMERIC(5,2),
@PublisherName VARCHAR(30)
AS
BEGIN
DECLARE @Admin BIT
DECLARE @PublisherID INT
DECLARE @Publisher BIT
/*Verify the Admin*/
EXEC @Admin = uspVerifyAdministrator @CurrentAdministrator, @CurrentSalt
IF @Admin <> 1
PRINT 'User does not have permission to edit'
ELSE
BEGIN
EXEC @Publisher = uspVerifyPublisher @PublisherName
IF @Publisher <> 1
PRINT 'Publisher Name is not valid'
ELSE
BEGIN
EXEC @PublisherID = uspGetPublisherID @PublisherName
INSERT INTO BOOK_DATA
(
Name,
ISBN,
Quantity,
CopyrightDate,
Cost,
PublisherID
)
VALUES
(
@Name,
@ISBN,
@Quantity,
@CopyrightDate,
@Cost,
@PublisherID
)
END
END
END;
25. CREATE PROCEDURE uspAddBookToShoppingCart
(
@ISBN VARCHAR(13),
@Email VARCHAR(40)
)
AS
BEGIN
Declare @previousTotal MONEY
Declare @rowCount INT
Declare @rowCountEmail INT
Declare @ShoppingCartID INT
Declare @BookDataID INT
Declare @NewTotal MONEY
Declare @Cost NUMERIC(5,2)
Declare @FinalTotal MONEY
Declare @CustomerDataID INT
SELECT @rowCountEmail = COUNT (*)
FROM CUSTOMER_DATA
WHERE Email = @Email
IF @rowCountEmail IS NULL
PRINT 'The email does not exist'
ELSE
BEGIN
SELECT @CustomerDataID = CustomerDataID
FROM CUSTOMER_DATA
WHERE Email = @Email
/*See if customer has a shopping cart w/o date*/
/*select ShoppingCart where customerID = @CustomerID*/
SELECT @rowCount = COUNT(*)
FROM SHOPPING_CART AS SC
WHERE SC.CustomerDataID = @CustomerDataID
AND SC.TransactionDateTime IS NULL;
/*if tdt == null add one to hasShoppingCartDate*/
IF @rowCount = 1 BEGIN
/*if so*/
/*Insert into transaction table ShoppingCartID and BookDateID*/
SELECT @ShoppingCartID = ShoppingCartID
FROM SHOPPING_CART AS SC1
WHERE SC1.CustomerDataID = @CustomerDataID
AND SC1.TransactionDateTime IS NULL;
--get the book data ID
SELECT @BookDataID = BookDataID
FROM BOOK_DATA
WHERE ISBN = @ISBN
26. INSERT INTO TRANSACTIONS(ShoppingCartID,BookDataID)
VALUES(@ShoppingCartID, @BookDataID)
/*Update total*/
/*Grab book cost and and to total*/
SELECT @previousTotal= Total
FROM SHOPPING_CART
WHERE ShoppingCartID = @ShoppingCartID
--get cost of the book
SELECT @COST = COST
FROM BOOK_DATA
WHERE BookDataID = @BookDataID
Select @FinalTotal = @previousTotal + @Cost
/*Update the quantity of the bookdata*/
UPDATE SHOPPING_CART
SET Total = @FinalTotal
WHERE ShoppingCartID = @ShoppingCartID
AND TransactionDateTime IS NULL;
END
/*if tdt != null add zero to hasShoppingCartDate*/
ELSE
BEGIN
/*if not*/
/*use @@IDENTITY TO GET id FROM SHOPPING CART*/
INSERT INTO SHOPPING_CART (CustomerDataID)
VALUES (@CustomerDataID)
SELECT @ShoppingCartID = @@IDENTITY
--get the book data ID
SELECT @BookDataID = BookDataID
FROM BOOK_DATA
WHERE ISBN = @ISBN
INSERT INTO TRANSACTIONS(ShoppingCartID,BookDataID)
VALUES(@ShoppingCartID, @BookDataID)
--get cost of the book
SELECT @COST = COST
FROM BOOK_DATA
WHERE BookDataID = @BookDataID
UPDATE SHOPPING_CART
SET Total = @Cost
WHERE ShoppingCartID = @ShoppingCartID
END
END
END
27. CREATE PROCEDURE uspAddGenre (
@GenreName VARCHAR(25)
)
AS
BEGIN
DECLARE @RowCount INT
SELECT @RowCount = COUNT(*)
FROM GENRE
WHERE GenreName = @GenreName
IF @RowCount = 0
INSERT INTO GENRE (GenreName) VALUES (@GenreName)
ELSE
PRINT 'GenreName Already Exists'
END
28. CREATE PROCEDURE uspAddGenreToBook
(
@GenreName VARCHAR(30),
@ISBN VARCHAR(13),
@CurrentAdministrator VARCHAR(20),
@CurrentSalt VARCHAR(45)
)
AS
BEGIN
DECLARE @RowCount INT
DECLARE @Admin BIT
DECLARE @GgenreID INT
DECLARE @GBookID INT
/*Verify the Admin*/
Exec @Admin = uspVerifyAdminister (@CurrentAdministrator, @CurrentSalt)
IF @ADMIN <> 1
PRINT 'Genre not connected with book'
ELSE
BEGIN
/*See if the Genre is already connected*/
EXEC @GgenreID = uspGetGenreID @GgenreName
EXEC @GBookID = uspGetBookID @ISBN
SELECT @RowCount = Count(*)
FROM GENRE_INTERSECTION
WHERE GenreID = @GenreID
AND BookDataID = @GBookID
IF @RowCount = 0
INSERT INTO GENRE_INTERSECTION (GenreID, BookDataID)
VALUES (@GgenreID, @GBookID)
ELSE
PRINT 'Connection already exists'
END
END;
29. CREATE PROCEDURE uspAddPublisher
@PubName VARCHAR(30),
@PubStreet VARCHAR(30),
@PubCity VARCHAR(30),
@PubRegion VARCHAR(30),
@PubCountry VARCHAR(30),
@PubZip VARCHAR(6)
AS
BEGIN
DECLARE @RowCount INT
SELECT @RowCount = COUNT(*)
FROM PUBLISHER
WHERE PublisherName = @PubName
IF @RowCount > 0
PRINT 'The publisher already exists in the database'
ELSE
INSERT INTO PUBLISHER
(
PublisherName,
Street,
City,
Region,
Country,
Zip
)
VALUES
(
@PubName,
@PubStreet,
@PubCity,
@PubRegion,
@PubCountry,
@PubZip
)
END;
30. CREATE PROCEDURE uspAddPublisherContact
@CurrentAdministrator VARCHAR(20),
@CurrentSalt VARCHAR(45),
@PublisherName VARCHAR(30),
@ContactName VARCHAR(20),
@Phone NUMERIC(11)
AS
BEGIN
DECLARE @PublisherID INT
DECLARE @Admin BIT
DECLARE @Publisher BIT
/*Verify the Admin*/
EXEC @Admin = uspVerifyAdministrator @CurrentAdministrator, @CurrentSalt
IF @Admin <> 1
PRINT 'User does not have permission to edit'
ELSE
BEGIN
/*Verify the publisher name*/
EXEC @Publisher = uspVerifyPublisher @PublisherName
IF @Publisher <> 1
PRINT 'Publisher name is not valid'
ElSE
BEGIN
/*Get the publisherID*/
EXEC @PublisherID = uspGetPublisherID @PublisherName
INSERT INTO PUBLISHER_CONTACTS
(
PublisherID,
ContactName,
Phone
)
VALUES
(
@PublisherID,
@ContactName,
@Phone
)
END
END
END;
31. CREATE PROCEDURE uspFinishTransaction
/*get stuff*/
@Email VARCHAR(40)
AS
BEGIN
/*create table to store shopping cart books*/
-- DECLARE @MyArray table(ShoppingCartID INT, TransactionDateTime DATETIME2, Total
MONEY)
DECLARE @ShoppingCartID INT
DECLARE @TransactionDateTime DATETIME2
DECLARE @Total MONEY
DECLARE @BookDataID INT
DECLARE @Counter INT
DECLARE @DiscountPercent NUMERIC(2,2)
DECLARE @CustomerDataID INT
DECLARE @TransactionID INT
DECLARE @PreviousTransactionID INT
DECLARE @Cost NUMERIC (5,2)
DECLARE @Quantity INT
--get the customer data ID
EXEC @CustomerDataID = uspGetCustomerDataID @Email
--get the shopping Cart ID
SELECT @ShoppingCartID = ShoppingCartID
FROM SHOPPING_CART
WHERE CustomerDataID = @CustomerDataID
AND TransactionDateTime IS NULL
SET @Counter = 0
--count the rows that have the same customerDataID's
-- count the books in the shopping cart
DECLARE @RowCount INT
SELECT @RowCount = COUNT(*)
FROM TRANSACTIONS
WHERE ShoppingCartID = @ShoppingCartID
SET @TransactionDateTime = CURRENT_TIMESTAMP
-- get the last transactionID of that customer where transactionDateTime is not
null
/*
SELECT TOP 1 @PreviousTransactionID = TransactionID
FROM TRANSACTIONS
JOIN SHOPPING_CART
ON SHOPPING_CART.ShoppingCartID = TRANSACTIONS.ShoppingCartID
WHERE TRANSACTIONS.ShoppingCartID = @ShoppingCartID
AND SHOPPING_CART.TransactionDateTime IS NOT NULL
ORDER BY TransactionID ASC
*/
SET @PreviousTransactionID = 0
/*fill table*/
WHILE @Counter < @RowCount
32. BEGIN
SELECT TOP 1 @TransactionID = TransactionID
FROM TRANSACTIONS
WHERE ShoppingCartID = @ShoppingCartID
AND TransactionID > @PreviousTransactionID
ORDER BY TransactionID ASC
SELECT @BookDataID = BookDataID
FROM TRANSACTIONS
WHERE TransactionID = @TransactionID
-- get the price of the book
SELECT @Cost = Cost
FROM BOOK_DATA
WHERE BookDataID = @BookDataID
-- insert purchaseDateTime, sellingPrince(of book), and BookDataID into
purchases
INSERT INTO PURCHASES (PurchaseDateTime, SellingPrice, BookDataID)
VALUES (@TransactionDateTime, @Cost, @BookDataID)
SET @PreviousTransactionID = @TransactionID
--decrement quantity of book by 1
SELECT @Quantity = Quantity
FROM BOOK_DATA
WHERE BookDataID = @BookDataID
UPDATE BOOK_DATA
SET Quantity = @Quantity - 1
WHERE BookDataID = @BookDataID
-- increment the counter
SET @Counter = @Counter + 1
END
-- get the Total from ShoppingCart
SELECT @Total = Total
FROM SHOPPING_CART
WHERE ShoppingCartID = @ShoppingCartID
/*check if they are eligible for a discount*/
IF @Total > 75
BEGIN
SELECT @DiscountPercent = DiscountPercent
FROM DISCOUNT
WHERE DiscountID = 1
IF @DiscountPercent = NULL
PRINT 'No discount available'
ELSE
SET @Total = @Total * (1 - @DiscountPercent)
END
UPDATE SHOPPING_CART
SET TransactionDateTime = @TransactionDateTime,
34. CREATE PROCEDURE uspGetAuthorID (
@Author VARCHAR(20)
)
AS
BEGIN
DECLARE @AuthorID INT
SELECT @AuthorID = AuthorID
FROM AUTHOR
WHERE AuthorName = @Author
IF @AuthorID = NULL
BEGIN
PRINT 'Author does not exist'
RETURN 0
END
ELSE
RETURN @AuthorID
END;
35. CREATE PROCEDURE uspGetBookID (
@ISBN VARCHAR(13)
)
AS
BEGIN
DECLARE @BookID INT
SELECT @BookID = BookDataID
FROM BOOK_DATA
WHERE ISBN = @ISBN
IF @BookID = NULL
PRINT 'ISBN does not exist'
ELSE
RETURN @BookID
END;
36. CREATE PROCEDURE uspGetCustomerDataID
@Email VARCHAR(200)
AS
BEGIN
DECLARE @CustomerDataID INT
--get the customerDataID
SELECT @CustomerDataID = CustomerDataID
FROM CUSTOMER_DATA
WHERE Email = @Email
-- if the email was not found
IF @CustomerDataID = NULL
PRINT 'Invalid Email'
ELSE
RETURN @CustomerDataID
END;
37. Create PROCEDURE uspGetCustomerID
@Email VARCHAR(200),
@CurrentSalt VARCHAR(45)
AS
BEGIN
/*Check if email exists*/
DECLARE @CustomerID INT
DECLARE @RowCount INT
SELECT @CustomerID = CustomerID
FROM CUSTOMER_DATA
WHERE Email = @Email
/*if email does not exist*/
IF @CustomerID = NULL
PRINT 'The email does not exist'
ELSE
BEGIN
/*Check that the customer salt matches with the customerID*/
SELECT @RowCount = COUNT(*)
FROM CUSTOMER
JOIN CUSTOMER_DATA
ON CUSTOMER.CustomerID = CUSTOMER_DATA.CustomerID
WHERE @CustomerID = CUSTOMER.CustomerID
AND @CurrentSalt = Salt
If @RowCount <> 1
PRINT 'Input invalid customer salt'
ELSE
RETURN @CustomerID
END
END;
38. CREATE PROCEDURE uspGetGenreID (
@GenreName VARCHAR(30)
)
AS
BEGIN
/*Check if the genre exists*/
DECLARE @GenreID INT
SELECT @GenreID = GenreID
FROM GENRE
WHERE GenreName = @GenreName
/*Return the genreid if the name exists*/
IF @GenreID = NULL
PRINT 'Name does not exist'
ELSE
RETURN @GenreID
END;
39. CREATE PROCEDURE uspGetPublisherID (
@PublisherName VARCHAR(30)
)
AS
BEGIN
DECLARE @PublisherID INT
SELECT @PublisherID = PublisherID
FROM PUBLISHER
WHERE PublisherName = @PublisherName
IF @PublisherID = NULL
PRINT 'Name does not exist'
ELSE
RETURN @PublisherID
END;
40. CREATE PROCEDURE uspGetShoppingCartID
@Email VARCHAR(200)
AS
BEGIN
DECLARE @ShoppingCartID INT
DECLARE @CustomerDataID INT
EXEC @CustomerDataID = uspGetCustomerDataID @Email
SELECT @ShoppingCartID = ShoppingCartID
FROM SHOPPING_CART
WHERE CustomerDataID = @CustomerDataID
IF @ShoppingCartID = NULL
PRINT 'A shoppingCartID was not found'
ELSE
RETURN @ShoppingCartID
END;
41. CREATE PROCEDURE uspRemoveBookFromShoppingCart (
@Email VARCHAR(40),
@ISBN VARCHAR(13)
)
AS
BEGIN
DECLARE @RowCount INT
DECLARE @CustomerID INT
DECLARE @BookDataID INT
DECLARE @ShoppingCartID INT
DECLARE @BookCost NUMERIC(5,2)
DECLARE @OldTotal NUMERIC(5,2)
DECLARE @NewTotal NUMERIC(5,2)
--See if book is in shopping cart
EXEC @CustomerID = uspGetCustomerDataID @Email
SELECT @RowCount = COUNT(*)
FROM SHOPPING_CART sc
JOIN TRANSACTIONS tc ON sc.ShoppingCartID = tc.ShoppingCartID
JOIN BOOK_DATA bd ON tc.BookDataID = bd.BookDataID
WHERE ISBN = @ISBN
AND sc.CustomerDataID = @CustomerID
AND sc.TransactionDateTime IS NULL
--If there is a book or books
IF @RowCount > 1
BEGIN
--Lower the total
EXEC @ShoppingCartID = uspGetShoppingCartID @Email
SELECT @BookCost = Cost
FROM BOOK_DATA
WHERE BookDataID = @BookDataID
SELECT @OldTotal = Total
FROM SHOPPING_CART
WHERE ShoppingCartID = @ShoppingCartID
SELECT @NewTotal = @OldTotal - @BookCost
UPDATE SHOPPING_CART
SET Total = @NewTotal
WHERE ShoppingCartID = @ShoppingCartID
AND TransactionDateTime IS NULL
--Remove from transactions
DELETE FROM TRANSACTIONS
WHERE ShoppingCartID = @ShoppingCartID
AND BookDataID = @BookDataID
END
ELSE
BEGIN
PRINT 'There is no such book in the shopping cart'
END
END
42. CREATE PROCEDURE uspVerifyPublisher (
@PublisherName VARCHAR(30)
)
AS
BEGIN
DECLARE @PublisherID INT
SELECT @PublisherID = PublisherID
FROM PUBLISHER
WHERE PublisherName = @PublisherName
/*If publisher is null then return 0 for false*/
IF @PublisherID = NULL
Return 0
ELSE
/*If publisher is not null then return 1 for true*/
Return 1
END;
45. CREATE PROCEDURE uspTotalRevenueTimeFrame
@BeginDate DATE,
@EndDate DATE
AS
BEGIN
/*get the beginning and end dates
check that beginning is earlier than end date
Add all the totals between those 2 dates
*/
IF @BeginDate > @EndDate
PRINT 'Begin Date must be earlier than End Date'
ELSE
SELECT SUM (SellingPrice) AS 'Total Sales During Period'
FROM PURCHASES
WHERE PurchaseDateTime >= @BeginDate
AND PurchaseDateTime <= @EndDate
END
46. CREATE PROCEDURE uspUpdateAdminHashSalt
@CurrentAdministrator VARCHAR(20),
@CurrentSalt VARCHAR(45),
@NewSalt VARCHAR(20),
@NewHash VARCHAR(45)
AS
BEGIN
DECLARE @AdminCheck BIT
/*Verify the administrator*/
EXEC @AdminCheck = uspVerifyAdministrator @CurrentAdministrator, @CurrentSalt
IF @AdminCheck <> 1
PRINT 'User does not have permission to edit'
ELSE
BEGIN
/*Update the old hash and salt with the new hash and salt*/
UPDATE ADMINISTRATOR
SET Hash = @NewHash,
Salt = @NewSalt
WHERE Username = @CurrentAdministrator
END
END;
47. CREATE PROCEDURE uspUpdateBillingAddress
@CurrentAdmin VARCHAR(20),
@CurrentSalt VARCHAR(45),
@Email VARCHAR(40),
@Street1 VARCHAR(25),
@Street2 VARCHAR(25),
@City VARCHAR(25),
@Zip VARCHAR(6),
@Region VARCHAR(25),
@Country VARCHAR(25)
AS
BEGIN
DECLARE @Admin BIT
DECLARE @EmailCount INT
DECLARE @BillingAddressID INT
--check that the current administrator has permission to update
EXEC @Admin = uspVerifyAdministrator @CurrentAdmin, @CurrentSalt
IF @Admin <> 1
PRINT 'User does not have permission to edit'
ELSE
BEGIN
--Verify the email
SELECT @EmailCount = COUNT(*)
FROM CUSTOMER_DATA
WHERE Email = @Email
IF @EmailCount < 1
PRINT 'The email does not exist'
ELSE
BEGIN
--get the BillingAdressID
SELECT @BillingAddressID = BillingAddressID
FROM CUSTOMER_DATA
WHERE Email = @Email
UPDATE BILLING_ADDRESS
SET Street = @Street1,
Street2 = @Street2,
City = @City,
Zip = @Zip,
Region = @Region,
Country = @Country
WHERE BillingAddressID = @BillingAddressID
END
END
END;
48. CREATE PROCEDURE uspUpdateBookInformation
@CurrentAdmin VARCHAR(20),
@CurrentSalt VARCHAR(40),
@ISBN VARCHAR(13),
@Name VARCHAR(45),
@NewISBN VARCHAR(13),
@Quantity INT,
@CopyrightDate DATE,
@Cost NUMERIC(5,2)
AS
BEGIN
DECLARE @Admin BIT
DECLARE @ISBNCount INT
DECLARE @BookDataID INT
--check that the current administrator has permission to update
EXEC @Admin = uspVerifyAdministrator @CurrentAdmin, @CurrentSalt
IF @Admin <> 1
PRINT 'User does not have permission to edit'
ELSE
BEGIN
--check that the ISBN exists in the table
SELECT @ISBNCount = COUNT(*)
FROM BOOK_DATA
WHERE ISBN = @ISBN
IF @ISBNCount < 1
PRINT 'The ISBN does not exist in the table'
ELSE
BEGIN
--get bookDataID
SELECT @BookDataID = BookDataID
FROM BOOK_DATA
WHERE ISBN = @ISBN
--insert new information
UPDATE BOOK_DATA
SET Name = @Name,
ISBN = @NewISBN,
Quantity = @Quantity,
CopyrightDate = @CopyrightDate,
Cost = @Cost
WHERE BookDataID = @BookDataID
END
END
END;
49. CREATE PROCEDURE uspUpdateCustomerHashSalt
@CurrentAdministrator VARCHAR(20),
@CurrentSalt VARCHAR(45),
@Email VARCHAR(30),
@NewCustomerSalt VARCHAR(45),
@NewCustomerHash VARCHAR(45)
AS
BEGIN
DECLARE @AdminCheck BIT
DECLARE @CustomerID INT
/*Verify the administrator*/
EXEC @AdminCheck = uspVerifyAdministrator @CurrentAdministrator, @CurrentSalt
IF @AdminCheck <> 1
PRINT 'User does not have permission to edit'
ELSE
BEGIN
EXEC @CustomerID = uspGetCustomerID @CurrentSalt, @Email
/*Update the old customer hash and salt with the new hash and salt*/
UPDATE CUSTOMER
SET Hash = @NewCustomerHash,
Salt = @NewCustomerSalt
WHERE CustomerID = @CustomerID
END
END;
50. CREATE procedure uspUpdateCustomerEmail
(
@CurrentAdministrator Varchar(20),
@AdminSalt Varchar(45),
@CurrentSalt Varchar(45),
@Email varchar(200),
@NewEmail varchar(30)
)
AS
BEGIN
DECLARE @CurrentAdmin int
/*Check to see if user is admin*/
DECLARE @AdminCheck BIT
DECLARE @CustomerID INT
/*Verify the administrator*/
EXEC @AdminCheck = uspVerifyAdministrator @CurrentAdministrator, @AdminSalt
IF @AdminCheck <> 1
PRINT 'User does not have permission to edit'
ELSE
/*If user is admin*/
BEGIN
EXEC @CustomerID = uspGetCustomerID @Email,@CurrentSalt
/*Update the old customer email*/
UPDATE CUSTOMER_DATA
SET Email = @NewEmail
WHERE CustomerID = @CustomerID
END
END;
51. CREATE PROCEDURE uspUpdateCustomerInformation
@CurrentAdmin VARCHAR(20),
@CurrentSalt VARCHAR(45),
@Email VARCHAR(40),
@FirstName VARCHAR(25),
@LastName VARCHAR(25),
@Age INT,
@Gender CHAR(1),
@NewEmail VARCHAR(40),
@HomePhone VARCHAR(15),
@WorkPhone VARCHAR(15)
AS
BEGIN
DECLARE @Admin BIT
DECLARE @EmailCount INT
DECLARE @CustomerDataID INT
--check that the current administrator has permission to update
EXEC @Admin = uspVerifyAdministrator @CurrentAdmin, @CurrentSalt
IF @Admin <> 1
PRINT 'User does not have permission to edit'
ELSE
BEGIN
--Verify the email
SELECT @EmailCount = COUNT(*)
FROM CUSTOMER_DATA
WHERE Email = @Email
IF @EmailCount < 1
PRINT 'The email does not exist'
ELSE
BEGIN
--get customerDataID
SELECT @CustomerDataID = CustomerDataID
FROM CUSTOMER_DATA
WHERE Email = @Email
UPDATE CUSTOMER_DATA
SET FirstName = @FirstName,
LastName = @LastName,
Age = @Age,
Gender = @Gender,
Email = @NewEmail,
HomePhone = @HomePhone,
WorkPhone = @WorkPhone
WHERE CustomerDataID = @CustomerDataID
END
END
END;
52. CREATE PROCEDURE uspUpdateShippingAddress
@CurrentAdmin VARCHAR(20),
@CurrentSalt VARCHAR(45),
@Email VARCHAR(40),
@Street1 VARCHAR(25),
@Street2 VARCHAR(25),
@City VARCHAR(25),
@Zip VARCHAR(6),
@Region VARCHAR(25),
@Country VARCHAR(25)
AS
BEGIN
DECLARE @Admin BIT
DECLARE @EmailCount INT
DECLARE @ShippingAddressID INT
--check that the current administrator has permission to update
EXEC @Admin = uspVerifyAdministrator @CurrentAdmin, @CurrentSalt
IF @Admin <> 1
PRINT 'User does not have permission to edit'
ELSE
BEGIN
--Verify the email
SELECT @EmailCount = COUNT(*)
FROM CUSTOMER_DATA
WHERE Email = @Email
IF @EmailCount < 1
PRINT 'The email does not exist'
ELSE
BEGIN
--get the shippingAddressID
SELECT @ShippingAddressID = ShippingAddressID
FROM CUSTOMER_DATA
WHERE Email = @Email
UPDATE SHIPPING_ADDRESS
SET Street = @Street1,
Street2 = @Street2,
City = @City,
Zip = @Zip,
Region = @Region,
Country = @Country
WHERE ShippingAddressID = @ShippingAddressID
END
END
END;
53. CREATE PROCEDURE uspUpdateAdminAccess
(
@CurrentAdministrator VARCHAR(45),
@CurrentSalt VARCHAR(45),
@UserStatusChange VARCHAR(45),
@ChangeAccess bit
)
AS
BEGIN
DECLARE @AdminCheck BIT
/*See if current user is an admin*/
EXEC @AdminCheck = uspVerifyAdministrator @CurrentAdministrator, @CurrentSalt
IF @AdminCheck <> 1
PRINT 'User does not have permission to edit'
ELSE
BEGIN
UPDATE ADMINISTRATOR
SET AdminAccess = @ChangeAccess
WHERE UserName = @UserStatusChange
END
END
54. Table Creation Code
CREATE TABLE ADMINISTRATOR (
AdministratorID INT NOT NULL IDENTITY (1000,1),
Username VARCHAR(20) NOT NULL,
Hash VARCHAR(45) NOT NULL,
Salt VARCHAR(45) NOT NULL,
AdminAccess BIT NOT NULL,
CONSTRAINT Admin_PK PRIMARY KEY(AdminID)
);
CREATE TABLE DISCOUNT (
DiscountID INT NOT NULL IDENTITY (1,1),
Name VARCHAR(25) NOT NULL,
DiscountPercent NUMERIC(2,3) NOT NULL,
CONSTRAINT Discount_PK PRIMARY KEY(DiscountID)
);
CREATE TABLE CUSTOMER (
CustomerID INT NOT NULL IDENTITY(1000,1),
Hash VARCHAR(45) NOT NULL,
Salt VARCHAR(45) NOT NULL,
CONSTRAINT Customer_PK PRIMARY KEY(CustomerID)
);
CREATE TABLE AUTHOR_INTERSECTION (
AuthorID INT NOT NULL,
BookDataID INT NOT NULL,
CONSTRAINT AInter_PK PRIMARY KEY(AuthorID, BookDataID)
);
CREATE TABLE AUTHOR (
AuthorID INT NOT NULL IDENTITY (1000,1),
AuthorName VARCHAR(20) NOT NULL,
CONSTRAINT Author_PK PRIMARY KEY(AuthorID)
);
CREATE TABLE BILLING_ADDRESS (
BillingAddressID INT NOT NULL IDENTITY (1000,1),
Street VARCHAR(25) NOT NULL,
Street2 VARCHAR(25) NULL,
City VARCHAR(25) NOT NULL,
Zip VARCHAR(6) NULL,
Region VARCHAR(25) NOT NULL,
Country VARCHAR(25) NOT NULL,
CONSTRAINT Billing_PK PRIMARY KEY(BillingAddressID),
CONSTRAINT Region_check CHECK(Region='Alabama' or Region='Alaska' or
Region='Arizona' or Region='California' or Region='Colorado' or Region='Connecticut' or
Region='Delaware' or Region='Florida' or Region='Georgia' or Region='Hawaii' or
Region='Idaho' or Region='Illinois' or Region='Indiana' or Region='Iowa' or
Region='Kansas' or Region='Kentucky' or Region='Louisiana' or Region='Maine' or
Region='Maryland' or Region='Massachusetts' or Region='Michigan' or Region='Minnesota' or
Region='Mississippi' or Region='Missouri' or Region='Montana' or Region='Nebraska' or
Region='Nevada' or Region='New Hampshire' or Region='New Jersey' or Region='New Mexico'
or Region='New York' or Region='North Carolina' or Region='North Dakota' or Region='Ohio'
or Region='Oklahoma' or Region='Oregon' or Region='Pennsylvania' or Region='Rhode Island'
or Region='South Carolina' or Region='South Dakota' or Region='Tennessee' or
55. Region='Texas' or Region='Utah' or Region='Vermont' or Region='Virginia' or
Region='Washington' or Region='West Virginia' or Region='Wisconsin' or Region='Wyoming'
or Region='Pacific Coast' or Region='Gulf of Mexico' or Region='Baja' or Region='Central'
or Region='Northern' or Region='Alberta' or Region='British Columbia' or
Region='Manitoba' or Region='New Brunswick' or Region='Newfoundland and labrador' or
Region='Northwest Territories' or Region='Nova Scotia' or Region='Nunavut' or
Region='Ontario' or Region='Prince Edward Island' or Region='Quebec' or
Region='Saskatchewan' or Region='Yukon'),
CONSTRAINT Country_Check Check(Country='United States' or
Country='Mexico' or Country='Canada')
);
CREATE TABLE CUSTOMER_DATA (
CustomerDataID INT NOT NULL IDENTITY(1000,1),
CustomerID INT NOT NULL,
BillingAddressID INT NOT NULL,
ShippingAddressID INT NOT NULL,
ShoppingCartID INT NOT NULL,
CreditCardID INT NOT NULL,
FirstName VARCHAR(25) NOT NULL,
LastName VARCHAR(25) NOT NULL,
Age INT NOT NULL,
Gender CHAR(1) NOT NULL,
EMail VARCHAR(40) NOT NULL,
HomePhone VARCHAR(15) NOT NULL,
WorkPhone VARCHAR(15) NULL,
CONSTRAINT CustomerData_PK PRIMARY KEY(CustomerDataID),
CONSTRAINT CustomerID_FK FOREIGN KEY(CustomerID) REFERENCES
CUSTOMER(CustomerID),
CONSTRAINT BillingAddressID_FK FOREIGN KEY(BillingAddressID) REFERENCES
BILLING_ADDRESS(BillingAddressID),
CONSTRAINT ShippingAddressID_FK FOREIGN KEY(ShippingAddressID) REFERENCES
SHIPPING_ADDRESS(ShoppingAddressID),
CONSTRAINT ShoppingCartID_FK FOREIGN KEY(ShoppingCartID) REFERENCES
SHOPPING_CART(ShoppingCartID),
CONSTRAINT CreditCardID_FK FOREIGN KEY(CreditCardID) REFERENCES
CREDIT_CARD(CreditCardID),
CONSTRAINT Gender_check Check ('U' or 'F' or 'M' )
);
CREATE TABLE SHIPPING_ADDRESS (
ShippingAddressID INT NOT NULL IDENTITY(1000,1),
Street VARCHAR(25) NOT NULL,
Street2 VARCHAR(20) NULL,
City VARCHAR(25) NOT NULL,
Zip VARCHAR(5) NULL,
Region VARCHAR(25) NOT NULL,
Country VARCHAR(25) NOT NULL,
CONSTRAINT ship_address_pk PRIMARY KEY(shippingAddressID),
CONSTRAINT Region_check CHECK(Region='Alabama' or Region='Alaska' or
Region='Arkansas' or Region='Arizona' or Region='California' or Region='Colorado' or
Region='Connecticut' or Region='Delaware' or Region='Florida' or Region='Georgia' or
Region='Hawaii' or Region='Idaho' or Region='Illinois' or Region='Indiana' or
Region='Iowa' or Region='Kansas' or Region='Kentucky' or Region='Louisiana' or
Region='Maine' or Region='Maryland' or Region='Massachusetts' or Region='Michigan' or
Region='Minnesota' or Region='Mississippi' or Region='Missouri' or Region='Montana' or
Region='Nebraska' or Region='Nevada' or Region='New Hampshire' or Region='New Jersey' or
56. Region='New Mexico' or Region='New York' or Region='North Carolina' or Region='North
Dakota' or Region='Ohio' or Region='Oklahoma' or Region='Oregon' or Region='Pennsylvania'
or Region='Rhode Island' or Region='South Carolina' or Region='South Dakota' or
Region='Tennessee' or Region='Texas' or Region='Utah' or Region='Vermont' or
Region='Virginia' or Region='Washington' or Region='West Virginia' or Region='Wisconsin'
or Region='Wyoming' or Region='Pacific Coast' or Region='Gulf of Mexico' or Region='Baja'
or Region='Central' or Region='Northern' or Region='Alberta' or Region='British Columbia'
or Region='Manitoba' or Region='New Brunswick' or Region='Newfoundland and labrador' or
Region='Northwest Territories' or Region='Nova Scotia' or Region='Nunavut' or
Region='Ontario' or Region='Prince Edward Island' or Region='Quebec' or
Region='Saskatchewan' or Region='Yukon'),
CONSTRAINT Country_Check Check('United States' or 'Mexico' or 'Canada')
);
CREATE TABLE PURCHASES (
PurchaseID INT NOT NULL IDENTITY(1000,1),
BookDataID INT NOT NULL,
PurchaseDateTime DATETIME2 NOT NULL,
SellingPrice Money NOT NULL,
Constraint Purchase_PK PRIMARY KEY(PurchaseID),
Constraint Book_Data_FK FOREIGN KEY(BookDataID)
);
CREATE TABLE BOOK_DATA (
BookDataID INT NOT NULL IDENTITY(1000,1),
PublisherID INT NOT NULL,
Name VARCHAR(25) NOT NULL,
ISBN VARCHAR(13) NOT NULL,
Quantity INT NOT NULL,
CopyrightDate DATE NULL,
Cost NUMERIC(5,2) NOT NULL,
Constraint BookData_PK PRIMARY KEY(BookDataID),
Constraint Author_FK FOREIGN KEY(AuthorID) REFERENCES AUTHOR
(AuthorID),
Constraint Publisher_FK FOREIGN KEY(PublisherID)REFERENCES
PUBLISHER (PublisherID),
Constraint Genre_FK FOREIGN KEY(GenreID)REFERENCES GENRE
(GenreID),
Constraint Cost_Check CHECK (COST >= 0)
);
CREATE TABLE PUBLISHER (
PublisherID INT NOT NULL IDENTITY(1000,1),
PublisherName VARCHAR(30) NOT NULL,
Street VARCHAR(30) NOT NULL,
City VARCHAR(30) NOT NULL,
Region VARCHAR(25) NOT NULL,
Country VARCHAR(25) NOT NULL,
Zip VARCHAR(6) NULL,
CONSTRAINT Publisher_PK PRIMARY KEY(PublisherID),
CONSTRAINT Region_check CHECK(Region='Alabama' or Region='Alaska' or
Region='Arkansas' or Region='Arizona' or Region='California' or Region='Colorado' or
Region='Connecticut' or Region='Delaware' or Region='Florida' or Region='Georgia' or
Region='Hawaii' or Region='Idaho' or Region='Illinois' or Region='Indiana' or
Region='Iowa' or Region='Kansas' or Region='Kentucky' or Region='Louisiana' or
Region='Maine' or Region='Maryland' or Region='Massachusetts' or Region='Michigan' or
Region='Minnesota' or Region='Mississippi' or Region='Missouri' or Region='Montana' or
Region='Nebraska' or Region='Nevada' or Region='New Hampshire' or Region='New Jersey' or
57. Region='New Mexico' or Region='New York' or Region='North Carolina' or Region='North
Dakota' or Region='Ohio' or Region='Oklahoma' or Region='Oregon' or Region='Pennsylvania'
or Region='Rhode Island' or Region='South Carolina' or Region='South Dakota' or
Region='Tennessee' or Region='Texas' or Region='Utah' or Region='Vermont' or
Region='Virginia' or Region='Washington' or Region='West Virginia' or Region='Wisconsin'
or Region='Wyoming' or Region='Pacific Coast' or Region='Gulf of Mexico' or Region='Baja'
or Region='Central' or Region='Northern' or Region='Alberta' or Region='British Columbia'
or Region='Manitoba' or Region='New Brunswick' or Region='Newfoundland and labrador' or
Region='Northwest Territories' or Region='Nova Scotia' or Region='Nunavut' or
Region='Ontario' or Region='Prince Edward Island' or Region='Quebec' or
Region='Saskatchewan' or Region='Yukon'),
CONSTRAINT Country_Check Check(Country='United States' or
Country='Mexico' or Country='Canada')
);
CREATE TABLE PUBLISHER_CONTACTS (
ContactID INT NOT NULL IDENTITY(1000,1),
PublisherID INT NOT NULL,
ContactName VARCHAR(20) NULL,
Phone NUMERIC(11) NULL,
CONSTRAINT PublisherCON_PK PRIMARY KEY(ContactID),
CONSTRAINT PublisherID_FK FOREIGN KEY (PublisherID)REFERENCES
PUBLISHER(PublisherID)
);
CREATE TABLE CREDIT_CARD (
CreditCardID INT NOT NULL IDENTITY(1000,1),
Name VARCHAR(25) NOT NULL,
ExpirationDate DATETIME2(4) NOT NULL,
CreditCardNumber NUMERIC(16) NOT NULL,
CreditCardType VARCHAR(25) NOT NULL,
SecurityCode INT NOT NULL,
CONSTRAINT CreditCardID_PK PRIMARY KEY(CreditCardID),
CONSTRAINT CardType_Check CHECK(CreditCardType = 'VISA' OR CreditCardType
='American Express' OR CreditCardType ='MasterCard' OR CreditCardType ='Discover'),
);
CREATE TABLE SHOPPING CART (
ShoppingCartID INT NOT NULL IDENTITY(1000,1),
CustomerDataID INT NOT NULL,
TransactionDateTime DATETIME2 NULL,
Total MONEY NULL,
CONSTRAINT ShoppingCartID_PK PRIMARY KEY(ShoppingCartID),
CONSTRAINT TransactionID_FK FOREIGN KEY(TransactionID) REFERENCES
TRANSACTIONS(TransactionID),
CONSTRAINT CustomerDataID_FK FOREIGN KEY(CustomerDataID) REFERENCES
CUSTOMER_DATA(CustomerDataID),
);
CREATE TABLE TRANSACTIONS (
TransactionID INT NOT NULL IDENTITY(1000,1),
ShoppingCartID INT NOT NULL,
BookDataID INT NOT NULL,
CONSTRAINT TransactionID_PK PRIMARY KEY(TransactionID),
CONSTRAINT ShoppingCartID_FK FOREIGN KEY(ShoppingCartID) REFERENCES
SHOPPING_CART(ShoppingCartID),
CONSTRAINT BookDataID_FK FOREIGN KEY(BookDataID) REFERENCES BOOK_DATA
(BookDataID)
58. );
CREATE TABLE GENRE_INTERSECTION (
GenreID INT NOT NULL,
BookDataID INT NOT NULL,
CONSTRAINT GenreID_BookDataID_PK PRIMARY KEY(GenreID, BookDataID)
);
CREATE TABLE GENRE (
GenreID INT NOT NULL IDENTITY(1000,1),
GenreName VARCHAR(25) NULL,
CONSTRAINT GenreID_PK PRIMARY KEY(GenreID)
);
ALTER TABLE GENRE_INTERSECTION
ADD FOREIGN KEY (GenreID)
REFERENCES GENRE(GenreID);
ALTER TABLE GENRE_INTERSECTION
ADD FOREIGN KEY (BookDataID)
REFERENCES BOOK_DATA(BookDataID);
ALTER TABLE AUTHOR_INTERSECTION
ADD FOREIGN KEY (BookDataID)
REFERENCES BOOK_DATA(BookDataID);
ALTER TABLE AUTHOR_INTERSECTION
ADD FOREIGN KEY (AuthorID)
REFERENCES AUTHOR(AuthorID);