SQL Server Trigger functioning backwards - sql-server

I have a little strange issue with my SQL script and I was hoping someone could help me out with it.
I have a Database being created by using
IF EXISTS (SELECT name
FROM sysdatabases
WHERE name = 'travel')
DROP DATABASE travel
GO
CREATE DATABASE travel
GO
USE travel
GO
I then create 3 tables as shown below
CREATE TABLE customer
(
customerID INT,
lastname VARCHAR(70) NOT NULL,
firstname VARCHAR(70) NOT NULL,
phone VARCHAR(10) CONSTRAINT phoneCheck CHECK ((phone LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')),
category VARCHAR(7) NOT NULL CONSTRAINT categoryDefault DEFAULT 'A',
CONSTRAINT categoryCheck CHECK (category IN ('A', 'B', 'C')),
CONSTRAINT customerPK
PRIMARY KEY (customerID)
)
CREATE TABLE package /*Still need to do the Zero Padding*/
(
packageCode VARCHAR(6),
destination VARCHAR(70),
CONSTRAINT packageCodeCheck CHECK (packageCode LIKE ('YFK%')),
price MONEY NOT NULL CONSTRAINT priceCheck CHECK ((price BETWEEN 1000 AND 10000)),
passportRequired VARCHAR(7) NOT NULL CONSTRAINT passportRequiredDefault DEFAULT 'Y',
CONSTRAINT passportCheck CHECK (passportRequired IN ('Y', 'N')),
CONSTRAINT packagePK
PRIMARY KEY (packageCode)
)
CREATE TABLE booking /*Still need to do the Customer and Package delete*/
(
customerID VARCHAR(6),
bookingDate VARCHAR(70) NOT NULL DEFAULT GETDATE(),
amountPaid MONEY CONSTRAINT amountPaidDefault DEFAULT 0.00,
CONSTRAINT bookingPK
PRIMARY KEY (customerID)
)
Now heres the issue, I create a trigger as shown below
GO
CREATE TRIGGER customerDelete ON customer AFTER DELETE
AS
DELETE booking
FROM customer
WHERE customer.customerID = booking.customerID
GO
Which to my understanding it will delete all records in booking... that have the matching customerID WHEN a record is deleted from the customer Table. (I am new to triggers)
I INSERT Sample Data as shown below
INSERT INTO customer
(customerID, lastname, firstname, phone, category)
VALUES
(1, 'Picard', 'Corey', 1234567890, 'A'),
(2, 'Bond', 'Devon', 9876543210, 'B'),
(3, 'Douglas', 'Bryan', 6549871230, 'C')
INSERT INTO package
(packageCode, destination, price, passportRequired)
VALUES
('YFK001', 'Toronto', 1000.57, 'N'),
('YFK002', 'Orlando', 3000.98, 'Y')
INSERT INTO booking
(customerID, bookingDate, amountPaid)
VALUES
(1, GETDATE(), 1548),
(2, GETDATE(), 1586),
(3, GETDATE(), 1350),
(4, GETDATE(), 1650)
And Finally I delete the Customer from the TABLE customer with the customerID of 1 by using
DELETE customer
WHERE customerID = 1
However, when I attempt to see the results by using
SELECT * FROM customer
--WHERE customerID = 1 OR customerID = 2 OR customerID = 3
SELECT * FROM package
--WHERE packageCode = 'YFK001' OR packageCode = 'YFK002'
SELECT * FROM booking
--WHERE customerID = 1 OR customerID = 2 OR customerID = 3 OR customerID = 4
It displays bookings with customerID 1 and 4.
Can you let me know what I'm doing wrong?
The trigger is essentially used for the purpose of deleting the bookings with the same customerID of the customer we delete from the customer TABLE
All help is greatly appreciated.
Thanks,
Bryan

Change your delete to this:
DELETE B
FROM booking B
INNER JOIN DELETED D
ON B.customerID = D.customerID;

My Answer is not trigger, [ If you specially want to use Trigger then You can use Lamak's & Pradeep's Answer]
Here best way you can do is use Cacade on foreign Key in your case
Here is your Query I just updated cascade in it
CREATE TABLE customer
(
customerID INT,
lastname VARCHAR(70) NOT NULL,
firstname VARCHAR(70) NOT NULL,
phone VARCHAR(10) CONSTRAINT phoneCheck CHECK ((phone LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')),
category VARCHAR(7) NOT NULL CONSTRAINT categoryDefault DEFAULT 'A',
CONSTRAINT categoryCheck CHECK (category IN ('A', 'B', 'C')),
CONSTRAINT customerPK
PRIMARY KEY (customerID)
)
CREATE TABLE package /*Still need to do the Zero Padding*/
(
packageCode VARCHAR(6),
destination VARCHAR(70),
CONSTRAINT packageCodeCheck CHECK (packageCode LIKE ('YFK%')),
price MONEY NOT NULL CONSTRAINT priceCheck CHECK ((price BETWEEN 1000 AND 10000)),
passportRequired VARCHAR(7) NOT NULL CONSTRAINT passportRequiredDefault DEFAULT 'Y',
CONSTRAINT passportCheck CHECK (passportRequired IN ('Y', 'N')),
CONSTRAINT packagePK
PRIMARY KEY (packageCode)
ON DELETE CASCADE
ON UPDATE CASCADE
)
CREATE TABLE booking /*Still need to do the Customer and Package delete*/
(
customerID VARCHAR(6),
bookingDate VARCHAR(70) NOT NULL DEFAULT GETDATE(),
amountPaid MONEY CONSTRAINT amountPaidDefault DEFAULT 0.00,
CONSTRAINT bookingPK
PRIMARY KEY (customerID)
ON DELETE CASCADE
ON UPDATE CASCADE
)
This way when you are deleting or update [keyvalue] any entry of Table holding primary key will update its related foreign childs

Related

Adding a row to ORDERS table which then increases the ordered number of that product and the customer?

I am trying to learn SQL, and while my journey has been quite successful this far, I have run into problems with triggers. For the record, I am using SQL Server 2016. I would appreciate any help I can get. Please let me know if more details are needed.
Hope it will help
-------------
--cascade delete way
-------------
CREATE TABLE dbo.customers (
customer_id INT NOT NULL
, somedata UNIQUEIDENTIFIER NOT NULL
, CONSTRAINT PK_Customer PRIMARY KEY (customer_id)
);
CREATE TABLE dbo.orders (
OrderID INT NOT NULL
, customer_id INT NOT NULL
, somedata UNIQUEIDENTIFIER NOT NULL
, CONSTRAINT PK_Order PRIMARY KEY (OrderID)
, CONSTRAINT FK_CustomerOrder FOREIGN KEY (customer_id)
REFERENCES dbo.customers (customer_id) ON DELETE CASCADE
);
INSERT INTO dbo.customers (customer_id,somedata)
VALUES (1,NEWID()),(2,NEWID())
INSERT INTO dbo.orders(OrderID,customer_id,somedata)
VALUES (1,1,NEWID()),(2,2,NEWID())
DELETE FROM dbo.customers WHERE customer_id = 1
SELECT * FROM dbo.orders
-------------
--trigger way
-------------
CREATE TABLE dbo.customers1 (
customer_id INT NOT NULL
, somedata UNIQUEIDENTIFIER NOT NULL
, CONSTRAINT PK_Customer1 PRIMARY KEY (customer_id)
);
CREATE TABLE dbo.orders1 (
OrderID INT NOT NULL
, customer_id INT NOT NULL
, somedata UNIQUEIDENTIFIER NOT NULL
, CONSTRAINT PK_Order1 PRIMARY KEY (OrderID)
, CONSTRAINT FK_CustomerOrder1 FOREIGN KEY (customer_id)
REFERENCES dbo.customers1 (customer_id) ON DELETE CASCADE
);
GO
CREATE TRIGGER DELTRIG
ON dbo.customers1
FOR DELETE
AS
DELETE C
FROM dbo.orders1 AS C
INNER JOIN DELETED ON
C.customer_id = DELETED.customer_id
GO
INSERT INTO dbo.customers1 (customer_id,somedata)
VALUES (1,NEWID()),(2,NEWID())
INSERT INTO dbo.orders1(OrderID,customer_id,somedata)
VALUES (1,1,NEWID()),(2,2,NEWID())
DELETE FROM dbo.customers1 WHERE customer_id = 1
SELECT * FROM dbo.orders1
It is much safer if you would simply add a deleted flag in your customer table and in your trigger just update the deleted column to true.
But if you really need to delete the child records after the parent record is deleted, try using the cascade delete. You can refer from to this old post.
How do I use cascade delete with SQL Server?

Insert new record with composite primary key, which consists of two foreign keys from different tables

Please help me figure out how to Insert new record with composite primary key, which consists of two foreign keys from different tables.
I am working in C#, WPF if that matters.
I have three tables: Sales, SaleItem, Item.
CREATE TABLE [dbo].[Sales] (
[saleID] INT IDENTITY (1, 1) NOT NULL,
[saleTime] DATETIME NOT NULL,
[customerID] INT NULL,
[TIN] INT NOT NULL,
CONSTRAINT [PK_Sales] PRIMARY KEY CLUSTERED ([saleID] ASC),
CONSTRAINT [FK_Sales_Customers] FOREIGN KEY ([customerID]) REFERENCES [dbo].[Customers] ([customerID]),
CONSTRAINT [FK_Sales_Company] FOREIGN KEY ([TIN]) REFERENCES [dbo].[Company] ([TIN])
);
CREATE TABLE [dbo].[Item] (
[ItemSKU] INT IDENTITY (1, 1) NOT NULL,
[itemName] NVARCHAR (50) NOT NULL,
[volume] FLOAT (53) NOT NULL,
[measureUnit] NVARCHAR (50) NOT NULL,
[producer] NVARCHAR (50) NOT NULL,
[supplierID] INT NOT NULL,
[retailPrice] NUMERIC (18) NOT NULL,
CONSTRAINT [PK_Item] PRIMARY KEY CLUSTERED ([ItemSKU] ASC),
CONSTRAINT [FK_Item_Suppliers] FOREIGN KEY ([supplierID]) REFERENCES [dbo].[Suppliers] ([supplierID])
);
CREATE TABLE [dbo].[SaleItem] (
[saleID] INT IDENTITY (1, 1) NOT NULL,
[itemSKU] INT NOT NULL,
[quantity] INT NOT NULL,
CONSTRAINT [PK_SaleItem] PRIMARY KEY CLUSTERED ([saleID] ASC, [itemSKU] ASC),
CONSTRAINT [FK_SaleItem_Sales] FOREIGN KEY ([saleID]) REFERENCES [dbo].[Sales] ([saleID]),
CONSTRAINT [FK_SaleItem_Item] FOREIGN KEY ([itemSKU]) REFERENCES [dbo].[Item] ([ItemSKU])
);
I want to insert a new record into SaleItem table (the third one) where saleID is the last ID recorded in Sales table and ItemSKU which is equal to the value I get from another window.
I want these values:
SaleID = SELECT TOP 1 saleID FROM Sales ORDER BY saleID DESC";
ItemSKU = "SELECT itemName FROM Item WHERE ItemSKU = #sku";
I think I must do it in one query but I have no idea how.
Can you please give me a hint? I
First, you need to remove the IDENTITY property from the dbo.SaleItem table. The IDENTITY property is only required on the parent table, dbo.Sales.
You can do a single INSERT statement like this. It uses two subqueries, which are the SELECT statements in parentheses, to get values from the other two tables.
INSERT INTO dbo.SaleItem (saleID, itemSKU, quantity)
VALUES ((SELECT MAX(saleID) FROM dbo.Sales),
(SELECT ItemSKU FROM dbo.Item WHERE itemName = N'Widget'),
50);
You might want to turn it into a stored procedure, like this:
CREATE PROCEDURE dbo.up_InsertSaleItem
(
#itemName nvarchar(50),
#quantity int
)
AS
INSERT INTO dbo.SaleItem (saleID, itemSKU, quantity)
VALUES ((SELECT MAX(saleID) FROM dbo.Sales),
(SELECT ItemSKU FROM dbo.Item WHERE itemName = #itemName),
#quantity);
Then to use the stored procedure:
-- Test the stored procedure
EXEC dbo.up_InsertSaleItem #itemName=N'Widget', #quantity=50;
SELECT *
FROM dbo.SaleItem;
To read more about subqueries, see Microsoft SQL Server 2012 T-SQL Fundamentals by Itzik Ben-Gan, Chapter 4: Subqueries.

Update timestamp column when Foreign table updates without Trigger

I'm trying to setup a Timestamp/Rowversion on a Parent table so that when the Child table updates, the Timestamp on the Parent table row changes.
I don't need to know about the row in the Child table, just that according to the parent this particular row has changed.
USE [Test]
GO
CREATE TABLE [dbo].[Clerk](
[ID] [int] NOT NULL,
[Name] [varchar](20) NOT NULL,
[lastUpdate] [timestamp] NOT NULL,
CONSTRAINT [PK_Clerk] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
CREATE TABLE [dbo].[ClerkAddress](
[ClerkID] [int] NOT NULL,
[Address] [varchar](40) NOT NULL,
CONSTRAINT [PK_ClerkAddress] PRIMARY KEY CLUSTERED
(
[ClerkID] ASC
)
ALTER TABLE [dbo].[ClerkAddress] WITH CHECK ADD CONSTRAINT [FK_ClerkAddress_Clerk] FOREIGN KEY([ClerkID])
REFERENCES [dbo].[Clerk] ([ID])
ON UPDATE CASCADE
insert into Clerk (ID, Name) values (1, 'Test1')
insert into Clerk (id, Name) values (2, 'Test2')
insert into ClerkAddress (ClerkID, Address) values (1, 'address1')
insert into ClerkAddress (ClerkID, Address) values (2, 'address2')
using the following code examples.
update ClerkAddress set Address = NEWID() where ClerkID = 2
--no change to Clerk when address changes
select * from Clerk
select * from ClerkAddress
--Of course these update the lastUpdate in clerk
update Clerk set Name = 'test2' where ID = 2
update Clerk set Name = name
Is this even possible or do I need to make triggers for the updates? (update clerk set name = name where id = ClerkID)
You can make it appear as though the parent row is updated with a view.
You need to add a rowversion column to ClerkAddress, then
CREATE VIEW dbo.Clerk2
WITH SCHEMABINDING -- works for me on SQL Server 2012
AS
SELECT
C.ID, C.Name, ISNULL(MAX(CA.lastUpdate), C.lastUpdate) AS lastupdate
FROM
[dbo].[Clerk] C
LEFT JOIN
[dbo].[ClerkAddress] CA ON C.ID = CA.ClerkID
GROUP BY
C.ID, C.Name, C.lastUpdate
GO
SELECT * FROM dbo.Clerk2;
GO
update ClerkAddress set Address = NEWID() where ClerkID = 2;
GO
SELECT * FROM dbo.Clerk2;
GO
update ClerkAddress set Address = NEWID() where ClerkID = 2;
GO
SELECT * FROM dbo.Clerk2;
GO
This uses the highest value from rowversion yet preserves the actual rowversion on Clerk (which can still be used for optimistic concurrency by the client)
This works because rowversion is database unique

Is this a bug in MERGE, failing to implement FOREIGN KEY properly?

I am using the following tables to implement subtypes, which is a very common approach:
CREATE TABLE dbo.Vehicles(
ID INT NOT NULL,
[Type] VARCHAR(5) NOT NULL,
CONSTRAINT Vehicles_PK PRIMARY KEY(ID),
CONSTRAINT Vehicles_UNQ_ID_Type UNIQUE(ID, [Type]),
CONSTRAINT Vehicles_CHK_ValidTypes CHECK([Type] IN ('Car', 'Truck'))
);
GO
CREATE TABLE dbo.Cars(ID INT NOT NULL,
[Type] AS CAST('Car' AS VARCHAR(5)) PERSISTED,
OtherData VARCHAR(10) NULL,
CONSTRAINT Cars_PK PRIMARY KEY(ID),
CONSTRAINT Cars_FK_Vehicles FOREIGN KEY(ID, [Type])
REFERENCES dbo.Vehicles(ID, [Type])
);
GO
-- adding parent rows
INSERT INTO dbo.Vehicles(ID, [Type])
VALUES(1, 'Car'),
(2, 'Truck');
I have no problem adding a child row via INSERT, as follows:
INSERT INTO dbo.Cars(ID, OtherData)
VALUES(1, 'Some Data');
DELETE FROM dbo.Cars;
Surprisingly, MERGE fails to add one child row:
MERGE dbo.Cars AS TargetTable
USING
( SELECT 1 AS ID ,
'Some Data' AS OtherData
) AS SourceData
ON SourceData.ID = TargetTable.ID
WHEN NOT MATCHED
THEN INSERT (ID, OtherData)
VALUES(SourceData.ID, SourceData.OtherData);
Msg 547, Level 16, State 0, Line 1
The MERGE statement conflicted with the FOREIGN KEY constraint "Cars_FK_Vehicles". The conflict occurred in database "Test", table "dbo.Vehicles".
The statement has been terminated.
Is this a bug in MERGE or am I missing something?
Looks like a definite bug in MERGE to me.
The execution plan has the Clustered Index Merge operator and is supposed to output [Cars].ID,[Cars].Type for validation against the Vehicles table.
Experimentation shows that instead of passing the value "Car" as the Type value it is passing an empty string. This can be seen by removing the check constraint on Vehicles then inserting
INSERT INTO dbo.Vehicles(ID, [Type]) VALUES (3, '');
The following statement now works
MERGE dbo.Cars AS TargetTable
USING
( SELECT 3 AS ID ,
'Some Data' AS OtherData
) AS SourceData
ON SourceData.ID = TargetTable.ID
WHEN NOT MATCHED
THEN INSERT (ID, OtherData)
VALUES(SourceData.ID, SourceData.OtherData);
But the end result is that it inserts a row violating the FK constraint.
Cars
ID Type OtherData
----------- ----- ----------
3 Car Some Data
Vehicles
ID Type
----------- -----
1 Car
2 Truck
3
Checking the constraints immediately afterwards
DBCC CHECKCONSTRAINTS ('dbo.Cars')
Shows the offending row
Table Constraint Where
------------- ------------------- ------------------------------
[dbo].[Cars] [Cars_FK_Vehicles] [ID] = '3' AND [Type] = 'Car'

What is the proper procedure when trying to test your database in SQL?

I'm pretty new to databases and I have this assignment that I've completed where I had to look at a merged Entity Relationship Diagram and then create Drop Tables, Tables (with constraints and identity's), Alterations and Indexes. I'm pretty sure I've coded everything correctly but the only area I'm a little unsure about, it's how to test that the database will actually function when executing it. My instructor gave me a TestData.sql file that I just have to refer to the database and then execute and it should insert all the data into the tables and drop everything correctly. I have it all hooked up properly on SQL Server Management Studio but I forget what steps I should be taking in order to test the proper execution of the tables. I'll post some of my code so you guys can take a look. Any information regarding this issue would be greatly appreciated!
Also, when it says in the Test Data SQL code "IMPORTANT! If you need to run this script more than once you must drop and recreate your tables first to reset the identity properties." --Does this mean that if I run into any errors while trying to execute the test data, I will have to execute the DROP TABLES first and then maybe copy and paste all the TABLES back into the Database file? I don't actually have to manually type all the TABLES again, just need to re-enter them as "new" so the system will kind of reset it's identity properties?
If you guys need me to post more of the code for clarification, just let me know. Thanks for taking the time to read this :)
Update: I'm getting 2 error messages when trying to execute the TestData script: "Invalid object name 'SaleDetail'." and "Invalid object name 'Author'." I've also provided the rest of the code from my Database script file for you to take a look at. I'm almost certain everything is correct.
Database Tables Code (this is the complete code script)
USE Lab2A_BooksGalore
GO
/*------ Drop Table Statements ------*/
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'SaleDetail')
DROP TABLE SaleDetail
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'AuthorTitle')
DROP TABLE AuthorTitle
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Title')
DROP TABLE Title
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Publisher')
DROP TABLE Publisher
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Category')
DROP TABLE Category
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Author')
DROP TABLE Author
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Sale')
DROP TABLE Sale
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Employee')
DROP TABLE Employee
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Customer')
DROP TABLE Customer
/*------- Create Table Statements -------*/
CREATE TABLE Customer
(
CustomerNumber int
CONSTRAINT PK_Customer_CustomerNumber
PRIMARY KEY
IDENTITY (1, 1) NOT NULL,
LastName varchar(30) NOT NULL,
FirstName varchar(30) NOT NULL,
[Address] varchar(40) NULL,
City varchar(30) NULL,
Province char(2)
CONSTRAINT DF_Customer_Province
DEFAULT ('AB') NULL,
PostalCode char(6)
CONSTRAINT CK_Customer_PostalCode
CHECK (PostalCode LIKE '[A-Z][0-9][A-Z][0-9][A-Z][0-9]')
NULL,
HomePhone char(10)
)
CREATE TABLE Employee
(
EmployeeNumber int
CONSTRAINT PK_Employee_EmployeeNumber
PRIMARY KEY
IDENTITY (300, 1) NOT NULL,
[SIN] char(9) NOT NULL,
LastName varchar(30) NOT NULL,
FirstName varchar(30) NOT NULL,
[Address] varchar(40) NULL,
City varchar(20) NULL,
Province char(2)
CONSTRAINT DF_Employee_Province
DEFAULT ('AB') NULL,
PostalCode char(6)
CONSTRAINT CK_Employee_PostalCode
CHECK (PostalCode LIKE '[A-Z][0-9][A-Z][0-9][A-Z][0-9]')
NULL,
HomePhone char(10) NULL,
WorkPhone char(10) NULL,
Email varchar(40) NULL,
)
CREATE TABLE Sale
(
SaleNumber int
CONSTRAINT PK_Sale_SaleNumber
PRIMARY KEY
IDENTITY (3000, 1) NOT NULL,
SaleDate datetime NOT NULL,
CustomerNumber int
CONSTRAINT FK_Sale_CustomerNumber_Customer_CustomerNumber
FOREIGN KEY REFERENCES Customer(CustomerNumber)
NOT NULL,
EmployeeNumber int
CONSTRAINT FK_Sale_EmployeeNumber_Employee_EmployeeNumber
FOREIGN KEY REFERENCES Employee(EmployeeNumber)
NOT NULL,
Subtotal money
CONSTRAINT CK_Sale_Subtotal
CHECK (Subtotal <= Total) NOT NULL,
GST money NOT NULL,
Total money
CONSTRAINT CK_Sale_Total
CHECK (Total >= Subtotal) NOT NULL,
)
CREATE TABLE Author
(
AuthorCode int
CONSTRAINT PK_Author_AuthorCode
PRIMARY KEY
IDENTITY (100, 1) NOT NULL,
LastName varchar(30) NOT NULL,
FirstName varchar(30) NOT NULL,
)
CREATE TABLE Category
(
CategoryCode int
CONSTRAINT PK_Category_CategoryCode
PRIMARY KEY
IDENTITY (1, 1) NOT NULL,
[Description] varchar(40) NOT NULL,
)
CREATE TABLE Publisher
(
PublisherCode int
CONSTRAINT PK_Publisher_PublisherCode
PRIMARY KEY
IDENTITY (200, 1) NOT NULL,
[Name] varchar(40) NOT NULL,
)
CREATE TABLE Title
(
ISBN char(10)
CONSTRAINT PK_Title_ISBN
PRIMARY KEY NOT NULL,
Title varchar(40) NOT NULL,
SuggestedPrice smallmoney
CONSTRAINT DF_Title_SuggestedPrice
DEFAULT (0) NOT NULL,
NumberInStock smallint
CONSTRAINT CK_Title_NumberInStock
CHECK (NumberInStock >= 0)
CONSTRAINT DF_Title_NumberInStock
DEFAULT (0) NOT NULL,
PublisherCode int
CONSTRAINT FK_Title_PublisherCode_Publisher_PublisherCode
FOREIGN KEY REFERENCES Publisher(PublisherCode)
NOT NULL,
CategoryCode int
CONSTRAINT FK_Title_CategoryCode_Category_CategoryCode
FOREIGN KEY REFERENCES Category(CategoryCode)
NOT NULL,
)
CREATE TABLE AuthorTitle
(
ISBN char(10)
CONSTRAINT FK_AuthorTitle_ISBN_Title_ISBN
FOREIGN KEY REFERENCES Title(ISBN)
NOT NULL,
AuthorCode int
CONSTRAINT FK_AuthorTitle_AuthorCode_Author_AuthorCode
FOREIGN KEY REFERENCES Author(AuthorCode)
NOT NULL,
)
CREATE TABLE SaleDetail
(
SaleNumber int
CONSTRAINT FK_SaleDetail_SaleNumber_Sale_SaleNumber
FOREIGN KEY REFERENCES Sale(SaleNumber)
NOT NULL,
ISBN char(10)
CONSTRAINT FK_SaleDetail_ISBN_Title_ISBN
FOREIGN KEY REFERENCES Title(ISBN)
NOT NULL,
SellingPrice money NOT NULL,
Quantity int NOT NULL,
Amount money NOT NULL,
)
/*----------------- Alter Table Statements --------------------*/
---1) Add a char(10) attribute named WorkPhone to the Customer Table
ALTER TABLE Customer
ADD WorkPhone char(10) NULL
GO
---2) Add a varchar(30) attribute named Email to the Customer Table
ALTER TABLE Customer
ADD Email varchar(30) NULL
GO
---3) Add a constraint to make sure the correct format is followed for the Email attribute
ALTER TABLE Customer
ADD CONSTRAINT CK_Customer_Email
CHECK (Email LIKE '[a-z, 0-9][a-z, 0-9][a-z, 0-9]%#[a-z, 0-9][a-z, 0-9][a-z, 0-9]%.[a-z, 0-9][a-z, 0-9]%')
--- Match For: b 8 l # g v t . c a
GO
---4) Add a char(1) attribute named Active that's required for the Employee Table
ALTER TABLE Employee
ADD Active char(1) NOT NULL
GO
---5) Add a constraint to make sure the default character is used for the Active attribute
ALTER TABLE Employee
ADD CONSTRAINT DF_Employee_Active
DEFAULT ('y')
GO
/*------------------ Foreign Key Index Statements -----------------*/
CREATE NONCLUSTERED INDEX IX_Sale_CustomerNumber
ON Sale (CustomerNumber)
CREATE NONCLUSTERED INDEX IX_Sale_EmployeeNumber
ON Sale (EmployeeNumber)
CREATE NONCLUSTERED INDEX IX_Title_PublisherCode
ON Title (PublisherCode)
CREATE NONCLUSTERED INDEX IX_Title_CategoryCody
ON Title (CategoryCode)
CREATE NONCLUSTERED INDEX IX_AuthorTitle_ISBN
ON AuthorTitle (ISBN)
CREATE NONCLUSTERED INDEX IX_AuthorTitle_AuthorCode
ON AuthorTitle (AuthorCode)
CREATE NONCLUSTERED INDEX IX_SaleDetail_SaleNumber
ON SaleDetail (SaleNumber)
CREATE NONCLUSTERED INDEX IX_SaleDetail_ISBN
ON SaleDetail (ISBN)
GO
Test Data Code(this is only a snippet being this script is 100% accurate - provided by instructor)
USE Lab2A_BooksGalore
GO
--Lab 2 insert script
--IMPORTANT! If you need to run this script more than once you must drop and recreate your tables first to reset the identity properties.
--Delete existing data in the tables, if there is any
Delete From SaleDetail
Delete From Sale
Delete From AuthorTitle
Delete From Title
Delete From Employee
Delete From Customer
Delete From Category
Delete From Publisher
Delete From Author
Go
Insert into Author
(LastName, FirstName)
Values
('Smith', 'Sammy'),
('Greens', 'George'),
('Jones', 'Johnny'),
('Davidson', 'David'),
('Robertson', 'Rob'),
('Abbots', 'Abe'),
('Bakers', 'Bob'),
('Caters', 'Clem'),
('Semenko', 'Dave'),
('Franky', 'Fran'),
('Horton', 'Harry'),
('Kelly', 'Kevin'),
('Lambert', 'Larry'),
('Johnson', 'Jon'),
('Anderson', 'Ander'),
('Peterson', 'Peter'),
('Jensen', 'Jens'),
('Issacsen', 'Issac')
Insert into Publisher
(Name)
Values
('Addison Westley'),
('SAMS'),
('Harlequin'),
('Self Publish Inc'),
('Microsoft Press'),
('Jones and Bartlett'),
('WROX'),
('West'),
('Premier')
Insert into Category
(Description)
Values
('Computers'),
('Business'),
('Human Relation'),
('Electronics'),
('Designs'),
('Miscellaneous'),
('Media Design'),
('Information Technologies')

Resources