![]() |
Exam 70-433 Preparation: Microsoft SQL Server Database Development |
|
Questions |
CREATE TABLE Inventory.Categories
(
CategoryID int identity(1, 1) primary key,
Category nvarchar(20) not null
);
GO
CREATE TABLE Inventory.StoreItems
(
ItemNumber nvarchar(10) primary key,
CategoryID int foreign key
references Inventory.Categories(CategoryID),
ItemName nvarchar(60) not null,
Size nvarchar(20),
UnitPrice money
);
GO
INSERT INTO Inventory.Categories(Category)
VALUES(N'Men'), (N'Women'), (N'Boys'), (N'Girls'),(N'Miscellaneous');
GO
The employees of the company
are in charge of adding the records to the tables. To keep track of the
records added to the StoreItems table, James creates a table as
follows:
CREATE TABLE Inventory.DatabaseOperations
(
OperationID int identity(1,1) NOT NULL,
ObjectType nchar(20) default N'Table',
ObjectName nvarchar(40),
PerformedBy nvarchar(50),
ActionPerformed nvarchar(max),
TimePerformed datetime,
CONSTRAINT PK_Operations PRIMARY KEY(OperationID)
);
GO
When a new item is added to the StoreItems table, James would like
the DatabaseOperations table to receive a new record to that effect. How can
James create a trigger to perform that operation?
CREATE TRIGGER Inventory.NewProductCreated
ON Inventory.StoreItems
AFTER INSERT
AS
BEGIN
INSERT INTO Inventory.DatabaseOperations(ObjectType,
ObjectName, PerformedBy,
ActionPerformed, TimePerformed)
VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(),
N'New product added', GETDATE())
END
GOCREATE TRIGGER Inventory.NewProductCreated
AFTER INSERT
FOR OBJECT::Inventory.StoreItems
AS
BEGIN
INSERT INTO Inventory.DatabaseOperations(ObjectType,
ObjectName, PerformedBy,
ActionPerformed, TimePerformed)
VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(),
N'New product added', GETDATE())
END
GOCREATE OBJECT::Inventory.NewProductCreated
ON Inventory.StoreItems
AS TRIGGER FOR INSERT
BEGIN
RETURN
INSERT INTO Inventory.DatabaseOperations(ObjectType,
ObjectName, PerformedBy,
ActionPerformed, TimePerformed)
VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(),
N'New product added', GETDATE());
END
GOCREATE TRIGGER Inventory.NewProductCreated
ON Inventory.StoreItems
SET TRIGGER = INSERT
AS
RETURN
INSERT INTO Inventory.DatabaseOperations(ObjectType,
ObjectName, PerformedBy,
ActionPerformed, TimePerformed)
VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(),
N'New product added', GETDATE());
GOCREATE TRIGGER Inventory.NewProductCreated
ON Inventory.StoreItems
FOR INSERT
AS
INSERT INTO Inventory.DatabaseOperations(ObjectType,
ObjectName, PerformedBy,
ActionPerformed, TimePerformed)
VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(),
N'New product added', GETDATE());
GOCREATE TABLE Products
(
ProductID int identity(1, 1) not null,
DateAcquired date,
Name nvarchar(50),
Size nvarchar(32),
UnitPrice money,
DiscountRate decimal(4, 2),
CONSTRAINT PK_Products PRIMARY KEY(ProductID)
);
GO
He wants to get a list of products using their names, their sizes, and prices. He wants the list to be sorted by the acquired dates
but he does not want to see the acquired date column. What code
can he use to do that?
SELECT DateAcquired, Name, Size, UnitPrice FROM Products ORDER BY DateAcquired SET DateAcquired = NULL; GO
SELECT DateAcquired, Name, Size, UnitPrice FROM Products HIDE DateAcquired ORDER BY DateAcquired; GO
SELECT Name, Size, UnitPrice FROM Products ORDER BY DateAcquired; GO
SELECT Name, Size, UnitPrice ORDER BY DateAcquired FROM Products SET DateAcquired SHOW = OFF; GO
SELECT DateAcquired, Name, Size, UnitPrice SORT(DateAcquired) IS NULL FROM Products; GO
CREATE TABLE Products
(
ProductID int identity(1, 1),
Name nvarchar(50),
UnitPrice money
);
GO
The table already has a few records that were added previously. This
morning, to add a few records, Andrew writes the following code:
INSERT Products(Name, UnitPrice)
VALUES(N'Mid Lady Bag - Lizard', 228),
(N'Holly Gladiator Heel Shoes', 198),
(N'Short Black Skirt', 55.85);
GO
When he executes that
code, Andrew receives the following error:
Explicit value must be specified for identity column in table 'Products' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column.What must Andrew do to let the database engine generate a product number?
INSERT Products(ProductID, Name, UnitPrice)
VALUES(N'Mid Lady Bag - Lizard', 228),
(N'Holly Gladiator Heel Shoes', 198),
(N'Short Black Skirt', 55.85);
GO
CREATE TABLE Customers ( AccountNumber nchar(7), FirstName nvarchar(20), LastName nvarchar(20), PhoneNumber nvarchar(20), EmailAddress nvarchar(40) );Now he wants an index tied to that table. What code can he use to create the index?
CREATE INDEX IDX_Customers ON Customers SET IDX_Customers = AccountNumber;
CREATE INDEX IDX_Customers AS AccountNumber FROM Customers;
CREATE INDEX IDX_Customers ON Customers(AccountNumber);
SELECT AccountNumber FROM Customers CREATE INDEX IDX_Customers;
EXEC CREATE INDEX ON Customers(AccountNumber) = IDX_Customers;
CREATE TABLE Customers
(
CustomerID INT IDENTITY(1000, 1),
Name nvarchar(50),
[Phone Number] nvarchar(20),
CREATE PRIMARY KEY WITH CustomerID
);
GOCREATE TABLE Customers
(
CustomerID INT IDENTITY(1000, 1)
CONSTRAINT PK_Customers PRIMARY KEY(CustomerID),
Name nvarchar(50),
[Phone Number] nvarchar(20),
);
GOCREATE TABLE Customers
(
CustomerID INT IDENTITY(1000, 1) PRIMARY KEY,
Name nvarchar(50),
[Phone Number] nvarchar(20),
);
GOCREATE TABLE Customers
(
CustomerID INT IDENTITY(1000, 1),
Name nvarchar(50),
[Phone Number] nvarchar(20),
PRIMARY KEY REFERENCES(CustomerID)
);
GOCREATE TABLE Customers
(
CustomerID INT IDENTITY(1000, 1),
Name nvarchar(50),
[Phone Number] nvarchar(20),
CONSTRAINT PK_Customers PRIMARY KEY(CustomerID)
);
GOCREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus smallint,
HourlySalary money
);
GO
INSERT Personnel.Employees
VALUES(N'284-680', N'Anselme', N'Bongos', 2, 18.62),
(N'730-704', N'June', N'Malea', 1, 9.95),
(N'735-407', N'Frank', N'Monson', 3, 14.58),
(N'281-730', N'Jerry', N'Beaulieu', 1, 16.65);
GO
Hank also
has the following table of sales made by employees during a certain period:
CREATE TABLE Commercial.Sales
(
SaleID int identity(1, 1),
EmployeeNumber nchar(7) not null,
SaleDate date,
Amount money
);
GO
INSERT INTO Commercial.Sales(EmployeeNumber, SaleDate, Amount)
VALUES(N'284-680', N'2011-02-14', 4250),
(N'735-407', N'2011-02-14', 5300),
(N'730-704', N'2011-02-14', 2880),
(N'281-730', N'2011-02-14', 4640),
(N'284-680', N'2011-02-15', 4250),
(N'281-730', N'2011-02-15', 3675);
GO
Now,
Hank wants to get a list that displays the name of each employee and the
number of sales he or she made. What code can he use?
SELECT LastName + N', ' + FirstName Employee,
COUNT(EmployeeNumber) AS [Number of Sales]
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
GROUP BY LastName + N', ' + FirstNameSELECT LastName + N', ' + FirstName Employee,
COUNT(Amount) AS [Number of Sales]
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
GROUP BY LastName + N', ' + FirstNameSELECT LastName + N', ' + FirstName Employee,
COUNT(*) AS [Number of Sales]
GROUP BY LastName + N', ' + FirstName
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumberSELECT LastName + N', ' + FirstName Employee,
COUNT(*) AS [Number of Sales]
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
GROUP BY LastName + N', ' + FirstName
HAVING Amount NOT NULLSELECT LastName + N', ' + FirstName Employee,
COUNT(*) AS [Number of Sales]
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
GROUP BY LastName + N', ' + FirstName
WHERE Amount IS NOT NULLCREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(10) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus tinyint,
HourlySalary money
);
GO
INSERT Personnel.Employees
VALUES(N'284-680', N'Anselme', N'Bongos', 2, 18.62),
(N'730-704', N'June', N'Malea', 1, 9.95);
GO
To protect the table,
Mark
wants to create a view used for data entry. The view will be named NewHire.
The view must include a condition that states that the staus of the new
employee can be 1, 2, or 3 and no other number.
Mark wants to make sure no record is added to the table if that record
violates the condition in the view. What code can he use to accomplish that?
CREATE VIEW Personnel.NewHire
WITH CHECK OPTION
AS
SELECT EmployeeNumber,
FirstName,
LastName,
EmploymentStatus,
HourlySalary
FROM Personnel.Employees
WHERE EmploymentStatus IN(1, 2, 3); -- Full Time, Part Time, Unknown/Other
GOCREATE VIEW Personnel.NewHire
AS
WITH CHECK OPTION
SELECT EmployeeNumber,
FirstName,
LastName,
EmploymentStatus,
HourlySalary
FROM Personnel.Employees
WHERE EmploymentStatus IN(1, 2, 3); -- Full Time, Part Time, Unknown/Other
GOCREATE VIEW Personnel.NewHire
SET CHECK OPTION ON
AS
SELECT EmployeeNumber,
FirstName,
LastName,
EmploymentStatus,
HourlySalary
FROM Personnel.Employees
WHERE EmploymentStatus IN(1, 2, 3); -- Full Time, Part Time, Unknown/Other
GOCREATE VIEW Personnel.NewHire
AS
SELECT EmployeeNumber,
FirstName,
LastName,
EmploymentStatus,
HourlySalary
FROM Personnel.Employees
WHERE EmploymentStatus IN(1, 2, 3) -- Full Time, Part Time, Unknown/Other
WITH CHECK OPTION;
GOCREATE VIEW Personnel.NewHire
AS
SELECT EmployeeNumber,
FirstName,
LastName,
EmploymentStatus,
HourlySalary
FROM Personnel.Employees
CONSTRAINT CHECK EmploymentStatus IN(1, 2, 3); -- Full Time, Part Time, Unknown/Other
GOCREATE TABLE Employees ( EmployeeNumber nchar(60) not null unique primary key, [Full Name] nvarchar(50), HourlySalary money, Department nchar(4) )
CREATE TABLE Employees ( EmployeeNumber nchar(10) not null primary key, FirstName nvarchar(20), LastName nvarchar(20), DepartmentCode nchar(6), HourlySalary money ); GOThen you create the following view:
CREATE VIEW EmployeesRecords
AS
SELECT EmployeeNumber, FirstName, LastName
FROM Employees;
GO
Now you want to modify the view to add the HourlySalary field.
What code would you use to do that?
UPDATE VIEW EmployeesRecords
BEGIN
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Employees;
ENDALTER VIEW EmployeesRecords
AS
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Employees;
GOEXECUTE sp_change EmployeesRecords
BEGIN
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Employees;
ENDALTER VIEW EmployeesRecords
AS
ADD HourlySalary
FROM Employees;
ENDALTER VIEW EmployeesRecords
AS
ADD Employees.HourlySalary;
GOCREATE TABLE Members
(
MemberID int unique,
Name nvarchar(50),
MembershipStatus nvarchar(20)
CHECK(MembershipStatus IN (N'In Review', N'Active', N'Suspended'))
);
INSERT INTO Members
VALUES(100, N'Albert Welch', N'Active'),
(104, N'Daniel Simpson', N'Suspended'),
(264, N'Ann Plants', N'Active'),
(275, N'Jane Womack', N'In Review'),
(279, N'June Palau', N'Suspended'),
(288, N'Paul Motto', N'Active');
GO
He wants to remove all members who have been suspended from the
organization. What code can he use?
DELETE ALL * FROM Members WHERE MembershipStatus IS N'Suspended'; GO
DELETE FROM Members WHERE MembershipStatus != N'Suspended'; GO
REMOVE Members WHERE MembershipStatus = N'Suspended'; GO
EXECUTE sp_remove FROM Members WHERE MembershipStatus = N'Suspended'; GO
DELETE FROM Members WHERE MembershipStatus = N'Suspended'; GO
CREATE TABLE Departments
(
DepartmentCode nchar(6) not null primary key,
DepartmentName nvarchar(50) not null
);
GO
INSERT INTO Departments
VALUES(N'HMRS', N'Human Resources'),
(N'ACNT', N'Accounting'),
(N'PSNL', N'Personnel'),
(N'RSDV', N'Research & Development');
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(10) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
DepartmentCode nchar(6)
);
GO
INSERT INTO Employees
VALUES(N'283-947', N'Timothy', N'White', N'RSDV'),
(N'572-384', N'Jeannette', N'Welch', N'PSNL'),
(N'279-242', N'Ann', N'Welch', N'HMRS'),
(N'495-728', N'Robert', N'Simms', N'RSDV'),
(N'382-505', N'Paula', N'Waters', N'PSNL'),
(N'268-046', N'Martine', N'Nyamoto', N'ACNT'),
(N'773-148', N'James', N'Larsen', N'RSDV'),
(N'958-057', N'Peter', N'Aut', N'HMRS');
GO
She wants to
change the department of employees from the personnel department to the human
resources department. When the operation has been performed, she wants to
see the list of records that were affected. What code can she use?
UPDATE Employees SET DepartmentCode = N'PSNL' OUTPUT INSERTED.* WHERE DepartmentCode = N'HMRS'; GO
UPDATE Employees SET DepartmentCode = N'HMRS' OUTPUT INSERTED.* WHERE DepartmentCode = N'PSNL'; GO
UPDATE Employees SET DepartmentCode = N'PSNL' WHERE DepartmentCode = N'HMRS' OUTPUT DELETED.*; GO
SET Employees OUTPUT UPDATED.* UPDATE DepartmentCode = N'HMRS' WHERE DepartmentCode = N'PSNL'; GO
SET Employees UPDATE DepartmentCode = N'PSNL' WHERE DepartmentCode = N'HMRS' OUTPUT INSERTED.*; GO
CREATE TABLE StoreItems ( ItemNumber int, ItemName nvarchar(60), ItemDescription nvarchar(max), UnitPrice money ); GO
What two segment codes can be used to create three records (select 2)?
INSERT StoreItems VALUES(190857, N'Men Deodorant', 5.05); INSERT INTO StoreItems VALUES(838273, N'Currently on sale bar soaps', N'Sold as 6 bars', 1.95); INSERT StoreItems(ItemNumber, ItemName, ItemDescription) VALUES(828305, N'Cereal in a Jar', N'');
INSERT StoreItems VALUES(149752, N'Chocolate Bar', NULL, 75.00); INSERT INTO StoreItems(ItemNumber, ItemName, UnitPrice) VALUES(350882, N'1Gal Milk 2%', 3.85); INSERT StoreItems VALUES(247014, N'Peanut Butter Jar', N'Sold in 24 Units', 2.55);
INSERT StoreItems
VALUES(197084, N'Tomato Juice', 4.55),
(274859, N'Orange Juice', 8.95),
(927304, N'2-Litter Soda Bottle', 2.25);
INSERT StoreItems(ItemNumber, ItemName, UnitPrice)
VALUES(918839, N'Ground Beef', 6.55),
(829307, N'Tomato Sauce', 2.95);
INSERT StoreItems(ItemNumber, ItemName, ItemDescription)
VALUES(941155, N'12-Doughnuts Pack', N'On sale - must go');
CREATE DATABASE NationalBank;
GO
USE NationalBank;
GO
CREATE TABLE Employees
(
EmployeeNumber int,
FirstName nvarchar(20),
LastName nvarchar(20),
Salary decimal(20, 6)
);
GO
CREATE USER [Jeremy Blasick]
FOR LOGIN jblasick;
GO
GRANT UPDATE
ON OBJECT::Employees
TO [Jeremy Blasick];
GO
INSERT INTO Employees
VALUES(500727, N'John', N'Harrolds', 18.25);
GO
So you call Jeremy and ask him to change the record in the Employees table. After a few minutes, he calls you back saying he can't and he doesn't understand why. What do you think is the problem?
GRANT INSERT, UPDATE, SELECT TO [Kirk Blankey] ON OBJECT::Students; GO
GRANT CONNECT, INSERT, UPDATE, ON OBJECT::Students TO User = N'Kirk Blankey' WITH GRANT OPTION; GO
GRANT INSERT, UPDATE, SELECT ON OBJECT::Students TO [Kirk Blankey] WITH GRANT OPTION; GO
GRANT OPTION = ALL TO [Kirk Blankey] ON OBJECT::Students; GO
GRANT ALTER, CONNECT ON OBJECT::Students TO [Kirk Blankey] WITH OPTION GRANT ALL; GO
USE StateUniversity1; GO SELECT TeacherID, FullName, Teachers.CourseID FROM Teachers; GO
What will this statement produce?
| TeacherID | TeacherName | CourseCode |
| 218440 | Roberta Jerseys | CMST 385 |
| 250077 | Mary Shamberg | CMIS 101 |
| 270480 | Olympia Sumners | CMIS 320 |
| 274692 | Leslie Aronson | CMIS 170 |
| 294057 | Peter Sonnens | CMST 306 |
| 493748 | John Franks | CMIS 101 |
| 948025 | Chryssa Lurie | CMIS 320 |
| 972837 | Hellah Zanogh | CMST 306 |
SELECT * FROM Teachers WHERE CourseID = [CMST 320]; GO
SELECT TeacherID, TeacherName, CourseID FROM Teachers; GO
SELECT * FROM Teachers WHEN CourseID = N'CMIS 101'; GO
SELECT TeacherName FROM Teachers WHERE TeacherName = N'Leslie Aronson'; GO
SELECT * FROM Teachers WHERE CourseID = N'CMIS 101'; GO
SELECT CourseID, COUNT(*) FROM Teachers GROUP BY CourseID; GO
What will this statement produce?
| CourseID | CourseName | Credits |
| CMIS 101 | Introduction to Problem Solving and Algorithm Design | 3 |
| CMIS 170 | Introduction to XML | 3 |
| CMIS 320 | Relational Databases | 3 |
| CMIS 420 | Advanced Relational Databases | 3 |
| CMST 306 | Introduction to Visual Basic Programming | 3 |
| CMST 385 | Internet and Web Design | 3 |
| TeacherID | FullName |
| 218440 | Roberta Jerseys |
| 250077 | Mary Shamberg |
| 270480 | Olympia Sumners |
| 274692 | Leslie Aronson |
| 294057 | Peter Sonnens |
| 493748 | John Franks |
| 948025 | Chryssa Lurie |
| 972837 | Hellah Zanogh |
| CourseID | CourseName | Credits |
| 1 | 493748 | CMIS 101 |
| 2 | 270480 | CMIS 328 |
| 3 | 294057 | CMST 306 |
| 4 | 274692 | CMIS 170 |
| 5 | 274692 | CMIS 101 |
| 6 | 972837 | CMIS 320 |
| 7 | 250077 | CMIS 101 |
| 8 | 294057 | CMST 309 |
| 9 | 294057 | CMST 412 |
| 10 | 948025 | CMIS 320 |
| 11 | 972837 | CMST 306 |
| 12 | 270480 | CMIS 320 |
| 13 | 218440 | CMST 385 |
SELECT TeacherID, CourseID FROM TeachersAndCourses GROUP BY CourseID; GO
SELECT * FROM TeachersAndCourses WHERE CourseID = N'CMIS 328' GROUP BY CourseID; GO
SELECT CourseID, COUNT(*) FROM TeachersAndCourses GROUP BY CourseID; GO
SELECT TeacherID, COUNT(*) FROM TeachersAndCourses GROUP BY TeacherID; GO
SELECT TeacherID, COUNT(*) FROM TeachersAndCourses GROUP BY CourseID; GO
CREATE TABLE EmploymentTypes ( EmplTypeID int not null, EmplType nvarchar(20) ); GO CREATE TABLE Employees ( EmployeeNumber nchar(7) not null, EmplTypeID int, FirstName nvarchar(20), LastName nvarchar(20), HourlySalary money ); GO INSERT INTO EmploymentTypes(EmplTypeID, EmplType) VALUES(10, N'Employee'), (20, N'Contractor'), (40, N'Seasonal'), (60, N'Other'); GO INSERT INTO Employees(EmployeeNumber, EmplTypeID, FirstName, LastName, HourlySalary) VALUES(N'202-725', 20, N'Julie', N'Flanell', 36.55), (N'927-205', 10, N'Paulette', N'Simms', 26.65), (N'840-202', 40, N'Alexandra', N'Ulm', 12.85), (N'472-095', 10, N'Ellie', N'Tchenko', 11.95), (N'268-046', 60, N'Martine', N'Nyamoto', 15.52), (N'273-148', 20, N'James', N'Larsen', 18.24), (N'481-729', 10, N'Faye', N'Cross', 14.92); GOWhat will the following code produce?
SELECT EmplTypeID FROM Employees WHERE HourlySalary < ALL(SELECT AVG(HourlySalary) FROM Employees GROUP BY EmplTypeID); GO
CREATE SCHEMA Personnel;
GO
CREATE TABLE Personnel.Employees
(
EmplNbr nchar(10),
FirstName nvarchar(20),
LastName nvarchar(20),
Salary money,
FullTime bit
);
GO
INSERT INTO Personnel.Employees
VALUES(N'29730', N'Philippe', N'Addy', 20.05, 1),
(N'28084', N'Joan', N'Shepherd', 12.72, 0),
(N'79272', N'Joshua', N'Anderson', 18.26, 0),
(N'22803', N'Gregory', N'Swanson', 15.95, 0),
(N'83084', N'Josephine', N'Anderson', 22.25, 1);
GO
CREATE USER Hermine
FOR LOGIN hnkolo;
GO
GRANT INSERT
ON OBJECT::Personnel.Employees
TO Hermine;
GO
GRANT UPDATE
ON OBJECT::Personnel.Employees
TO Hermine;
GO
After executing the script, you let Hermine know that she can use the table.
After a few minutes, Hermine calls you and says that when she tries to create
records, she receives an error that she was denied the object:
CREATE VIEW Personnel.Contractors AS SELECT empl.EmployeeNumber, empl.[First Name], empl.[Last Name] FROM Personnel.Employees empl ORDER BY empl.[Last Name] GOWhen she executes the statement to create the view, she receives an error. What is wrong?
CREATE TABLE #Employees ( EmployeeNumber nchar(10) not null, [First Name] nvarchar(20), [Last Name] nvarchar(20) not null, Title nvarchar(40), Salary money ); GO CREATE VIEW Contractors AS SELECT EmployeeNumber, [First Name], [Last Name] FROM #Employees; GOWhen he executes the code, she receives an error. What do you think is the problem?
SELECT TeacherID, FullName, Teachers.CourseID FROM Teachers LEFT OUTER JOIN Courses ON Teachers.CourseID = Courses.CourseID; GO
SELECT TeacherID, FullName, Teachers.CourseID FROM Teachers CROSS OUTER JOIN Courses ON Teachers.CourseID = Courses.CourseID; GO
SELECT TeacherID, FullName, Teachers.CourseID FROM Teachers
SELECT Courses.CourseID, Courses.CourseName FROM Courses LEFT OUTER JOIN Teachers ON Teachers.CourseID = Courses.CourseID; GO
SELECT TeacherID, FullName, Teachers.CourseID FROM Teachers CROSS JOIN Courses
CREATE TABLE Departments ( DepartmentCode nchar(6) not null primary key, DepartmentName nvarchar(50) not null ); GO CREATE TABLE Employees ( EmployeeNumber nchar(10) not null primary key, FirstName nvarchar(20), LastName nvarchar(20), DepartmentCode nchar(6) ); GO
What would the following statement produce?
SELECT Employees.EmployeeNumber,
Employees.FirstName,
Employees.LastName,
Departments.DepartmentName
FROM Employees INNER JOIN Departments
ON Departments.DepartmentCode = Employees.DepartmentCode;
GO
CREATE TABLE Departments ( DepartmentCode nchar(6) not null primary key, DepartmentName nvarchar(50) not null ); GO CREATE TABLE Employees ( EmployeeNumber nchar(10) not null primary key, FirstName nvarchar(20), LastName nvarchar(20), DepartmentCode nchar(6) ); GO
What is the difference in result between this code:
SELECT Employees.EmployeeNumber,
Employees.FirstName,
Employees.LastName,
Departments.DepartmentName
FROM Employees INNER JOIN Departments
ON Departments.DepartmentCode = Employees.DepartmentCode;
GO
and this one?
SELECT Employees.EmployeeNumber,
Employees.FirstName,
Employees.LastName,
Departments.DepartmentName
FROM Employees JOIN Departments
ON Departments.DepartmentCode = Employees.DepartmentCode;
GO
CREATE TABLE Departments
(
DepartmentCode nchar(6) not null primary key,
DepartmentName nvarchar(50) not null
);
GO
INSERT INTO Departments
VALUES(N'HMRS', N'Human Resources'),
(N'ACNT', N'Accounting'),
(N'RSDV', N'Research & Development');
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(10) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
DepartmentCode nchar(6)
);
GO
INSERT INTO Employees
VALUES(N'283-947', N'Timothy', N'White', N'RSDV'),
(N'495-728', N'Robert', N'Simms', N'RSDV'),
(N'268-046', N'Martine', N'Nyamoto', N'ACNT'),
(N'273-148', N'James', N'Larsen', N'RSDV'),
(N'958-057', N'Peter', N'Aut', N'HMRS');
GO
What would the following code produce?
SELECT Employees.EmployeeNumber,
Employees.FirstName,
Employees.LastName,
Departments.DepartmentName
FROM Personnel.Employees JOIN Departments
ON Departments.DepartmentCode = Employees.DepartmentCode
WHERE Departments.DepartmentCode = N'RSDV';
GO
CREATE SCHEMA Management;
GO
CREATE SCHEMA Personnel;
GO
CREATE SCHEMA Transactions;
GO
GOCREATE TABLE Transactions.Customers
(
CustomerID int Identity(1, 1) NOT NULL,
DateCreated date,
AccountNumber nvarchar(20),
CustomerName nvarchar(50)
);
GO
CREATE TABLE Transactions.DatabaseOperations
(
OperationID int identity(1,1) NOT NULL,
ObjectName nvarchar(40),
PerformedBy nvarchar(50),
ActionPerformed nvarchar(50),
CONSTRAINT PK_DBOperations PRIMARY KEY(OperationID)
);
GO
CREATE TRIGGER Personnel.ForCustomers
ON Transactions.Customers
AFTER INSERT
AS
BEGIN
INSERT INTO Management.DatabaseOperations(ObjectName,
PerformedBy, ActionPerformed)
VALUES(N'Customers', SUSER_SNAME(), N'Processed a deposit')
END
GO
Frank executes that code and it works fine.INSERT INTO Transactions.Customers(DateCreated, AccountNumber, CustomerName) VALUES(N'02/20/2011', N'000-2860-3982', N'John Doe'); GOWhen he executes it, Gary receives an error. What do you think is the problem?
CREATE SCHEMA Listing;
GO
CREATE TABLE Listing.Apartments
(
UnitNumber int not null,
Bedrooms int,
Bathrooms real,
Price money,
Deposit money,
Available bit
);
GO
INSERT Listing.Apartments
VALUES(104, 2, 1.00, 1050.00, 300.00, 0),
(306, 3, 2.00, 1350.00, 425.00, 1),
(105, 1, 1.00, 885.00, 250.00, 1),
(202, 1, 1.00, 950.00, 325.00, 0),
(304, 2, 2.00, 1250.00, 300.00, 0),
(106, 3, 2.00, 1350.00, 425.00, 1),
(308, 0, 1.00, 875.00, 225.00, 1),
(203, 1, 1.00, 885.00, 250.00, 1),
(204, 2, 2.00, 1125.00, 425.00, 1),
(205, 1, 1.00, 1055.00, 350.00, 0);
GO
The documentation of the database indicates that the first symbol of
a unit number indicates the floor level. What two codes would let Martha see
the list of apartments from the second floor?
SELECT * FROM Units WHERE UnitNumber IN N'200' UP; GO
SELECT ALL * FROM Units WHERE UnitNumber LIKE N'2%'; GO
SELECT ALL * FROM Units WHERE UnitNumber FROM 200 TO 299; GO
SELECT ALL * FROM Units WHERE UnitNumber BETWEEN N'200' AND N'300'; GO
SELECT ALL * FROM UnitNumber FROM 200 TO 300; GO
CREATE TABLE Employees ( EmployeeNumber nchar(60) not null, [Full Name] nvarchar(50), HourlySalary money CHECK(HourlySalary !< 12.50), Department nchar(4) ); GO
CREATE TABLE Employees ( EmployeeNumber nchar(60) not null, [Full Name] nvarchar(50), HourlySalary money CONSTRAINT CHECK(HourlySalary >= 12.50), Department nchar(4) ); GO
CREATE TABLE Employees ( EmployeeNumber nchar(60) not null, [Full Name] nvarchar(50), HourlySalary money, Department nchar(4), CONSTRAINT CK_HourlySalary CHECK (HourlySalary >= 12.50) ); GO
CREATE TABLE Employees ( EmployeeNumber nchar(60) not null, [Full Name] nvarchar(50), HourlySalary money, Department nchar(4), CONSTRAINT CK_HourlySalary CHECK ON (HourlySalary >= 12.50) ); GO
CREATE TABLE Employees ( EmployeeNumber nchar(60) not null, [Full Name] nvarchar(50), HourlySalary money, Department nchar(4), CONSTRAINT ON HourlySalary FOR CHECK(HourlySalary >= 12.50) ); GO
CREATE TABLE Departments
(
Code nchar(4),
Name nvarchar(40)
);
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(6) not null unique,
[Full Name] nvarchar(50),
HourlySalary money,
Department nchar(4)
);
GO
INSERT Departments
VALUES(N'HMNR', N'Human Resources'), (N'ACNT', N'Accounting'),
(N'RNDV', N'Research & Development');
GO
INSERT Employees
VALUES(N'60-224', N'Frank Roberts', 20.15, N'RNDV'),
(N'29-742', N'Marcial Engolo', 12.58, N'HMNR'),
(N'82-073', N'John Duchant', 22.75, N'RNDV'),
(N'82-503', N'Marthe Mengue', 15.86, N'ACNT'),
(N'47-582', N'Hervey Arndt', 12.24, N'HMNR'),
(N'82-263', N'Mark Edwards', 18.14, N'RNDV');
GO
He is using the following code to get some statistics about the employees:
SELECT MAX(HourlySalary) FROM Employees empls WHERE empls.Department = N'RNDV'; GOWhat will that code produce?
CREATE TABLE Departments
(
Code nchar(4),
Name nvarchar(40)
);
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(6) not null unique,
[Full Name] nvarchar(50),
Department nchar(4)
);
GO
INSERT Departments
VALUES(N'HMNR', N'Human Resources'), (N'ACNT', N'Accounting'),
(N'RNDV', N'Research & Development');
GO
INSERT Employees
VALUES(N'60-224', N'Frank Roberts', N'RNDV'),
(N'29-742', N'Marcial Engolo', N'HMNR'),
(N'82-073', N'John Duchant', N'RNDV'),
(N'82-503', N'Marthe Mengue', N'ACNT'),
(N'47-582', N'Hervey Arndt', N'HMNR'),
(N'82-263', N'Mark Edwards', N'RNDV');
GO
He wants to know the number of employees in
the human resources department. Which one of the following codes can
he use?SELECT ALL COUNT(*) AS [# of Employees] FROM Employees empls WHERE empls.Department = N'HMNR'; GO
SELECT ALL COUNT(*) FROM Employees empls AS [# of Employees] WHERE empls.Department = N'HMNR'; GO
SELECT FROM Employees empls ALL COUNT(*) AS [# of Employees] WHERE empls.Department = N'HMNR'; GO
SELECT COUNT(*) AS [# of Employees] WHERE empls.Department = N'HMNR' FROM Employees empls; GO
SELECT WHERE empls.Department = N'HMNR' COUNT(*) AS [# of Employees] FROM Employees empls; GO
CREATE TABLE Employees
(
EmployeeNumber nchar(6) not null unique,
[Full Name] nvarchar(50),
HourlySalary money
);
GO
INSERT Employees
VALUES(N'60-224', N'Frank Roberts', 12.48),
(N'29-742', N'Marcial Engolo', 30.15),
(N'82-073', N'John Duchant', 8.75),
(N'82-503', N'Marthe Mengue', 14.85),
(N'47-582', N'Hervey Arndt', 10.06),
(N'82-263', N'Mark Edwards', 25.55);
GO
He wants to get the highest salary. What code can he use?
SELECT FROM Employees empls MAX(HourlySalary) AS [Highest Salary]; GO
SELECT FROM Employees empls HIGH(HourlySalary) AS [Highest Salary]; GO
SELECT MAX(HourlySalary) AS [Highest Salary] FROM Employees empls; GO
SELECT HIGH(HourlySalary) AS [Highest Salary] FROM Employees empls; GO
SELECT MAX(HourlySalary) FROM Employees empls AS [Highest Salary]; GO
CREATE TABLE Departments
(
Code nchar(4),
Name nvarchar(40)
);
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(6) not null unique,
[Full Name] nvarchar(50),
HourlySalary money,
Department nchar(4)
);
GO
INSERT Departments
VALUES(N'HMNR', N'Human Resources'), (N'ACNT', N'Accounting'),
(N'RNDV', N'Research & Development');
GO
INSERT Employees
VALUES(N'60-224', N'Frank Roberts', 20.15, N'RNDV'),
(N'29-742', N'Marcial Engolo', 12.58, N'HMNR'),
(N'82-073', N'John Duchant', 22.75, N'RNDV'),
(N'66-080', N'Mark Roberts', 10.12, N'HMNR'),
(N'82-503', N'Marthe Mengue', 15.86, N'ACNT'),
(N'47-582', N'Hervey Arndt', 12.24, N'HMNR'),
(N'82-263', N'Mark Edwards', 18.14, N'RNDV');
GO
He wants to find the highest salary in the human resources department.
What code can he use to get it?
SELECT MAX(HourlySalary) FROM Employees empl INNER JOIN Departments dept ON empl.Department = dept.Code WHERE dept.Code = N'RNDV'; GO
SELECT MAX(HourlySalary) FROM Employees empl INNER JOIN Departments dept ON empl.Department = dept.Code WHERE dept.Code = N'HMNR'; GO
SELECT MAX(HourlySalary) FROM Employees empl CROSS OUTER JOIN Departments dept ON empl.Department = dept.Code WHERE dept.Code = N'HMNR'; GO
SELECT HIGH(HourlySalary) FROM Employees empl INNER JOIN Departments dept ON empl.Department = dept.Code WHERE NOT dept.Code = N'RNDV'; GO
SELECT sp_high(HourlySalary) FROM Employees empl JOIN Departments dept ON empl.Department = dept.Code WHERE dept.Code = N'HMNR'; GO
CREATE TABLE Employees
(
EmployeeNumber nchar(6) not null unique,
[Full Name] nvarchar(50),
HourlySalary money,
Manager nchar(6)
);
GO
INSERT Employees
VALUES(N'60-224', N'Frank Roberts', 20.15, NULL),
(N'29-742', N'Marcial Engolo', 12.58, NULL),
(N'82-073', N'John Duchant', 22.74, N'29-742'),
(N'82-503', N'Marthe Mengue', 15.86, N'60-224'),
(N'44-440', N'Paul Motto', 16.22, N'29-742'),
(N'47-582', N'Hervey Arndt', 12.24, N'60-224'),
(N'82-263', N'Mark Edwards', 18.14, N'29-742');
GO
She wants to get the list of employees with the last column showing each employee's manager name.
What code would produce that list?
SELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
empl.HourlySalary AS Salary,
(SELECT mgr.[Full Name]
FROM Employees mgr
WHERE empl.Manager = mgr.EmployeeNumber) AS Manager
FROM Employees empl;
GOSELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
empl.HourlySalary AS Salary,
(SELECT mgr.EmployeeNumber, mgr.[Full Name]
FROM Employees mgr
WHERE empl.Manager = mgr.EmployeeNumber) AS Manager
FROM Employees empl;
GOSELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
empl.HourlySalary AS Salary,
(SELECT mgr.[Full Name]
FROM Employees mgr
WHERE empl.Manager = mgr.Manager) AS Manager
FROM Employees empl;
GOSELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
empl.HourlySalary AS Salary,
(SELECT mgr.EmployeeNumber
FROM Employees mgr
WHERE empl.Manager = mgr.EmployeeNumber) AS Manager
FROM Employees empl;
GOSELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
empl.HourlySalary AS Salary,
(SELECT mgr.[Full Name]
FROM Employees mgr
WHERE empl.[Full Name] = mgr.[Full Name]) AS Manager
FROM Employees empl;
GOCREATE TABLE Employees
(
EmployeeNumber nchar(6) not null unique,
[Full Name] nvarchar(50),
HourlySalary money,
Manager nchar(6)
);
GO
INSERT Employees
VALUES(N'60-224', N'Frank Roberts', 20.15, NULL),
(N'29-742', N'Marcial Engolo', 12.58, NULL),
(N'82-073', N'John Duchant', 22.74, N'29-742'),
(N'82-503', N'Marthe Mengue', 15.86, N'60-224'),
(N'44-440', N'Paul Motto', 16.22, N'29-742'),
(N'47-582', N'Hervey Arndt', 12.24, N'60-224'),
(N'82-263', N'Mark Edwards', 18.14, N'29-742');
GO
She wants to get the list of employees with the last column showing each employee's manager name
but the list must include only the employees who have a manager.
What code would produce that list?
SELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
empl.HourlySalary AS Salary,
(SELECT mgr.[Full Name]
FROM Employees mgr
WHERE empl.Manager = mgr.EmployeeNumber) AS Manager
FROM Employees empl
WHERE empl.Manager IS NOT NULL;
GOSELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
empl.HourlySalary AS Salary,
(SELECT mgr.[Full Name]
FROM Employees mgr
WHERE (empl.Manager = mgr.EmployeeNumber)
AND empl.Manager IS NOT NULL) AS Manager
FROM Employees empl;
GOSELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
empl.HourlySalary AS Salary,
(SELECT mgr.[Full Name]
FROM Employees mgr
WHERE empl.Manager = mgr.Manager) AS Manager IS NOT NULL
FROM Employees empl;
GOSELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
empl.HourlySalary AS Salary,
(SELECT mgr.EmployeeNumber
FROM Employees mgr
WHERE (empl.Manager = mgr.EmployeeNumber)
AND empl.Manager IS NOT NULL) AS Manager
FROM Employees empl;
GOSELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
empl.HourlySalary AS Salary,
(SELECT mgr.[Full Name] NOT NULL
FROM Employees mgr
WHERE empl.[Full Name] = mgr.[Full Name]) AS Manager
FROM Employees empl;
GOCREATE TABLE Employees
(
EmployeeNumber nchar(6) not null unique,
[Full Name] nvarchar(50),
Manager nchar(6)
);
GO
INSERT Employees
VALUES(N'60-224', N'Frank Roberts', NULL),
(N'29-742', N'Marcial Engolo', NULL),
(N'82-073', N'John Duchant', N'29-742'),
(N'82-503', N'Marthe Mengue', N'60-224'),
(N'44-440', N'Paul Motto', N'29-742'),
(N'47-582', N'Hervey Arndt', N'60-224'),
(N'82-263', N'Mark Edwards', N'29-742');
GO
To keep
employee's personal information private, she created an additional table that
contains employees salaries as follows:
CREATE TABLE Salaries
(
SalaryID int identity(1, 1) primary key,
EmployeeNumber nchar(6) not null,
HourlySalary money not null,
);
GO
INSERT Salaries(EmployeeNumber, HourlySalary)
VALUES(N'60-224', 20.15),
(N'29-742', 12.58),
(N'82-073', 22.74),
(N'82-503', 15.86),
(N'44-440', 16.22),
(N'47-582', 12.24),
(N'82-263', 18.14);
GO
Now,
Ann wants to see the list of employees so that each record shows an
employee's salary and his or her manager name. What code would produce that
result?
SELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
(SELECT sal.SalaryID, sal.HourlySalary
FROM Salaries sal
WHERE empl.EmployeeNumber = sal.EmployeeNumber) AS Salary,
(SELECT mgr.EmployeeNumber, mgr.[Full Name]
FROM Employees mgr
WHERE empl.Manager = mgr.EmployeeNumber) AS Manager
FROM Employees empl;
GOSELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
(SELECT sal.HourlySalary
FROM Salaries sal
WHERE empl.EmployeeNumber = sal.EmployeeNumber) AS Salary,
(SELECT mgr.[Full Name]
FROM Employees mgr
WHERE empl.Manager = mgr.EmployeeNumber) AS Manager
FROM Employees empl;
GOSELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
(SELECT sal.HourlySalary
FROM Salaries sal
WHERE empl.EmployeeNumber = sal.SalaryID) AS Salary,
(SELECT mgr.[Full Name]
FROM Employees mgr
WHERE empl.Manager = mgr.EmployeeNumber) AS Manager
FROM Employees empl;
GOSELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
(SELECT sal.EmployeeNumber
FROM Salaries sal
WHERE empl.EmployeeNumber = sal.EmployeeNumber) AS Salary,
(SELECT mgr.EmployeeNumber
FROM Employees mgr
WHERE empl.SalaryID = mgr.SalaryID) AS Manager
FROM Employees empl;
GOSELECT empl.EmployeeNumber AS [Empl #],
empl.[Full Name],
(SELECT sal.EmployeeNumber
FROM Salaries sal
WHERE empl.EmployeeNumber = sal.EmployeeNumber) AS Salary,
(SELECT mgr.EmployeeNumber
FROM Employees mgr
WHERE empl.Manager = mgr.EmployeeNumber) AS Manager
FROM Employees empl;
GOCREATE SCHEMA Personnel;
GO
CREATE TABLE Personnel.StartingSalaries
(
Category nvarchar(30) not null,
StartingSalary money null
);
INSERT INTO Personnel.StartingSalaries
VALUES(N'Base', 10.00),
(N'Intern', 12.35),
(N'Regular', 14.50),
(N'Manager', 20.00);
GO
John also has a table of employees as follows:
CREATE TABLE Personnel.Employees
(
EmployeeID int identity(1,1) NOT NULL,
EmployeeNumber nchar(10),
FirstName nvarchar(32),
LastName nvarchar(32) NOT NULL,
Title nvarchar(50),
HourlySalary money,
CONSTRAINT PK_Employees PRIMARY KEY (EmployeeID)
);
GO
INSERT INTO Personnel.Employees(EmployeeNumber, FirstName,
LastName, Title, HourlySalary)
VALUES(N'662-286', N'Lienev', N'Zbrnitz', N'Cashier', 15.75),
(N'487-525', N'Paulin', N'Guerrero', N'Intern', 10.85),
(N'395-138', N'Plant', N'Waste', N'Head Teller', 16.75),
(N'822-730', N'Steven', N'Chang', N'Intern', 14.15),
(N'930-717', N'Abedi', N'Kombo', N'Shift Leader', 10.02),
(N'573-048', N'Paul', N'Landsford', N'Cashier', 12.25);
GONow, John wants to get a list of employees whose salary is lower than
the intern's salary of the StartingSalaries table. What code can John use:
SELECT empl.*
FROM Personnel.Employees empl
WHERE empl.Title <= (SELECT Category
FROM Personnel.StartingSalaries sal);
GOSELECT empl.*
FROM Personnel.Employees empl
WHERE empl.HourlySalary <= (SELECT sal.Category
FROM Personnel.StartingSalaries sal
WHERE sal.StartingSalary = 12.35);
GOSELECT empl.*
FROM Personnel.Employees empl
WHERE empl.HourlySalary <= (SELECT sal.StartingSalary
FROM Personnel.StartingSalaries sal
WHERE sal.Category = N'Intern');
GOSELECT empl.EmployeeNumber,
empl.FirstName,
empl.LastName,
empl.Title,
(SELECT sal.StartingSalary
FROM Personnel.StartingSalaries sal
WHERE sal.Category = N'Intern')
FROM Personnel.Employees empl;
GOSELECT empl.EmployeeNumber,
empl.FirstName,
empl.LastName,
empl.Title,
(SELECT sal.Category
FROM Personnel.StartingSalaries sal
WHERE sal.StartingSalary = 12.3500)
FROM Personnel.Employees empl;
GOCREATE TABLE Departments
(
DepartmentCode nchar(6) not null primary key,
DepartmentName nvarchar(50) not null
);
GO
INSERT INTO Departments
VALUES(N'HMRS', N'Human Resources'),
(N'ACNT', N'Accounting'),
(N'PSNL', N'Personnel'),
(N'RSDV', N'Research & Development');
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(10) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
DepartmentCode nchar(6)
);
GO
INSERT INTO Employees
VALUES(N'283-947', N'Timothy', N'White', N'RSDV'),
(N'572-384', N'Jeannette', N'Welch', N'PSNL'),
(N'279-242', N'Ann', N'Welch', N'HMRS'),
(N'495-728', N'Robert', N'Simms', N'RSDV'),
(N'382-505', N'Paula', N'Waters', N'PSNL'),
(N'268-046', N'Martine', N'Nyamoto', N'ACNT'),
(N'773-148', N'James', N'Larsen', N'RSDV'),
(N'958-057', N'Peter', N'Aut', N'HMRS');
GO
He wants to move all employees from the personnel department to the human
resources department. Which of the following codes would produce the right
result?
UPDATE Employees SET DepartmentCode = N'PSNL' WHERE DepartmentCode = N'HMRS'; GO
UPDATE Employees SET DepartmentCode = N'HMRS' WHERE DepartmentCode = N'PSNL'; GO
UPDATE FROM Employees SET DepartmentCode = N'PSNL' WHERE DepartmentCode = N'HMRS'; GO
SET Employees UPDATE DepartmentCode = N'HMRS' WHERE DepartmentCode = N'PSNL'; GO
SET Employees UPDATE DepartmentCode = N'PSNL' WHERE DepartmentCode = N'HMRS'; GO
DROP ObsoleteProducts;
REMOVE ALL * FROM ObsoleteProducts;
DELETE * FROM ObsoleteProducts;
DELETE ObsoleteProducts;
EXECUTE sp_removerecords FROM ObsoleteProducts;
CREATE TABLE Employees ( EmployeeNumber nchar(10) not null primary key, FirstName nvarchar(20), LastName nvarchar(20), DepartmentCode nchar(6) );Imagine you want to provide your users with a view that shows the employees numbers and their name. What code can you use to create such a view?
CREATE VIEW EmployeesRecords BEGIN SELECT empl.EmployeeNumber, empl.FirstName, empl.LastName FROM Employees empl; END
CREATE VIEW EmployeesRecords AS SELECT empl.EmployeeNumber, empl.FirstName, empl.LastName FROM Employees empl;
CREATE VIEW EmployeesRecords RETURN TABLE AS SELECT empl.EmployeeNumber, empl.FirstName, empl.LastName FROM Employees empl;
CREATE VIEW EmployeesRecords1
WITH SELECT empl.EmployeeNumber, empl.FirstName, empl.LastName
FROM Employees empl;
ENDEXECUTE CREATE EmployeesRecords1 AS VIEW
SELECT empl.EmployeeNumber, empl.FirstName, empl.LastName
FROM Employees empl;CREATE TABLE Employees ( EmployeeNumber nchar(10) not null primary key, FirstName nvarchar(20), LastName nvarchar(20), DepartmentCode nchar(6) ); GONow you want to change the table to add a column named HourlySalary of type money. What code would you use to do that?
UPDATE TABLE Employees
BEGIN
ADD HourlySalary money;
ENDALTER TABLE Employees ADD HourlySalary money;
EXECUTE MODIFY TABLE Employees
AS
ADD HourlySalary money;
ENDEXECUTE sp_change TABLE Employees
AS
BEGIN
ADD HourlySalary money;
ENDALTER TABLE Employees
AS
BEGIN
ADD COLUMN HourlySalary money;
ENDCREATE TABLE Employees
(
FirstName nvarchar(20),
LastName nvarchar(20),
DepartmentCode nchar(6)
);
GO
Now you want to add a primary key column named EmployeeNumber
of type int. What two codes can you use to perform that operation?
WITH Employees
SET EmployeeNumber int not null PRIMARY KEY(EmployeeNumber);
GOALTER TABLE Employees
ADD EmployeeNumber int not null PRIMARY KEY;
GOALTER TABLE Employees
ADD EmployeeNumber int not null
CONSTRAINT PK_Employees PRIMARY KEY(EmployeeNumber);
GOUPDATE TABLE Employees
ADD COLUMN EmployeeNumber int not null PRIMARY KEY(EmployeeNumber);
GOALTER TABLE Employees
ADD EmployeeNumber int not null
ALTER EmployeeNumber AS PRIMARY KEY(EmployeeNumber);
GOSELECT ALL * FROM Employees WHERE LastName LIKE N'%a'; GO
SELECT ALL * FROM Employees WHERE LastName LIKE N'_a'; GO
SELECT ALL * FROM Employees WHERE LastName LIKE N'[a]'; GO
SELECT * FROM Employees WHERE LastName LIKE N'[^a]'; GO
SELECT ALL * FROM Employees WHERE LastName LIKE N'!a'; GO
CREATE TABLE Products
(
ItemNumber int primary key,
Name nvarchar(50),
UnitPrice money,
Discount decimal(4, 2)
);
Many records have been
added to the table. Some records have a value for the discount and some do
not. To get a list of products that do not have a discount, what code can
Alex use?
SELECT ItemNumber, Name, UnitPrice, Discount FROM Products WHERE Discount = 0; GO
SELECT ItemNumber, Name, UnitPrice, Discount FROM Products WHERE Discount = NULL; GO
SELECT * FROM Products WHERE Discount <> 0;
SELECT * FROM Products WHERE Discount NULL;
SELECT ItemNumber, Name, UnitPrice, Discount FROM Products WHERE Discount IS NULL;
CREATE VIEW Payroll
SET ENCRYPTION ON
AS
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Employees
GOCREATE VIEW Payroll
AS
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Employees;
ENCRYPT WHEN DONE
GOCREATE VIEW Payroll
WITH ENCRYPTION
AS
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Employees
GOCREATE VIEW Payroll
AS
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Employees;
WITH ENCRYPTION
GOCREATE VIEW Payroll
AS
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Employees
SET ENCRYPTION ON
GOSELECT ALL USERS FROM Personnel.Employees GRANT ALTER TO Peter;
GRANT ALTER ON OBJECT::Personnel.Employees TO Peter;
EXECUTE sp_grant(ALTER) TO Peter ON OBJECT::Personnel.Employees;
GRANT PERMISSION ALTER TO Peter ON OBJECT::Personnel.Employees;
SET PERMISSION ALTER ON OBJECT::Personnel.Employees TO Peter;
CREATE VIEW Personnel.Payroll
DO SCHEMA BINDING
AS
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Personnel.Employees
GOCREATE VIEW Personnel.Payroll
AS
WITH SCHEMA BINDING
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Personnel.Employees
GOCREATE VIEW Personnel.Payroll
FOR SCHEMABINDING
AS
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Personnel.Employees
GOCREATE VIEW Personnel.Payroll
WITH SCHEMABINDING
AS
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Personnel.Employees
GOCREATE VIEW Personnel.Payroll
AS
SELECT EmployeeNumber, FirstName, LastName, HourlySalary
FROM Personnel.Employees
SET SCHEMA BINDING ON
GOCREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus smallint,
HourlySalary money
);
GO
INSERT Personnel.Employees
VALUES(N'284-680', N'Anselme', N'Bongos', 2, 18.62),
(N'730-704', N'June', N'Malea', 1, 9.95);
(N'735-407', N'Frank', N'Monson', 3, 14.58),
(N'281-730', N'Jerry', N'Beaulieu', 1, 16.65);
GO
Harriett also
has the following table of sales made by employees during a certain period:
CREATE TABLE Commercial.Sales
(
SaleID int identity(1, 1),
EmployeeNumber nchar(7) not null,
SaleDate date,
Amount money
);
GO
INSERT INTO Commercial.Sales(EmployeeNumber, SaleDate, Amount)
VALUES(N'284-680', N'2011-02-14', 4250),
(N'735-407', N'2011-02-14', 5300),
(N'730-704', N'2011-02-14', 2880),
(N'281-730', N'2011-02-14', 4640),
(N'284-680', N'2011-02-15', 4250),
(N'281-730', N'2011-02-15', 3675),
(N'735-407', N'2011-02-15', 3420),
(N'730-704', N'2011-02-15', 3675),
(N'284-680', N'2011-02-16', 5500),
(N'281-730', N'2011-02-16', 2675),
(N'735-407', N'2011-02-16', 4400),
(N'730-704', N'2011-02-16', 2605);
GO
Now, Harriett
wants to see the highest sales made by employees but the list must include
only employees who sold over 4750. What code can she use?
SELECT LastName + N', ' + FirstName, MAX(Amount)
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
HAVING MAX(Amount) > 4750.00;
GROUP BY LastName + N', ' + FirstName
GOSELECT LastName + N', ' + FirstName, MAX(Amount)
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
GROUP BY LastName + N', ' + FirstName
HAVING SUM(Amount) > 4750.00;
GOSELECT LastName + N', ' + FirstName, MAX(Amount)
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
GROUP BY LastName + N', ' + FirstName
HAVING MAX(Amount) > 4750.00;
GOSELECT LastName + N', ' + FirstName, MAX(Amount)
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
GROUP BY LastName + N', ' + FirstName
WHERE Amount > 4750.00;
GOSELECT LastName + N', ' + FirstName, MAX(Amount)
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
GROUP BY LastName + N', ' + FirstName
HAVING MAX(Amount) > 4750.00
WHERE Amount IS NOT NULL;
GOCREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus smallint,
HourlySalary money
);
GO
INSERT Personnel.Employees
VALUES(N'284-680', N'Anselme', N'Bongos', 2, 18.62),
(N'730-704', N'June', N'Malea', 1, 9.95);
(N'735-407', N'Frank', N'Monson', 3, 14.58),
(N'281-730', N'Jerry', N'Beaulieu', 1, 16.65);
GO
He also
has the following table of sales made by employees during a certain period:
CREATE TABLE Commercial.Sales
(
SaleID int identity(1, 1),
EmployeeNumber nchar(7) not null,
SaleDate date,
Amount money
);
GO
INSERT INTO Commercial.Sales(EmployeeNumber, SaleDate, Amount)
VALUES(N'284-680', N'2011-02-14', 4250),
(N'735-407', N'2011-02-14', 5300),
(N'730-704', N'2011-02-14', 2880),
(N'281-730', N'2011-02-14', 4640),
(N'284-680', N'2011-02-15', 4250),
(N'281-730', N'2011-02-15', 3675);
GO
Charles wants to get the list employees so that each record shows the first
name, the last name and the numer of sales the employee made. The list must
show the number of sales in incremental order. What code can he use?
SELECT pe.LastName [First Name], pe.FirstName [Last Name],
COUNT(cs.Amount) AS [Number of Sales]
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
GROUP BY pe.LastName, pe.FirstName
ORDER BY [Number of Sales];SELECT pe.LastName [First Name], pe.FirstName [Last Name],
COUNT(*) AS [Number of Sales]
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
GROUP BY Amount
ORDER BY Amount;SELECT pe.LastName AS [First Name], pe.FirstName AS [Last Name],
COUNT(cs.Amount) AS [Number of Sales]
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
GROUP BY cs.Amount
HAVING cs..Amount
ORDER BY cs.Amount;SELECT pe.LastName AS [First Name], pe.FirstName AS [Last Name],
COUNT(*) AS [Number of Sales]
GROUP BY cs.Amount
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber
ORDER BY cs.Amount;SELECT pe.LastName AS [First Name], pe.FirstName AS [Last Name],
COUNT(cs.Amount) AS [Number of Sales]
ORDER BY cs.Amount
GROUP BY cs.Amount
FROM Commercial.Sales cs JOIN
Personnel.Employees pe ON
cs.EmployeeNumber = pe.EmployeeNumber;CREATE TABLE Contractors ( EmployeeID int identity(1, 1), FullName nvarchar(50), Wage money );Imagine you want to rename the last column from Wage to HourlySalary. What code would let you do that?
ALTER TABLE Contractors DELETE COLUMN EmploymentStatus; GO
ALTER TABLE Contractors SET EmploymentStatus = NULL; GO
UPDATE TABLE Contractors DELETE EmploymentStatus; GO
ALTER TABLE Contractors DROP COLUMN EmploymentStatus; GO
UPDATE TABLE Contractors SET EmploymentStatus = NULL; GO
CREATE TABLE Employees
(
[Empl #] nchar(7),
[First Name] nvarchar(20),
[Last Name] nvarchar(20),
[Hourly Salary] money
);
GO
CREATE TABLE Products
(
Number int,
Name nvarchar(50),
UnitPrice money,
);
GO
INSERT INTO Employees
VALUES(N'207-025', N'Julie', N'Flanell', 36.55),
(N'926-705', N'Paulette', N'Simms', 26.65),
(N'240-002', N'Alexandra', N'Ulm', 12.85),
(N'847-295', N'Ellie', N'Tchenko', 11.95);
GO
INSERT INTO Products
VALUES(217409, N'Short Black Skirt', 55.85),
(790279, N'Classic Fit Pinpoint Shirt', 82.00),
(284001, N'Pencil Skirt', 49.00);
GO
John wants
to see a list of employees mixed with products. The list should include only
products that cost more than 50.00. What code can he use?
SELECT [Empl #], [First Name], [Last Name], Name, UnitPrice FROM Employees, Products WHERE UnitPrice > 50; GO
SELECT empl.[Empl #], empl.[First Name], empl.[Last Name],
empl.Name, DISTINCT(empl.UnitPrice)
FROM Employees empl, Products prod
WHERE empl.UnitPrice > 50;
GOSELECT empl.[Empl #], empl.[First Name], empl.[Last Name],
prod.Name, prod.UnitPrice
FROM Employees empl INNER JOIN Products prod
ON empl.[Empl #] = prod.Number
HAVING prod.UnitPrice > 50;
GOSELECT empl.[Empl #], empl.[First Name], empl.[Last Name],
prod.Name, prod.UnitPrice
FROM Employees empl JOIN Products prod
ON empl.[Empl #] = prod.Number
GROUP BY prod.UnitPrice
HAVING prod.UnitPrice > 50;
GOSELECT empl.[Empl #], empl.[First Name], empl.[Last Name],
prod.Name, prod.UnitPrice
FROM Employees empl, Products prod
HAVING prod.UnitPrice > 50;
GOCREATE TABLE Employees ( EmployeeNumber nchar(7), [First Name] nvarchar(20), [Last Name] nvarchar(20), [Hourly Salary] money ); GOShe wants to create a table named Sales so that each record in the Sales table indicates the employee who made the sale. What two codes can she use to create the new table?
CREATE TABLE Sales
(
SaleID int IDENTITY(1, 1) PRIMARY KEY,
SaleDate date,
EmployeeNumber nchar(7),
ProductName nvarchar(60),
UnitPrice money,
CONSTRAINT FK_Employees FOREIGN KEY REFERENCES Employees(EmployeeNumber)
);CREATE TABLE Sales
(
SaleID int IDENTITY(1, 1) PRIMARY KEY,
SaleDate date,
EmployeeNumber nchar(7) FOREIGN KEY REFERENCES Employees(EmployeeNumber),
ProductName nvarchar(60),
UnitPrice money,
);CREATE TABLE Sales
(
SaleID int IDENTITY(1, 1) PRIMARY KEY,
SaleDate date,
EmployeeNumber nchar(7)
CONSTRAINT FK_Employees FOREIGN KEY REFERENCES Employees(EmployeeNumber),
ProductName nvarchar(60),
UnitPrice money,
);CREATE TABLE Sales
(
SaleID int IDENTITY(1, 1) PRIMARY KEY,
SaleDate date,
EmployeeNumber nchar(7)
CONSTRAINT FOREIGN KEY REFERENCES Employees(EmployeeNumber),
ProductName nvarchar(60),
UnitPrice money,
);CREATE TABLE Sales
(
SaleID int IDENTITY(1, 1) PRIMARY KEY,
SaleDate date,
EmployeeNumber nchar(7),
ProductName nvarchar(60),
UnitPrice money,
CREATE FOREIGN KEY WITH EmployeeNumber FROM Employees
);DROP INDEX IDX_Customers ON Customers(AccountNumber);
DELETE INDEX IDX_Customers ON Customers;
DROP INDEX IDX_Customers FROM Customers;
DROP INDEX IDX_Customers ON Customers;
DELETE INDEX IDX_Customers AccountNumber FROM Customers;
CREATE TABLE Employees
(
EmployeeNumber nchar(7) PRIMARY KEY,
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money
);
GO
CREATE TABLE Sales
(
SaleID int IDENTITY(1, 1) PRIMARY KEY,
SaleDate date,
ProductName nvarchar(60),
UnitPrice money
);
GO
Now he wants to add a column to the Sales table so that the new field gets
its values from the Employees table. How can he write code to do that?
ALTER TABLE Sales ADD FOREIGN KEY EmployeeNumber nchar(7) FOR Employees(EmployeeNumber);
UPDATE TABLE Sales ADD COLUMN EmployeeNumber nchar(7) FOREIGN KEY Employees(EmployeeNumber); GO
CHANGE TABLE Sales ADD EmployeeNumber nchar(7) FOREIGN KEY Employees(EmployeeNumber); GO
UPDATE TABLE Sales ADD FOREIGN KEY AS EmployeeNumber nchar(7) REFERENCES EmployeeNumber FROM Employees;
ALTER TABLE Sales ADD EmployeeNumber nchar(7) FOREIGN KEY REFERENCES Employees(EmployeeNumber);
CREATE DATATYPE Integer FROM int;
EXECUTE sp_createtype Integer AS Natural;
CREATE TYPE SET Integer = int;
CREATE OBJECT:TYPE Integer FROM int;
CREATE TYPE Integer FROM int;
CREATE TABLE Customers
(
CustomerID int identity(1, 1),
FullName nvarchar(50),
PhoneNumber nvarchar(20)
)
WITH COLLATE SQL_Latin1_General_CP1_CI_AS;WITH COLLATE SQL_Latin1_General_CP1_CI_AS
BEGIN
CREATE TABLE Customers
(
CustomerID int identity(1, 1),
FullName nvarchar(50),
PhoneNumber nvarchar(20)
)
END;
CREATE TABLE Customers
(
CustomerID int identity(1, 1),
FullName nvarchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS,
PhoneNumber nvarchar(20)
);
CREATE TABLE Customers
(
CustomerID int identity(1, 1),
FullName nvarchar(50) WITH COLLATE SQL_Latin1_General_CP1_CI_AS,
PhoneNumber nvarchar(20)
);
CREATE TABLE Customers
(
CustomerID int identity(1, 1),
FullName nvarchar(50),
PhoneNumber nvarchar(20),
CONSTRAINT CT_Customers COLLATE SQL_Latin1_General_CP1_CI_AS
);
GRANT INSERT, UPDATE ON OBJECT::Sales.Customers TO [James Galvin]; GO
GRANT INSERT, UPDATE TO [James Galvin]; ON OBJECT::Sales.Customers GO
SET GRANT INSERT, UPDATE ON OBJECT::Sales.Customers TO N'James Galvin'; GO
GRANT INSERT AND UPDATE FOR OBJECT::Sales.Customers TO [James Galvin]; GO
WITH GRANT INSERT, UPDATE SET OBJECT::Sales.Customers TO [James Galvin]; GO
GRANT CREATE DATABASES TO jpalau;
FOR ANY DATABASE GRANT CREATE TO jpalau;
WITH OBJECT::jpalau GRANT CREATE ANY DATABASE;
GRANT CREATE ANY DATABASE TO jpalau;
EXECUTE CREATE ANY DATABASE FOR USER::jpalau;
WITH gsanders, hnorm GRANT CREATE ANY DATABASE, ALTER ANY LOGIN; GO
GRANT CREATE ANY DATABASE, ALTER ANY LOGIN TO gsanders, hnorm; GO
GRANT PERMISSION::CREATE ANY DATABASE, PERMISSION::ALTER ANY LOGIN TO gsanders, hnorm; GO
GRANT PERMISSION(CREATE ANY DATABASE, ALTER ANY LOGIN) TO OBJECT::gsanders; GO GRANT PERMISSION(CREATE ANY DATABASE, ALTER ANY LOGIN) TO OBJECT::hnorm; GO
EXECUTE GRANT PERMISSION SET CREATE ANY DATABASE = TRUE SET ALTER ANY LOGIN = TRUE TO OBJECT::gsanders; GO EXECUTE GRANT PERMISSION SET CREATE ANY DATABASE = TRUE SET ALTER ANY LOGIN = TRUE TO OBJECT::hnorm; GO
CREATE TABLE Products
(
ProductCode nchar(6) not null,
Name nvarchar(50) not null,
UnitPrice money not null,
CONSTRAINT PK_Products PRIMARY KEY(ProductCode)
);
When you add a few records, you want to immediately see
the list of records that were added. What example of code would do that?
INSERT Products
VALUES(N'293804', N'Mid Lady Bag - Lizard', 228),
(N'400571', N'Holly Gladiator Heel Shoes', 198)
OUTPUT inserted.*;INSERT Products
VALUES(N'293804', N'Mid Lady Bag - Lizard', 228),
(N'400571', N'Holly Gladiator Heel Shoes', 198)
SHOW OUTPUT;INSERT Products
OUTPUT inserted.*
VALUES(N'293804', N'Mid Lady Bag - Lizard', 228),
(N'400571', N'Holly Gladiator Heel Shoes', 198);INSERT Products
SELECT VALUES(N'293804', N'Mid Lady Bag - Lizard', 228),
(N'400571', N'Holly Gladiator Heel Shoes', 198);WHEN INSERT Products
VALUES(N'293804', N'Mid Lady Bag - Lizard', 228),
(N'400571', N'Holly Gladiator Heel Shoes', 198)
GO TO OUTPUT INSERT;CREATE TABLE Products
(
ProductID int AUTONUMBER,
Name nvarchar(50),
UnitPrice money
);
GOCREATE TABLE Products
(
ProductID int COUNTER,
Name nvarchar(50),
UnitPrice money
);
GOCREATE TABLE Products
(
ProductID int AUTOINCREMENT,
Name nvarchar(50),
UnitPrice money
);
GOCREATE TABLE Products
(
ProductID int IDENTITY(1, 1),
Name nvarchar(50),
UnitPrice money
);
GOCREATE TABLE Products
(
ProductID int,
Name nvarchar(50),
UnitPrice money,
CONSTRAINT AI_Products IDENTITY(ProductID)
);
GOCREATE TABLE Products
(
ProductID int identity(1, 1),
Name nvarchar(50),
UnitPrice money
);
GO
Diane wants to add a new record but she wants to
specify the product number. What code can she use to create the table?
SET IDENTITY_INSERT Products ON;
GO
INSERT Products(ProductID, Name, UnitPrice)
VALUES(1002, N'Mid Lady Bag - Lizard', 228),
(84, N'Holly Gladiator Heel Shoes', 198),
(519, N'Short Black Skirt', 55.85);
GOWITH IDENTITY_INSERT ON Products;
GO
INSERT Products(ProductID, Name, UnitPrice)
VALUES(1002, N'Mid Lady Bag - Lizard', 228),
(84, N'Holly Gladiator Heel Shoes', 198),
(519, N'Short Black Skirt', 55.85);
GOWITH AUTOINCREMENT = FALSE;
GO
INSERT Products(ProductID, Name, UnitPrice)
VALUES(1002, N'Mid Lady Bag - Lizard', 228),
(84, N'Holly Gladiator Heel Shoes', 198),
(519, N'Short Black Skirt', 55.85);
GOSET IDENTITY ON Products = NULL;
GO
INSERT Products(ProductID, Name, UnitPrice)
VALUES(1002, N'Mid Lady Bag - Lizard', 228),
(84, N'Holly Gladiator Heel Shoes', 198),
(519, N'Short Black Skirt', 55.85);INSERT Products(ProductID, Name, UnitPrice)
WITH IDENTITY_INSERT = TRUE
VALUES(1002, N'Mid Lady Bag - Lizard', 228),
(84, N'Holly Gladiator Heel Shoes', 198),
(519, N'Short Black Skirt', 55.85);CREATE TABLE Products
(
ProductID int identity(1, 1) not null,
Name nvarchar(50),
Size nvarchar(32),
UnitPrice money,
DiscountRate decimal(4, 2),
CONSTRAINT PK_Products PRIMARY KEY(ProductID)
);
Justin wants to get a list of product names, their sizes and prices. He also
wants the list to be sorted alphabetically according to the names. What code
can he use to do that?
SELECT Name, Size, UnitPrice FROM Products SORT(Name); GO
SELECT SORT(Name), Size, UnitPrice FROM Products; GO
SELECT Name, Size, UnitPrice ORDER BY Name FROM Products; GO
SELECT Name, Size, UnitPrice FROM Products ORDER BY Name; GO
SELECT Name, Size, UnitPrice SET SORT FOR Name FROM Products; GO
CREATE TABLE Products
(
ProductID int identity(1, 1) not null,
DateAcquired date,
Name nvarchar(50),
Size nvarchar(32),
UnitPrice money,
DiscountRate decimal(4, 2),
CONSTRAINT PK_Products PRIMARY KEY(ProductID)
);
GO
INSERT Products(DateAcquired, Name, UnitPrice)
VALUES(N'2011-12-06', N'Mid Lady Bag - Lizard', 228),
(N'2010-08-09', N'Midnight Floral Cardigan', 78),
(N'2011-10-12', N'Zip Front Sheath Dress', 138),
(N'2010-05-24', N'Holly Gladiator Heel Shoes', 198),
(N'2011-02-16', N'Short Black Skirt', 55.85);
GO
Linette wants to get a list of products using with the date they were
acquired, their names, their sizes and prices. He also
wants the list to be sorted by the acquired dates from the most recent to
the oldest item. What code
can he use to do that?
SELECT DateAcquired, Name, Size, UnitPrice FROM Products ORDER BY DateAcquired ASC; GO
SELECT DateAcquired, Name, Size, UnitPrice FROM Products ORDER BY DateAcquired DESC; GO
SELECT DateAcquired, Name, Size, UnitPrice SORT(DateAcquired) ASCENDING FROM Products; GO
SELECT DateAcquired, Name, Size, UnitPrice FROM Products ORDER BY DateAcquired DESCENDING; GO
SELECT DateAcquired, Name, Size, UnitPrice SET SORT FOR DateAcquired ASC FROM Products; GO
CREATE TABLE Products
(
ProductCode nchar(6) not null,
DateAcquired date DEFAULT GETDATE(),
Name nvarchar(50),
Size nvarchar(32),
UnitPrice money,
DiscountRate decimal(4, 2),
CONSTRAINT PK_Products PRIMARY KEY(ProductCode)
);
GO
INSERT Products(ProductCode, Name, Size, UnitPrice)
VALUES(N'274978', N'Mid Lady Bag - Lizard', N'14', 228),
(N'827480', N'Midnight Floral Cardigan', N'12', 78),
(N'183518', N'Zip Front Sheath Dress', N'Small', 138),
(N'384680', N'Holly Gladiator Heel Shoes', N'7.5', 198),
(N'247008', N'Short Black Skirt', N'Medium', 55.85);
GO
Now he wants
to copy all the records and put them in a new table named Sales. What code can he use to
do that?
SELECT FROM Products INTO Sales; GO
COPY * FROM Products INTO Sales; GO
GET ALL * INTO Sales FROM Products; GO
WITH Products SELECT * INTO Sales; GO
SELECT ALL * INTO Sales FROM Products; GO
CREATE TABLE Departments
(
DepartmentCode nchar(6) not null primary key,
DepartmentName nvarchar(50) not null
);
GO
INSERT INTO Departments
VALUES(N'HMRS', N'Human Resources'),
(N'ACNT', N'Accounting'),
(N'PSNL', N'Personnel'),
(N'RSDV', N'Research & Development');
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(10) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus nvarchar(32),
DepartmentCode nchar(6)
);
GO
INSERT INTO Employees
VALUES(N'283-947', N'Timothy', N'White', N'Part Time', N'RSDV'),
(N'572-384', N'Jeannette', N'Welch', N'Part Time', N'PSNL'),
(N'279-242', N'Ann', N'Welch', N'Full Time', N'HMRS'),
(N'495-728', N'Robert', N'Simms', N'Part Time', N'RSDV'),
(N'382-505', N'Paula', N'Waters', N'Part Time', N'PSNL'),
(N'958-057', N'Peter', N'Aut', N'Part Time', N'HMRS'),
(N'268-046', N'Martine', N'Nyamoto', N'Part Time', N'ACNT'),
(N'400-752', N'James', N'Palau', N'Full Time', N'HMRS'),
(N'773-148', N'James', N'Larsen', N'Part Time', N'RSDV');
GO
What code
can Ade use to get a list of full-time employees from the human resources
department?
SELECT * FROM Employees WHERE (EmploymentStatus = N'Full Time') AND (DepartmentCode = N'HMRS'); GO
SELECT * FROM Employees WHERE (EmploymentStatus = N'Full Time') OR (DepartmentCode = N'HMRS'); GO
WITH (EmploymentStatus = N'Full Time') OR (DepartmentCode = N'HMRS') SELECT * FROM Employees; GO
WHERE (EmploymentStatus = N'Full Time') AND (DepartmentCode IN N'HMRS'); SELECT * FROM Employees GO
WHERE (EmploymentStatus = N'Full Time') OR (DepartmentCode = N'HMRS'); SELECT * FROM Employees GO
CREATE TABLE Departments
(
DepartmentCode nchar(6) not null primary key,
DepartmentName nvarchar(50) not null
);
GO
INSERT INTO Departments
VALUES(N'HMRS', N'Human Resources'),
(N'ACNT', N'Accounting'),
(N'PSNL', N'Personnel'),
(N'RSDV', N'Research & Development');
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(10) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus nvarchar(32),
DepartmentCode nchar(6)
);
GO
INSERT INTO Employees
VALUES(N'283-947', N'Timothy', N'White', N'Part Time', N'RSDV'),
(N'572-384', N'Jeannette', N'Welch', N'Part Time', N'PSNL'),
(N'279-242', N'Ann', N'Welch', N'Full Time', N'HMRS'),
(N'495-728', N'Robert', N'Simms', N'Part Time', N'RSDV'),
(N'382-505', N'Paula', N'Waters', N'Part Time', N'PSNL'),
(N'958-057', N'Peter', N'Aut', N'Part Time', N'HMRS'),
(N'268-046', N'Martine', N'Nyamoto', N'Part Time', N'ACNT'),
(N'400-752', N'James', N'Palau', N'Full Time', N'HMRS'),
(N'773-148', N'James', N'Larsen', N'Part Time', N'RSDV');
GO
What code
can he use to get a list of all part-time employees regardless of their
departments and all employees of the the Personnel department regardless of
their employment status?
SELECT * FROM Employees WHERE (EmploymentStatus = N'Part Time') AND (DepartmentCode = N'PSNL'); GO
WHEN (EmploymentStatus = N'Part Time') AND (DepartmentCode = N'HMRS') SELECT * FROM Employees; GO
SELECT * FROM Employees WHERE (EmploymentStatus = N'Part Time') OR (DepartmentCode = N'PSNL'); GO
WHEN (EmploymentStatus = N'Part Time') OR (DepartmentCode IN N'HMRS'); SELECT * FROM Employees GO
SELECT * FROM Employees WITH (EmploymentStatus = N'Part Time') AND (DepartmentCode = N'HMRS'); GO
CREATE TABLE Departments
(
DepartmentCode nchar(6) not null primary key,
DepartmentName nvarchar(50) not null
);
GO
INSERT INTO Departments
VALUES(N'HMRS', N'Human Resources'),
(N'ACNT', N'Accounting'),
(N'PSNL', N'Personnel'),
(N'RSDV', N'Research & Development');
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(10) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus nvarchar(32),
DepartmentCode nchar(6)
);
GO
INSERT INTO Employees
VALUES(N'283-947', N'Timothy', N'White', N'Part Time', N'RSDV'),
(N'572-384', N'Jeannette', N'Welch', N'Part Time', N'PSNL'),
(N'279-242', N'Ann', N'Welch', N'Full Time', N'HMRS'),
(N'495-728', N'Robert', N'Simms', N'Part Time', N'RSDV'),
(N'382-505', N'Paula', N'Waters', N'Part Time', N'PSNL'),
(N'958-057', N'Peter', N'Aut', N'Part Time', N'HMRS'),
(N'268-046', N'Martine', N'Nyamoto', N'Part Time', N'ACNT'),
(N'400-752', N'James', N'Palau', N'Full Time', N'HMRS'),
(N'773-148', N'James', N'Larsen', N'Part Time', N'RSDV'),
(N'208-255', N'William', N'Aula', N'Full Time', N'PSNL');
GO
He wants to get a list of part-time employees whose last name start with w.
What code can he write to get that list?
SELECT * FROM Employees WHERE (EmploymentStatus = N'Part Time') OR (LastName LIKE N'w%'); GO
WHEN (EmploymentStatus = N'Part Time') AND (LastName LIKE N'w%') SELECT * FROM Employees; GO
WHEN (EmploymentStatus = N'Part Time') OR (LastName LIKE N'w%'); SELECT * FROM Employees GO
SELECT * FROM Employees WHERE (EmploymentStatus = N'Part Time') AND (LastName LIKE N'w%'); GO
SELECT * FROM Employees WITH (EmploymentStatus = N'Part Time') AND (LastName LIKE N'w%'); GO
CREATE TABLE Departments
(
DepartmentCode nchar(6) not null primary key,
DepartmentName nvarchar(50) not null
);
GO
INSERT INTO Departments
VALUES(N'HMRS', N'Human Resources'),
(N'ACNT', N'Accounting'),
(N'PSNL', N'Personnel'),
(N'RSDV', N'Research & Development');
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(10) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus nvarchar(32),
DepartmentCode nchar(6)
);
GO
INSERT INTO Employees
VALUES(N'283-947', N'Timothy', N'White', N'Part Time', N'RSDV'),
(N'572-384', N'Jeannette', N'Welch', N'Part Time', N'PSNL'),
(N'279-242', N'Ann', N'Welch', N'Full Time', N'HMRS'),
(N'495-728', N'Robert', N'Simms', N'Part Time', N'RSDV'),
(N'382-505', N'Paula', N'Waters', N'Part Time', N'PSNL'),
(N'958-057', N'Peter', N'Aut', N'Part Time', N'HMRS'),
(N'268-046', N'Martine', N'Nyamoto', N'Part Time', N'ACNT'),
(N'400-752', N'James', N'Palau', N'Full Time', N'HMRS'),
(N'773-148', N'James', N'Larsen', N'Part Time', N'RSDV'),
(N'208-255', N'William', N'Aula', N'Full Time', N'PSNL');
GO
He wants to get a list of
full-time employees of the human resources department and the part time
employees of the personnel department.
What code can he use to get that result?
SELECT * FROM Employees
WHERE ((EmploymentStatus = N'Full Time') OR (DepartmentCode = N'HMRS'))
AND
((EmploymentStatus = N'Part Time') OR (DepartmentCode = N'PSNL'));
GOSELECT * FROM Employees
WHERE ((EmploymentStatus = N'Full Time') AND (DepartmentCode = N'HMRS'))
OR
((EmploymentStatus = N'Part Time') AND (DepartmentCode = N'PSNL'));
GOSELECT * FROM Employees
WHERE ((EmploymentStatus = N'Full Time') AND (DepartmentCode = N'HMRS'))
WITH
((EmploymentStatus = N'Part Time') AND (DepartmentCode = N'PSNL'));
GOSELECT * FROM Employees
WHERE ((EmploymentStatus = N'Full Time') OR (DepartmentCode = N'HMRS'))
OR
((EmploymentStatus = N'Part Time') OR (DepartmentCode = N'PSNL'));
GOSELECT * FROM Employees
WHERE ((EmploymentStatus = N'Full Time') AND (DepartmentCode = N'HMRS'))
AND
((EmploymentStatus = N'Part Time') AND (DepartmentCode = N'PSNL'));
GO| Column Name | Data Type | Size |
| EmployeeID | int | |
| FirstName | nvarchar | 20 |
| LastName | nvarchar | 20 |
| EmploymentStatus | nvarchar | 32 |
CREATE TABLE Employees
(
EmployeeID int unique,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus nvarchar(32)
SET EmploymentStatus(N'Full Time', N'Part Time', N'Unknown')
);
GOCREATE TABLE Employees
(
EmployeeID int unique,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus nvarchar(32)
)WITH EmploymentStatus AS (N'Full Time', N'Part Time', N'Unknown');
GO
CREATE TABLE Employees
(
EmployeeID int unique,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus nvarchar(32),
CONSTRAINT FOR EmploymentStatus IN(N'Full Time', N'Part Time', N'Unknown'))
);
GOCREATE TABLE Employees
(
EmployeeID int unique,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus nvarchar(32) SET AS (N'Full Time', N'Part Time', N'Unknown')
);
GOCREATE TABLE Employees
(
EmployeeID int unique,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus nvarchar(32)
CHECK(EmploymentStatus IN(N'Full Time', N'Part Time', N'Unknown'))
);
GOCREATE TABLE Employees
(
EmployeeID int unique,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus nvarchar(32)
CHECK(EmploymentStatus IN(N'Full Time', N'Part Time', N'Unknown'))
);
GO
INSERT INTO Employees
VALUES(10, N'Timothy', N'White', N'Part Time'),
(50, N'Jeannette', N'Welch', N'Part Time'),
(36, N'Ann', N'Welch', N'Full Time'),
(60, N'Robert', N'Simms', N'Part Time'),
(20, N'Paula', N'Waters', N'Part Time'),
(80, N'Peter', N'Aut', N'Part Time'),
(30, N'Martine', N'Nyamoto', N'Part Time'),
(24, N'James', N'Palau', N'Full Time'),
(53, N'James', N'Larsen', N'Part Time'),
(15, N'William', N'Aula', N'Full Time');
GO
Now he wants to get a list of employees using their IDs from 20 to 40.
What statement can help him get that result?
SELECT * FROM Employees WHERE EmployeeID BETWEEN 20 AND 40; GO
SELECT * FROM Employees WHERE EmployeeID IN(20, 40); GO
SELECT * FROM Employees WHERE (EmployeeID >= 20) AND (EmployeeID >= 40); GO
SELECT * FROM Employees WHERE EmployeeID IN (20 TO 40); GO
SELECT * FROM Employees WHERE EmployeeID FROM 20 TO 40; GO
CREATE TABLE Employees
(
EmployeeNumber nchar(6) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20) not null
);
GO
He wants to create another table named Sales that has a column named
EmployeeNumber whose values would come from the EmployeeNumber of the
Employees table. To prevent people from breaking the relationships among records,
he wants to make sure that when a record is deleted from the Employees table,
the database engine would display an error. How must
he create the new table?
CREATE TABLE Sales
(
SaleCode nchar(10) not null primary key,
SaleDate date not null,
EmployeeNumber nchar(6)
CONSTRAINT FK_Employees FOREIGN KEY
REFERENCES Employees(EmployeeNumber),
Amount money
)ON DELETE CASCADE ERROR;
GOCREATE TABLE Sales
(
SaleCode nchar(10) not null primary key,
SaleDate date not null,
EmployeeNumber nchar(6) FOREIGN KEY
REFERENCES Employees(EmployeeNumber),
Amount money
)ON DELETE SET NULL;
GOCREATE TABLE Sales
(
SaleCode nchar(10) not null primary key,
SaleDate date not null,
EmployeeNumber nchar(6)
CONSTRAINT FK_Employees FOREIGN KEY
REFERENCES Employees(EmployeeNumber)
ON DELETE NO ACTION,
Amount money
);CREATE TABLE Sales
(
SaleCode nchar(10) not null primary key,
SaleDate date not null,
EmployeeNumber nchar(6) FOREIGN KEY
REFERENCES Employees(EmployeeNumber)
ON DELETE SHOW ERROR,
Amount money
);
GOCREATE TABLE Sales
(
SaleCode nchar(10) not null primary key,
SaleDate date not null,
EmployeeNumber nchar(6) FOREIGN KEY
REFERENCES Employees(EmployeeNumber),
Amount money
);
WITH DELETE SET REFERENCE ERROR
GOCREATE TABLE Employees
(
EmployeeNumber nchar(6) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20) not null
);
GO
Now she is creating a Products table that will contain a column that uses some
values from the employees table. If a record of the Employees table is updated,
she wants to display an error. How should she create the Products table?
CREATE TABLE Products
(
ProductCode nchar(8) primary key,
EmployeeNumber nchar(6) FOREIGN KEY REFERENCES Employees(EmployeeNumber)
ON UPDATE SHOW ERROR,
DateAcquired date,
Name nvarchar(60),
UnitPrice money
);
GOCREATE TABLE Products
(
ProductCode nchar(8) primary key,
EmployeeNumber nchar(6) FOREIGN KEY REFERENCES Employees(EmployeeNumber),
DateAcquired date,
Name nvarchar(60),
UnitPrice money
)ON UPDATE CASCADE ERROR;
GODROP TABLE Products;
GO
CREATE TABLE Products
(
ProductCode nchar(9) primary key,
EmployeeNumber nchar(6) FOREIGN KEY REFERENCES Employees(EmployeeNumber)
ON UPDATE SET NULL,
DateAcquired date,
Name nvarchar(60),
UnitPrice money
);
GOCREATE TABLE Products
(
ProductCode nchar(9) primary key,
EmployeeNumber nchar(6) FOREIGN KEY REFERENCES Employees(EmployeeNumber)
ON UPDATE NO ACTION,
DateAcquired date,
Name nvarchar(60),
UnitPrice money
);
GOCREATE TABLE Products
(
ProductCode nchar(9) primary key,
EmployeeNumber nchar(6) FOREIGN KEY REFERENCES Employees(EmployeeNumber),
DateAcquired date,
Name nvarchar(60),
UnitPrice money
)ON UPDATE SET ERROR;
GOCREATE TABLE Employees
(
EmployeeNumber nchar(6) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20) not null
);
GO
He wants to make sure that when a record is deleted from the Employees
table, any record of the Products table that was using the correspoding
value of the Employees table is deleted. What code can he use to create the
Products table?
CREATE TABLE Products
(
ProductCode nchar(9) primary key,
EmployeeNumber nchar(6) FOREIGN KEY REFERENCES Employees(EmployeeNumber),
DateAcquired date,
Name nvarchar(60),
UnitPrice money
)ON DELETE SET DELETE;
GOCREATE TABLE Products
(
ProductCode nchar(9) primary key,
EmployeeNumber nchar(6) FOREIGN KEY REFERENCES Employees(EmployeeNumber)
ON DELETE CASCADE,
DateAcquired date,
Name nvarchar(60),
UnitPrice money
);
GOCREATE TABLE Products
(
ProductCode nchar(9) primary key,
EmployeeNumber nchar(6) FOREIGN KEY REFERENCES Employees(EmployeeNumber),
DateAcquired date,
Name nvarchar(60),
UnitPrice money
)ON DELETE NO ACTION;
GOCREATE TABLE Products
(
ProductCode nchar(9) primary key,
EmployeeNumber nchar(6) FOREIGN KEY REFERENCES Employees(EmployeeNumber)
ON DELETE SET NULL,
DateAcquired date,
Name nvarchar(60),
UnitPrice money
);
GOCREATE TABLE Products
(
ProductCode nchar(9) primary key,
EmployeeNumber nchar(6) FOREIGN KEY REFERENCES Employees(EmployeeNumber),
DateAcquired date,
Name nvarchar(60),
UnitPrice money
)ON DELETE SET NULL;
GOCREATE TABLE Categories
(
CategoryID nchar(4) not null PRIMARY KEY,
Category nvarchar(32) not null
);
GO
Gio now has to create a new table for the houses. The table must include a
column that will get the house types for the above table. If a category is
changed from the above table, Gio would like the records that were using
that category in the new table to be changed to reflect the new value. How should he create the new table?
CREATE TABLE Houses ( Code nchar(11) not null PRIMARY KEY, CategoryID nchar(4) FOREIGN KEY REFERENCES Categories(CategoryID) ON UPDATE SET DELETE, City nvarchar(40), MarketValue money ); GO
CREATE TABLE Houses ( Code nchar(11) not null PRIMARY KEY, CategoryID nchar(4) FOREIGN KEY REFERENCES Categories(CategoryID) ON UPDATE CASCADE, City nvarchar(40), MarketValue money ); GO
CREATE TABLE Houses ( Code nchar(11) not null PRIMARY KEY, CategoryID nchar(4) FOREIGN KEY REFERENCES Categories(CategoryID), City nvarchar(40), MarketValue money )ON UPDATE NO ACTION; GO
CREATE TABLE Houses ( Code nchar(11) not null PRIMARY KEY, CategoryID nchar(4) FOREIGN KEY REFERENCES Categories(CategoryID) ON UPDATE SET NULL, City nvarchar(40), MarketValue money ); GO
CREATE TABLE Houses ( Code nchar(11) not null PRIMARY KEY, CategoryID nchar(4) FOREIGN KEY REFERENCES Categories(CategoryID), City nvarchar(40), MarketValue money )ON UPDATE NULL; GO
CREATE TABLE HouseTypes
(
HouseTypeID int not null PRIMARY KEY,
HouseType nvarchar(32) not null
);
GO
Now he has to create a table that holds the properties the company sells.
The table of properties will have a column that specifies the type of house.
The value of that column will come from the above table. When a house type
deleted from the first table, Charlie wants the corresponding records of the
new table to be changed to NULL. How can he create the new table to
implement that functionality?
CREATE TABLE Properties
(
PropertyNumber nchar(11) not null PRIMARY KEY,
HouseTypeID int CONSTRAINT FK_PropTypes FOREIGN KEY
REFERENCES HouseTypes(HouseTypeID)
ON DELETE CASCADE NULL,
City nvarchar(40),
MarketValue money
);
GO
CREATE TABLE Properties
(
PropertyNumber nchar(11) not null PRIMARY KEY,
HouseTypeID int CONSTRAINT FK_PropTypes FOREIGN KEY
REFERENCES HouseTypes(HouseTypeID)
ON DELETE NO ACTION,
City nvarchar(40),
MarketValue money
);
GO
CREATE TABLE Properties
(
PropertyNumber nchar(11) not null PRIMARY KEY,
HouseTypeID int CONSTRAINT FK_PropTypes FOREIGN KEY
REFERENCES HouseTypes(HouseTypeID),
City nvarchar(40),
MarketValue money
)ON DELETE NULL IS TRUE;
GO
CREATE TABLE Properties
(
PropertyNumber nchar(11) not null PRIMARY KEY,
HouseTypeID int CONSTRAINT FK_PropTypes FOREIGN KEY
REFERENCES HouseTypes(HouseTypeID)
ON DELETE SET NULL,
City nvarchar(40),
MarketValue money
);
GO
CREATE TABLE Properties
(
PropertyNumber nchar(11) not null PRIMARY KEY,
HouseTypeID int CONSTRAINT FK_PropTypes FOREIGN KEY
REFERENCES HouseTypes(HouseTypeID),
City nvarchar(40),
MarketValue money
)ON DELETE SET CASCADE NULL;
GO
CREATE TABLE Categories
(
CategoryID int not null PRIMARY KEY,
Category nvarchar(32) not null
);
GO
In the table for members, since Courtney will include a column for the categories,
when a record of the Categories table is are updated, she
wants the corresponding field in the members table to receive a NULL value.
How should she create the table for the members?
CREATE TABLE Members
(
MemberID int unique,
Name nvarchar(50),
CategoryID int FOREIGN KEY REFERENCES Categories(CategoryID)
ON UPDATE CASCADE NULL,
MembershipStatus nvarchar(20)
);
GO
CREATE TABLE Members
(
MemberID int unique,
Name nvarchar(50),
CategoryID int FOREIGN KEY REFERENCES Categories(CategoryID)
ON UPDATE NO ACTION,
MembershipStatus nvarchar(20)
);
GO
CREATE TABLE Members
(
MemberID int unique,
Name nvarchar(50),
CategoryID int FOREIGN KEY REFERENCES Categories(CategoryID)
ON UPDATE SET NULL,
MembershipStatus nvarchar(20)
);
GO
CREATE TABLE Members
(
MemberID int unique,
Name nvarchar(50),
CategoryID int FOREIGN KEY REFERENCES Categories(CategoryID),
MembershipStatus nvarchar(20)
)ON UPDATE NULL IS TRUE;
GO
CREATE TABLE Members
(
MemberID int unique,
Name nvarchar(50),
CategoryID int FOREIGN KEY REFERENCES Categories(CategoryID),
MembershipStatus nvarchar(20)
)ON UPDATE SET NULL;
GO
CREATE TABLE EmploymentTypes
(
EmploymentTypeID int identity(1000, 10) primary key,
EmploymenStatus nvarchar(20) not null,
);
GO
INSERT INTO EmploymentTypes(EmploymenStatus)
VALUES(N'Full Time'),(N'Part Time'),(N'Unknown');
GO
To keep track of employees, Douglas starts creating a table as follows:
CREATE TABLE Employees
(
EmployeeNumber nchar(6) not null primary key,
EmploymentTypeID int FOREIGN KEY
REFERENCES EmploymentTypes(EmploymentTypeID)
DEFAULT 3,
FirstName nvarchar(20),
LastName nvarchar(20) not null,
HourlySalary money
);
GO
If an employment
status is deleted from the EmploymentStatus table, Douglas would like the
employees who use that status to get the default value. How should he change
the Employees table to take care of this requirement?
CREATE TABLE Employees
(
EmployeeNumber nchar(6) not null primary key,
EmploymentTypeID int FOREIGN KEY
REFERENCES EmploymentTypes(EmploymentTypeID)
ON DELETE SET DEFAULT
DEFAULT 3,
FirstName nvarchar(20),
LastName nvarchar(20) not null,
HourlySalary money
);
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(6) not null primary key,
EmploymentTypeID int FOREIGN KEY
REFERENCES EmploymentTypes(EmploymentTypeID)
DEFAULT 3,
FirstName nvarchar(20),
LastName nvarchar(20) not null,
HourlySalary money
)ON DELETE DEFAULT = NULL;
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(6) not null primary key,
EmploymentTypeID int FOREIGN KEY
REFERENCES EmploymentTypes(EmploymentTypeID)
DEFAULT 3
ON DELETE CASCADE DEFAULT,
FirstName nvarchar(20),
LastName nvarchar(20) not null,
HourlySalary money
);
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(6) not null primary key,
EmploymentTypeID int FOREIGN KEY
REFERENCES EmploymentTypes(EmploymentTypeID)
ON DELETE NO ACTION
DEFAULT 3,
FirstName nvarchar(20),
LastName nvarchar(20) not null,
HourlySalary money
);
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(6) not null primary key,
EmploymentTypeID int FOREIGN KEY
REFERENCES EmploymentTypes(EmploymentTypeID)
DEFAULT 3,
FirstName nvarchar(20),
LastName nvarchar(20) not null,
HourlySalary money
)ON DELETE DEFAULT IS TRUE;
GO
CREATE TABLE ItemsTypes
(
ItemTypeID int identity(1, 1) primary key,
ItemType nvarchar(20) not null,
);
GO
INSERT INTO ItemsTypes(ItemType)
VALUES(N'Miscellaneous'),(N'Shirts'),(N'Dresses'),(N'Pants');
GO
In the table of items, there will be a column that gets its values from the
ItemsTypes table. To start with the items sold in the store, Josephs write the following
code without executing it:
CREATE TABLE StoreItems
(
ItemCode nchar(10) not null primary key,
ItemTypeID int FOREIGN KEY
REFERENCES ItemsTypes(ItemTypeID)
DEFAULT 1,
Name nvarchar(50),
Size nvarchar(20) not null,
UnitPrice money
);
GO
Sometimes the employees will change the name of a type in the ItemsTypes
table. When this happens, Joseph wants the items that use that category to get the default value.
How can Joseph change the code the StoreItems table to take care of this?
CREATE TABLE StoreItems
(
ItemCode nchar(10) not null primary key,
ItemTypeID int FOREIGN KEY
REFERENCES ItemsTypes(ItemTypeID)
DEFAULT 1,
Name nvarchar(50),
Size nvarchar(20) not null,
UnitPrice money
) ON UPDATE DEFAULT = NULL;
GO
CREATE TABLE StoreItems
(
ItemCode nchar(10) not null primary key,
ItemTypeID int FOREIGN KEY
REFERENCES ItemsTypes(ItemTypeID)
ON UPDATE CASCADE DEFAULT
DEFAULT 1,
Name nvarchar(50),
Size nvarchar(20) not null,
UnitPrice money
);
GO
CREATE TABLE StoreItems
(
ItemCode nchar(10) not null primary key,
ItemTypeID int FOREIGN KEY
REFERENCES ItemsTypes(ItemTypeID)
DEFAULT 1,
Name nvarchar(50),
Size nvarchar(20) not null,
UnitPrice money
)ON UPDATE NO ACTION;
GO
CREATE TABLE StoreItems
(
ItemCode nchar(10) not null primary key,
ItemTypeID int FOREIGN KEY
REFERENCES ItemsTypes(ItemTypeID)
DEFAULT 1
ON UPDATE DEFAULT IS TRUE,
Name nvarchar(50),
Size nvarchar(20) not null,
UnitPrice money
);
GO
CREATE TABLE StoreItems
(
ItemCode nchar(10) not null primary key,
ItemTypeID int FOREIGN KEY
REFERENCES ItemsTypes(ItemTypeID)
ON UPDATE SET DEFAULT
DEFAULT 1,
Name nvarchar(50),
Size nvarchar(20) not null,
UnitPrice money
);
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(9),
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money,
[Status] nvarchar(20) default N'Employee'
);
GO
CREATE TABLE Contractors
(
ContractorCode nchar(7),
Name1 nvarchar(20),
Name2 nvarchar(20),
Wage decimal(6, 2),
[Type] nvarchar(20) default N'Contractor'
);
GO
INSERT INTO Employees(EmployeeNumber, FirstName, LastName, HourlySalary)
VALUES(N'2930-4708', N'John', N'Franks', 20.05),
(N'8274-9571', N'Peter', N'Sonnens', 10.65),
(N'6359-8079', N'Leslie', N'Aronson', 15.88);
GO
INSERT INTO Contractors(ContractorCode, Name1, Name2, Wage)
VALUES(N'350-809', N'Mary', N'Shamberg', 14.20),
(N'286-606', N'Chryssa', N'Lurie', 20.26);
GO
In preparation of payroll, John wants to preview the employees and
contractors in one common list. What code can he write to get that list?
SELECT * FROM Employees; GO SELECT * FROM Contractors; GO
SELECT * FROM Employees UNION SELECT * FROM Contractors; GO
SELECT * FROM Employees; GO UNION SELECT * FROM Contractors; GO
WITH UNION SELECT * FROM Employees AND SELECT * FROM Contractors; GO
CREATE TABLE Seasonals
(
Number nchar(9),
FName nvarchar(20),
LName nvarchar(20),
HourlySalary money
);
GO
CREATE TABLE Contractors
(
Code nchar(7),
Name1 nvarchar(20),
Name2 nvarchar(20),
Wage decimal(6, 2)
);
GO
INSERT INTO Seasonals
VALUES(N'2930-4708', N'John', N'Franks', 20.05),
(N'8274-9571', N'Peter', N'Sonnens', 10.65),
(N'6359-8079', N'Leslie', N'Aronson', 15.88);
GO
INSERT INTO Contractors
VALUES(N'350-809', N'Mary', N'Shamberg', 14.20),
(N'286-606', N'Chryssa', N'Lurie', 20.26);
GO
All these seasonal employees and contractors have been hired by the company.
To prepare their inclusion into the company, Mark creates a new table named Employees as follows:
CREATE TABLE Employees
(
EmployeeNumber nchar(9),
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money
);
GO
Marc wants to add the
seasonal employees and the contractors to the Employees table. What code can
let him do that?
SELECT FROM Seasonals INTO Employees UNION SELECT FROM Contractors INTO Employees; GO
INSERT INTO Employees SELECT * FROM Seasonals UNION SELECT * FROM Contractors; GO
UNION ALL SELECT ALL * FROM Seasonals AND SELECT ALL * FROM Contractors INTO Employees; GO
SELECT ALL * FROM Seasonals AND SELECT ALL * FROM Contractors INTO Employees UNION ALL; GO
SELECT ALL * FROM Seasonals, Contractors INTO Employees UNION ALL; GO
CREATE TABLE Contractors
(
ContractorCode nchar(10),
FName nvarchar(20),
LName nvarchar(20),
Wage decimal(6, 2)
);
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(10),
DateHired date,
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money,
EmploymentStatus nvarchar(20) null
);
GO
INSERT INTO Contractors
VALUES(N'35080', N'Mary', N'Shamberg', 14.20),
(N'286606', N'Chryssa', N'Lurie', 20.26),
(N'415905', N'Ralph', N'Sunny', 15.55);
GO
INSERT INTO Employees
VALUES(N'286018', N'20020426', N'Julie', N'Chance', 12.84, N'Full Time'),
(N'286606', N'19981008', N'Ayinda', N'Kaihibu', 9.52, N'Part Time'),
(N'922620', N'20100815', N'Ann', N'Keans', 20.52, N'Full Time'),
(N'415905', N'20061222', N'Godwin', N'Harrison', 18.75, N'Full Time'),
(N'682470', N'20080430', N'Timothy', N'Journ', 21.05, NULL);
GO
He wants to merge the records to add those of the contractors to the Employees
table by comparing the employee numbers to the contractors codes. During the
operation, if a record from the Contractors table matches an employee
number, two leading 0s will be added to the employeee number to make sure
the numbers remain unique (but the other parts of the record will not be
changed). Otherwise, the record should be added.
What code would accomplish this?
USING Contractors AS SOURCE
MERGE Employees AS TARGET
ON (Workers.ContractorCode = Teachers.EmployeeNumber)
WHEN MATCHED
THEN UPDATE SET EmployeeNumber = N'00' + ContractorCode
WHEN NOT MATCHED BY SOURCE
THEN INSERT(EmployeeNumber, FirstName, LastName, HourlySalary)
VALUES(ContractorCode, FName, LName, Wage);
GOUSING Contractors AS SOURCE
MERGE Employees AS TARGET
ON (Workers.ContractorCode = Teachers.EmployeeNumber)
WHEN NOT MATCHED BY SOURCE
THEN INSERT(EmployeeNumber, FirstName, LastName, HourlySalary)
VALUES(ContractorCode, FName, LName, Wage)
WHEN MATCHED
THEN UPDATE SET EmployeeNumber = N'00' + ContractorCode;
GOMERGE Employees AS Teachers
WHEN MATCHED
THEN UPDATE SET EmployeeNumber = N'00' + ContractorCode
WHEN NOT MATCHED BY SOURCE
THEN INSERT(EmployeeNumber, FirstName, LastName, HourlySalary)
VALUES(ContractorCode, FName, LName, Wage)
USING Contractors AS Workers
ON (Workers.ContractorCode = Teachers.EmployeeNumber);MERGE Employees AS Teachers
USING Contractors AS Workers
ON (Workers.ContractorCode = Teachers.EmployeeNumber)
WHEN MATCHED
THEN UPDATE SET EmployeeNumber = N'00' + ContractorCode
WHEN NOT MATCHED BY TARGET
THEN INSERT(EmployeeNumber, FirstName, LastName, HourlySalary)
VALUES(ContractorCode, FName, LName, Wage);
GO
WITH MERGE Employees AS Teachers
ON (Workers.ContractorCode = Teachers.EmployeeNumber)
USING Contractors AS Workers
WHEN MATCHED
THEN UPDATE SET EmployeeNumber = N'00' + ContractorCode
WHEN NOT MATCHED BY SOURCE
THEN INSERT(EmployeeNumber, FirstName, LastName, HourlySalary)
VALUES(ContractorCode, FName, LName, Wage);
GOCREATE TABLE Products
(
ProductNumber int not null,
DateAcquired date,
Name nvarchar(50),
Size nvarchar(32),
UnitPrice money,
CONSTRAINT PK_Products PRIMARY KEY(ProductNumber)
);
GO
CREATE TABLE StoreItems
(
ItemCode int identity(1, 1) not null PRIMARY KEY,
Arrival date,
[Description] nvarchar(50),
Value money
);
GO
INSERT Products
VALUES(2, N'2011-12-06', N'Mid Lady Bag - Lizard', N'12', 228),
(888, N'2010-08-09', N'Midnight Floral Cardigan', N'Small', 78),
(105583, N'2011-10-12', N'Zip Front Sheath Dress', N'8', 138),
(4, N'2010-05-24', N'Holly Gladiator Heel Shoes', N'7.5', 198),
(3680, N'2011-02-16', N'Short Black Skirt', N'14', 55.85),
(28, NULL, N'Color-Block Chambray Shirt', N'10', 85.25);
GO
INSERT StoreItems(Arrival, [Description], Value)
VALUES(N'2010-02-22', N'Short-Sleeved Bush Shirt', 59.95),
(N'2011-10-12', N'Zip Front Sheath Dress', 138),
(N'2010-05-24', N'Pure Cashmere Sweater', 165),
(N'2011-02-16', N'Short Black Skirt', 55.85);
GO
It appears that
some records are duplicated. To start, Evelyne wants to merge
the records from the StoreItems to the Products tables. During this
operation, if a record from one table matches a record from the other table,
the matching record should be removed. Otherwise, if the record is not found
in the StoreItems table, it should be added to the Products table. How can she write code to merge the records?
USING StoreItems AS Items
MERGE Products AS Inventory
ON Inventory.ProductNumber = Items.ItemCode
WHEN MATCHED
THEN DELETE
WHEN NOT MATCHED THEN
INSERT(ProductNumber, DateAcquired, Name, UnitPrice)
VALUES(ItemCode, Arrival, [Description], Value);
GOMERGE Products AS Inventory
USING StoreItems AS Items
ON Inventory.ProductNumber = Items.ItemCode
WHEN MATCHED THEN DELETE
WHEN NOT MATCHED THEN
INSERT(ProductNumber, DateAcquired, Name, UnitPrice)
VALUES(ItemCode, Arrival, [Description], Value);
GOWITH StoreItems AS Items
MERGE Products AS Inventory
ON Inventory.ProductNumber = Items.ItemCode
WHEN MATCHED
THEN DELETE
WHEN NOT MATCHED THEN
INSERT(ProductNumber, DateAcquired, Name, UnitPrice)
VALUES(ItemCode, Arrival, [Description], Value);
GOWITH StoreItems AS Items
MERGE Products AS Inventory
ON Inventory.ProductNumber = Items.ItemCode
WHEN MATCHED SET NULL
OR
INSERT(ProductNumber, DateAcquired, Name, UnitPrice)
VALUES(ItemCode, Arrival, [Description], Value);
GOSELECT * FROM Products AS Inventory
AND
SELECT * FROM StoreItems AS Items
MERGE
ON Inventory.ProductNumber = StoreItems.ItemCode
IF MATCH THEN
DELETE
ELSE
INSERT(ProductNumber, DateAcquired, Name, UnitPrice)
VALUES(ItemCode, Arrival, [Description], Value);
GOCREATE TABLE Rooms
(
RoomNumber nchar(10) not null,
RoomType nvarchar(20) default N'Bedroom',
BedType nvarchar(40) default N'Queen',
Rate money default 75.85,
Available bit
);
GO
INSERT INTO Rooms(RoomNumber, BedType, Rate, Available)
VALUES(N'104', default, 80.25, 0),
(N'105', N'King', 95.50, 1),
(N'108', N'King', 92.50, 1),
(N'109', default, 68.95, 0),
(N'110', default, 74.95, 1);
GO
How can you write a common table expression
to see its records?
WITH BedRooms AS
(
SELECT * FROM Rooms
)
SELECT * FROM BedRooms;
GOWITH BedRooms AS SELECT * FROM BedRooms;
BEGIN
SELECT * FROM Rooms
ENDSELECT * FROM BedRooms
AS BedRooms
BEGIN
SELECT * FROM Rooms
ENDWITH BedRooms
AS
BEGIN
SELECT * FROM Rooms
ENDSELECT * FROM Rooms AS BedRooms
BEGIN
SELECT * FROM Bedrooms
ENDCREATE TABLE Rooms
(
RoomNumber nchar(10) not null,
RoomType nvarchar(20) default N'Bedroom',
BedType nvarchar(40) default N'Queen',
Rate money default 75.85,
Available bit
);
GO
INSERT INTO Rooms(RoomNumber, BedType, Rate, Available)
VALUES(N'104', default, 80.25, 0),
(N'105', N'King', 95.50, 1),
(N'108', N'King', 92.50, 1),
(N'109', default, 68.95, 0),
(N'110', default, 74.95, 1);
GO
What code allows you to create a common table expression
that includes only King bedrooms?
CREATE BedRooms(RoomNumber, RoomType, BedType, Rate, Available)
AS CTE
BEGIN
SELECT RoomNumber, RoomType, BedType, Rate, Available
FROM Rooms
WHERE BedType = N'King'
END
SELECT RoomNumber, RoomType, Rate, Available FROM BedRooms
GOSELECT RoomNumber, RoomType, BedType, Rate, Available FROM Rooms WHERE BedType = N'King' AS BedRooms(RoomNumber, RoomType, BedType, Rate, Available); GO SELECT RoomNumber, RoomType, Rate, Available FROM BedRooms GO
WITH BedRooms(RoomNumber, RoomType, BedType, Rate, Available)
AS
(
SELECT RoomNumber, RoomType, BedType, Rate, Available
FROM Rooms
WHERE BedType = N'King'
)
SELECT RoomNumber, RoomType, Rate, Available FROM BedRooms
GOSET BedRooms(RoomNumber, RoomType, BedType, Rate, Available) BEGIN SELECT RoomNumber, RoomType, BedType, Rate, Available FROM Rooms WHERE BedType = N'King' END SELECT RoomNumber, RoomType, Rate, Available FROM BedRooms GO
WITH BedRooms(RoomNumber, RoomType, BedType, Rate, Available)
BEGIN
SELECT RoomNumber, RoomType, BedType, Rate, Available
FROM Rooms
WHERE BedType = N'King'
SELECT RoomNumber, RoomType, Rate, Available FROM BedRooms
END
GOCREATE TABLE SleepingRooms (
RoomNumber nchar(10) not null,
RoomType nvarchar(20) default N'Bedroom',
BedType nvarchar(40) default N'Queen',
Rate money default 75.85,
Available bit
);
GO
CREATE TABLE ConferenceRooms (
RoomNumber nchar(10) not null,
RoomType nvarchar(20) default N'Conference',
BedType nvarchar(40),
Rate money default 75.85,
Available bit
);
GO
INSERT INTO SleepingRooms(RoomNumber, BedType, Rate, Available)
VALUES(N'104', default, 80.25, 0),
(N'105', N'King', 95.50, 1),
(N'108', N'King', 92.50, 1),
(N'109', default, 68.95, 0),
(N'110', default, 74.95, 1);
GO
INSERT INTO ConferenceRooms(RoomNumber, Rate)
VALUES(N'C-120', 525.00),
(N'C-122', 450.00);
GO
How can he create a common table expression to get a preview of bedrooms and
conference rooms in one list?
WITH HotelRooms
BEGIN
SELECT * FROM SleepingRooms
UNION
SELECT * FROM ConferenceRooms
END
SELECT * FROM HotelRooms;
GOSET CTE
BEGIN
SELECT * FROM SleepingRooms
UNION
SELECT * FROM ConferenceRooms
END
WITH HotelRooms
SELECT * FROM HotelRooms;
GODECLARE @HotelRooms AS VIEW
BEGIN
SELECT * FROM SleepingRooms
UNION
SELECT * FROM ConferenceRooms
END
SELECT * FROM @HotelRooms;
GOWITH HotelRooms AS TABLE
BEGIN
SELECT * FROM SleepingRooms
UNION ALL
SELECT * FROM ConferenceRooms
END
SELECT * FROM @HotelRooms;
GOWITH HotelRooms
AS
(
SELECT * FROM SleepingRooms
UNION
SELECT * FROM ConferenceRooms
)
SELECT * FROM HotelRooms;
GOCREATE TABLE SleepingRooms
(
RoomNumber nchar(10) not null,
RoomType nvarchar(20) default N'Bedroom',
BedType nvarchar(40) default N'Queen',
Rate money default 75.85,
Available bit
);
GO
CREATE TABLE ConferenceRooms
(
RoomNumber nchar(10) not null,
RoomType nvarchar(20) default N'Conference',
BedType nvarchar(40),
Rate money default 75.85,
Available bit
);
GO
INSERT INTO SleepingRooms(RoomNumber, BedType, Rate, Available)
VALUES(N'104', default, 80.25, 0),
(N'105', N'King', 95.50, 1),
(N'108', N'King', 92.50, 1),
(N'109', default, 68.95, 0),
(N'110', default, 74.95, 1);
GO
INSERT INTO ConferenceRooms(RoomNumber, Rate)
VALUES(N'C-120', 525.00),
(N'C-122', 450.00);
GO
How can he create a common table expression that
shows a list available bedrooms and
conference rooms?
SET HotelRooms
BEGIN
SELECT * FROM SleepingRooms
UNION
SELECT * FROM ConferenceRooms
END
SELECT RoomNumber, RoomType, BedType, Rate
FROM HotelRooms
WHERE Available = 1;
GOWITH HotelRooms
AS
(
SELECT * FROM SleepingRooms
UNION
SELECT * FROM ConferenceRooms
)
SELECT RoomNumber, RoomType, BedType, Rate
FROM HotelRooms
WHERE Available = 1;
GOWITH HotelRooms
BEGIN
SELECT * FROM SleepingRooms
UNION
SELECT * FROM ConferenceRooms
END
AS
SELECT RoomNumber, RoomType, BedType, Rate
FROM HotelRooms
WHERE Available = 1;
GOWITH HotelRooms
MERGE AS
(
SELECT * FROM SleepingRooms
UNION
SELECT * FROM ConferenceRooms
)
SELECT RoomNumber, RoomType, BedType, Rate
FROM HotelRooms
WHERE Available = 1;
GOWITH HotelRooms
MERGE AS
BEGIN
SELECT * FROM SleepingRooms
WHERE Available = 1
UNION
SELECT * FROM ConferenceRooms
WHERE Available = 1
END
SELECT RoomNumber, RoomType, BedType, Rate
FROM HotelRooms;
GOCREATE TABLE Rooms
(
RoomNumber nchar(10) not null,
RoomType nvarchar(20) default N'Bedroom',
BedType nvarchar(40) default N'Queen',
Rate money default 75.85,
Available bit
);
GO
INSERT INTO SleepingRooms(RoomNumber, BedType, Rate, Available)
VALUES(N'104', default, 80.25, 0),
(N'105', N'King', 95.50, 1),
(N'108', N'King', 92.50, 1),
(N'109', default, 68.95, 0),
(N'110', default, 74.95, 1);
GO
Write an inline table-valued function that would produce all records of that
table
CREATE FUNCTION GetRooms() AS TABLE
RETURN
SELECT ALL * FROM Rooms;
GOCREATE FUNCTION GetRooms()
RETURN
SELECT ALL * FROM Rooms AS TABLE;
GOCREATE FUNCTION GetRooms()
RETURNS TABLE
BEGIN
SELECT ALL * FROM Rooms;
END
GOCREATE FUNCTION GetRooms() RETURNS TABLE AS RETURN SELECT ALL * FROM Rooms; GO
CREATE FUNCTION GetRooms()
BEGIN
RETURN SELECT ALL * FROM Rooms;
END
GOCREATE SCHEMA Personnel;
GO
CREATE SCHEMA Commercial;
GO
CREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus smallint,
HourlySalary money
);
GO
CREATE TABLE Commercial.Sales
(
SaleID int identity(1, 1),
EmployeeNumber nchar(7) not null,
SaleDate date,
Amount money
);
GO
INSERT Personnel.Employees
VALUES(N'284-680', N'Anselme', N'Bongos', 2, 18.62),
(N'730-704', N'June', N'Malea', 1, 9.95),
(N'735-407', N'Frank', N'Monson', 3, 14.58),
(N'281-730', N'Jerry', N'Beaulieu', 1, 16.65);
GO
INSERT INTO Commercial.Sales(EmployeeNumber, SaleDate, Amount)
VALUES(N'284-680', N'2011-02-14', 4250),
(N'735-407', N'2011-02-14', 5300),
(N'730-704', N'2011-02-14', 2880),
(N'281-730', N'2011-02-14', 4640),
(N'284-680', N'2011-02-15', 4250),
(N'281-730', N'2011-02-15', 3675);
GO
Instead of a view, she wants to create an inline table-valued function named
GetSales that can produce a list of all sales made by the employees. Each
record will include the employee's full name (the last name followed by a
comma and followed by the first name), the date a sale was made, and the
amount of the sale. How can she write code for that function?
CREATE FUNCTION GetSales()
AS TABLE
RETURN
SELECT pe.LastName + N', ' + pe.FirstName,
cs.SaleDate, cs.Amount
FROM Commercial.Sales cs
INNER JOIN Personnel.Employees pe
ON cs.EmployeeNumber = pe.EmployeeNumber;
GOCREATE FUNCTION GetSales()
RETURN TABLE
BEGIN
RETURNS
SELECT pe.LastName + N', ' + pe.FirstName AS [Full Name],
cs.SaleDate, cs.Amount
FROM Commercial.Sales cs
INNER JOIN Personnel.Employees pe
ON cs.EmployeeNumber = pe.EmployeeNumber;
END
GOCREATE INLINE FUNCTION GetSales()
RETURN TABLE
BEGIN
SELECT pe.LastName + N', ' + pe.FirstName,
cs.SaleDate, cs.Amount
FROM Commercial.Sales cs
INNER JOIN Personnel.Employees pe
ON cs.EmployeeNumber = pe.EmployeeNumber;
END
GOCREATE FUNCTION GetSales()
RETURNS TABLE
AS
RETURN
SELECT pe.LastName + N', ' + pe.FirstName AS [Full Name],
cs.SaleDate, cs.Amount
FROM Commercial.Sales cs
INNER JOIN Personnel.Employees pe
ON cs.EmployeeNumber = pe.EmployeeNumber;
GOCREATE FUNCTION GetSales()
BEGIN
SELECT pe.LastName + N', ' + pe.FirstName AS [Full Name],
cs.SaleDate, cs.Amount
FROM Commercial.Sales cs
INNER JOIN Personnel.Employees pe
ON cs.EmployeeNumber = pe.EmployeeNumber;
END
RETURN TABLE
GOCREATE SCHEMA Personnel;
GO
CREATE SCHEMA Commercial;
GO
CREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus smallint,
HourlySalary money
);
GO
INSERT Personnel.Employees
VALUES(N'284-680', N'Anselme', N'Bongos', 2, 18.62),
(N'730-704', N'June', N'Malea', 1, 9.95),
(N'735-407', N'Frank', N'Monson', 3, 14.58),
(N'281-730', N'Jerry', N'Beaulieu', 1, 16.65);
GO
CREATE TABLE Commercial.Sales
(
SaleID int identity(1, 1),
EmployeeNumber nchar(7) not null,
SaleDate date,
Amount money
);
GO
INSERT INTO Commercial.Sales(EmployeeNumber, SaleDate, Amount)
VALUES(N'284-680', N'2011-02-14', 4250),
(N'735-407', N'2011-02-14', 5300),
(N'730-704', N'2011-02-14', 2880),
(N'281-730', N'2011-02-14', 4640),
(N'284-680', N'2011-02-15', 4250),
(N'281-730', N'2011-02-15', 3675);
GO
Since views don't allow parameterized queries, she wants to create an inline
table-valued function that takes an employee number as argument and produces
the sales made by that employee. Each record will include the employee's
full name (the last name followed by a comma and followed by the first
name), the date a sale was made, and the amount of the sale. How can she write code
to produce that result?
CREATE FUNCTION Commercial.GetSales(@EmplNbr nchar(7))
RETURNS TABLE
AS
RETURN
SELECT pe.LastName + N', ' + pe.FirstName AS [Full Name],
cs.SaleDate, cs.Amount
FROM Commercial.Sales cs
INNER JOIN Personnel.Employees pe
ON cs.EmployeeNumber = pe.EmployeeNumber
WHERE pe.EmployeeNumber = @EmplNbr;
GOCREATE FUNCTION Commercial.GetSales(@EmplNbr nchar(7))
RETURN
SELECT pe.LastName + N', ' + pe.FirstName AS [Full Name],
cs.SaleDate, cs.Amount
FROM Commercial.Sales cs
INNER JOIN Personnel.Employees pe
ON cs.EmployeeNumber = pe.EmployeeNumber
WHERE pe.EmployeeNumber = @EmplNbr
RETURNS TABLE
END
GOCREATE INLINE FUNCTION Commercial.GetSales(@EmplNbr nchar(7)) AS TABLE
BEGIN
SELECT pe.LastName + N', ' + pe.FirstName AS [Full Name],
cs.SaleDate, cs.Amount
FROM Commercial.Sales cs
INNER JOIN Personnel.Employees pe
ON cs.EmployeeNumber = pe.EmployeeNumber
WHERE pe.EmployeeNumber = @EmplNbr;
END
GOCREATE FUNCTION Commercial.GetSales(@EmplNbr nchar(7))
RETURNS TABLE
BEGIN
SELECT pe.LastName + N', ' + pe.FirstName,
cs.SaleDate, cs.Amount
FROM Commercial.Sales cs
INNER JOIN Personnel.Employees pe
ON cs.EmployeeNumber = pe.EmployeeNumber
WHERE pe.EmployeeNumber = @EmplNbr;
END
GOCREATE FUNCTION Commercial.GetSales(@EmplNbr nchar(7))
BEGIN
SELECT pe.LastName + N', ' + pe.FirstName AS [Full Name],
cs.SaleDate, cs.Amount
FROM Commercial.Sales cs
INNER JOIN Personnel.Employees pe
ON cs.EmployeeNumber = pe.EmployeeNumber
WHERE pe.EmployeeNumber = @EmplNbr
AS TABLE;
GOCREATE SCHEMA Inventory;
GO
CREATE TABLE Inventory.StoreItems
(
ItemCode int identity(1, 1) not null PRIMARY KEY,
DateAcquired date,
Name nvarchar(50),
Size nvarchar(32),
UnitPrice money,
DiscountRate decimal
);
GO
INSERT Inventory.StoreItems(DateAcquired, Name, Size, UnitPrice, DiscountRate)
VALUES(N'2011-12-06', N'Mid Lady Bag - Lizard', N'12', 228, NULL),
(N'2010-02-22', N'Short-Sleeved Bush Shirt', N'Medium', 59.95, 20),
(N'2011-10-12', N'Zip Front Sheath Dress', N'8', 138, NULL),
(N'2010-05-24', N'Holly Gladiator Heel Shoes', N'7.5', 198, 40),
(N'2011-02-16', N'Short Black Skirt', N'14', 55.85, 0.00),
(N'2011-04-18', N'Color-Block Chambray Shirt', N'10', 85.25, 20);
GO
To make easy to show the records, Evelyne wants to create a stored produce
that would produce the item code, the name,
the size, and the unit price. How can she write code to create that procedure?
CREATE OBJECT::Inventory.GetItems
AS PROCEDURE
SELECT ItemCode, Name, Size, UnitPrice
FROM Inventory.StoreItems;
GOCREATE PROCEDURE Inventory.GetItems
AS
SELECT ItemCode, Name, Size, UnitPrice
FROM Inventory.StoreItems;
GOCREATE OBJECT::Inventory.GetItems AS PROCEDURE
BEGIN
SELECT ItemCode, Name, Size, UnitPrice
FROM Inventory.StoreItems;
END
GOCREATE PROCEDURE OBJECT::Inventory.GetItems
RETURN
SELECT ItemCode, Name, Size, UnitPrice
FROM Inventory.StoreItems;
GOCREATE OBJECT::Inventory.GetItems
RETURN PROCEDURE
BEGIN
SELECT ItemCode, Name, Size, UnitPrice
FROM Inventory.StoreItems;
END
GOSELECT * FROM Inventory.GetItems; GO
WITH Inventory.GetItems EXECUTE; GO
EXECUTE Inventory.GetItems; GO
USE Inventory.GetItems; GO
SET Inventory.GetItems ON; GO
CREATE SCHEMA Listing; GO CREATE TABLE Listing.Apartment ( UnitNumber nchar(8) not null, Bedrooms int, Bathrooms real, Price money, Deposit money, Available bit );To protect the table, Martha wants to create a stored procedure named GetUnits that other employees can use to see a list derived from the table. The list will include the unit number, the number of bedrooms, the number of bathrooms, and pricce. Because other people cannot directly execute the new stored procedure, she wants to allow them to use the marthag account. How should she create the stored procedure to make this possible?
CREATE OBJECT::PROCEDURE Registration.GetUnits
AS
SET NOCOUNT ON
SELECT UnitNumber, Bedrooms, Bathrooms, Price
FROM Listing.Apartments
WITH EXECUTE AS N'marthag';
GOCREATE Registration.GetUnits
AS PROCEDURE
SET NOCOUNT ON
SELECT UnitNumber, Bedrooms, Bathrooms, Price
FROM Listing.Apartments
WITH EXECUTE AS N'marthag';
GOCREATE PROCEDURE Registration.GetUnits
SET USER = N'marthag'
AS
SET NOCOUNT ON
SELECT UnitNumber, Bedrooms, Bathrooms, Price
FROM Listing.Apartments;
GOCREATE PROCEDURE Registration.GetUnits
AS
SET NOCOUNT ON
SELECT UnitNumber, Bedrooms, Bathrooms, Price
FROM Listing.Apartments
SET USER = N'marthag';
GOCREATE PROCEDURE Registration.GetUnits
WITH EXECUTE AS N'marthag'
AS
SET NOCOUNT ON
SELECT UnitNumber, Bedrooms, Bathrooms, Price
FROM Listing.Apartments;
GOCREATE SCHEMA Listing;
GO
CREATE TABLE Listing.Apartment
(
UnitNumber nchar(8) not null,
Bedrooms int,
Bathrooms real,
Price money,
Deposit money,
Available bit
);
INSERT Listing.Apartments
VALUES('104', 2, 1.00, 1050.00, 300.00, 0),
('306', 3, 2.00, 1350.00, 425.00, 1),
('105', 1, 1.00, 885.00, 250.00, 1),
('202', 1, 1.00, 950.00, 325.00, 0),
('304', 2, 2.00, 1250.00, 300.00, 0),
('106', 3, 2.00, 1350.00, 425.00, 1),
('308', 0, 1.00, 875.00, 225.00, 1),
('203', 1, 1.00, 885.00, 250.00, 1),
('204', 2, 2.00, 1125.00, 425.00, 1),
('205', 1, 1.00, 1055.00, 350.00, 0);
GO
Martha wants to create a stored procedure named
ShowUnit that takes a unit number as argument and produces the record of the
corresponding apartment. How
can she write code for that stored procedure?
CREATE OBJECT::Listing.ShowUnit @UnitNbr nchar(8)
RETURN PROCEDURE
AS
SET NOCOUNT ON
SELECT UnitNumber, Bedrooms, Bathrooms, Price, Deposit, Available
FROM Listing.Apartments
WHERE UnitNumber = @UnitNbr;
GOCREATE OBJECT::Listing.ShowUnit @UnitNbr nchar(8)
RETURNS PROCEDURE
AS
SET NOCOUNT ON
RETURN SELECT UnitNumber, Bedrooms, Bathrooms,
Price, Deposit, Available
FROM Listing.Apartments
WHERE UnitNumber = @UnitNbr;
GOCREATE PROCEDURE Listing.ShowUnit @UnitNbr nchar(8)
AS
SET NOCOUNT ON
SELECT UnitNumber, Bedrooms, Bathrooms,
Price, Deposit, Available
FROM Listing.Apartments
WHERE UnitNumber = @UnitNbr;
GOCREATE PROCEDURE Listing.ShowUnit
AS
DECLARE @UnitNbr nchar(8)
SET NOCOUNT ON
RETURN SELECT UnitNumber, Bedrooms, Bathrooms,
Price, Deposit, Available
FROM Listing.Apartments
WHERE UnitNumber = @UnitNbr;
GOCREATE PROCEDURE OBJECT::Listing.ShowUnit
@UnitNbr nchar(8)
BEGIN
SET NOCOUNT ON
RETURN SELECT UnitNumber, Bedrooms, Bathrooms,
Price, Deposit, Available
FROM Listing.Apartments
WHERE UnitNumber = @UnitNbr;
END
GOCREATE TABLE Inventory.Categories
(
CategoryID int identity(1, 1) primary key,
Category nvarchar(20) not null
);
GO
CREATE TABLE Inventory.StoreItems
(
ItemNumber nvarchar(10) primary key,
CategoryID int foreign key
references Inventory.Categories(CategoryID),
ItemName nvarchar(60) not null,
Size nvarchar(20),
UnitPrice money
);
GO
INSERT INTO Inventory.Categories(Category)
VALUES(N'Men'), (N'Women'), (N'Boys'), (N'Girls'),(N'Miscellaneous');
GO
INSERT INTO Inventory.StoreItems
VALUES(N'264850', 2, N'Long-Sleeve Jersey Dress', N'Petite', 39.95),
(N'930405', 4, N'Solid Crewneck Tee', N'Medium', 12.95),
(N'924515', 1, N'Hooded Full-Zip Sweatshirt', N'S', 69.95),
(N'294936', 2, N'Cool-Dry Soft Cup Bra', N'36D', 15.55);
GO
The employees of the company
are in charge of creating and changing products records. To keep track of the
records added or changed from the StoredItems table, James creates a table as
follows:
CREATE TABLE Inventory.DatabaseOperations
(
OperationID int identity(1,1) NOT NULL,
ObjectType nchar(20) default N'Table',
ObjectName nvarchar(40),
PerformedBy nvarchar(50),
ActionPerformed nvarchar(max),
TimePerformed datetime,
CONSTRAINT PK_Operations PRIMARY KEY(OperationID)
);
GO
When
the record of an item has been changed in the StoreItems table, James would like
the DatabaseOperations table to receive a notification. How can
James create a trigger to perform that operation?
CREATE TRIGGER OBJECT::Inventory.ProductUpdated
ON Inventory.StoreItems
FOR UPDATE
AS
BEGIN
INSERT INTO Inventory.DatabaseOperations(ObjectType,
ObjectName, PerformedBy,
ActionPerformed, TimePerformed)
VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(),
N'Product was updated', GETDATE())
END
GOCREATE TRIGGER OBJECT::Inventory.ProductUpdated
ON Inventory.StoreItems
FOR UPDATE
AS
RETURN
INSERT INTO Inventory.DatabaseOperations(ObjectType,
ObjectName, PerformedBy,
ActionPerformed, TimePerformed)
VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(),
N'Product was updated', GETDATE()),
GOCREATE OBJECT::Inventory.ProductUpdated ON Inventory.StoreItems RETURNS TRIGGER WITH UPDATE AS INSERT INTO Inventory.DatabaseOperations(ObjectType, ObjectName, PerformedBy, ActionPerformed, TimePerformed) VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(), N'Product was updated', GETDATE()), GO
CREATE TRIGGER Inventory.ProductUpdated ON Inventory.StoreItems AFTER UPDATE AS INSERT INTO Inventory.DatabaseOperations(ObjectType, ObjectName, PerformedBy, ActionPerformed, TimePerformed) VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(), N'Product was updated', GETDATE()); GO
CREATE OBJECT::Inventory.ProductUpdated
ON Inventory.StoreItems
AFTER UPDATE
AS TRIGGER
BEGIN
INSERT INTO Inventory.DatabaseOperations(ObjectType,
ObjectName, PerformedBy,
ActionPerformed, TimePerformed)
VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(),
N'Product was updated', GETDATE())
END
GOCREATE TABLE Inventory.Categories
(
CategoryID int identity(1, 1) primary key,
Category nvarchar(20) not null
);
GO
CREATE TABLE Inventory.StoreItems
(
ItemNumber nvarchar(10) primary key,
CategoryID int foreign key
references Inventory.Categories(CategoryID),
ItemName nvarchar(60) not null,
Size nvarchar(20),
UnitPrice money
);
GO
INSERT INTO Inventory.Categories(Category)
VALUES(N'Men'), (N'Women'), (N'Boys'), (N'Girls'),(N'Miscellaneous');
GO
INSERT INTO Inventory.StoreItems
VALUES(N'264850', 2, N'Long-Sleeve Jersey Dress', N'Petite', 39.95),
(N'930405', 4, N'Solid Crewneck Tee', N'Medium', 12.95),
(N'924515', 1, N'Hooded Full-Zip Sweatshirt', N'S', 69.95),
(N'294936', 2, N'Cool-Dry Soft Cup Bra', N'36D', 15.55);
GO
The employees
regularly create, change, and delete records from the tables. To keep track
of operations in the StoredItems table, James creates a table as
follows:
CREATE TABLE Inventory.DatabaseOperations
(
OperationID int identity(1,1) NOT NULL,
ObjectType nchar(20) default N'Table',
ObjectName nvarchar(40),
PerformedBy nvarchar(50),
ActionPerformed nvarchar(max),
TimePerformed datetime,
CONSTRAINT PK_Operations PRIMARY KEY(OperationID)
);
GO
To know when a record has been deleted from the StoredItems table, James wants
a new record to be added to the DatabaseOperations table. How can
James create a trigger to get those notifications?
CREATE TRIGGER Inventory.ProductRemoved
AFTER DELETE
ON Inventory.StoreItems
AS
RETURN
INSERT INTO Inventory.DatabaseOperations(ObjectType,
ObjectName, PerformedBy,
ActionPerformed, TimePerformed)
VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(),
N'Existing product deleted', GETDATE());
END
GOCREATE TRIGGER Inventory.ProductRemoved ON Inventory.StoreItems AFTER DELETE AS INSERT INTO Inventory.DatabaseOperations(ObjectType, ObjectName, PerformedBy, ActionPerformed, TimePerformed) VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(), N'Existing product deleted', GETDATE()); GO
CREATE OBJECT::Inventory.ProductRemoved
RETURNS TRIGGER
AFTER DELETE
ON Inventory.StoreItems
BEGIN
RETURN
INSERT INTO Inventory.DatabaseOperations(ObjectType,
ObjectName, PerformedBy,
ActionPerformed, TimePerformed)
VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(),
N'Existing product deleted', GETDATE());
END
GOCREATE OBJECT::Inventory.ProductRemoved AS TRIGGER AFTER DELETE ON Inventory.StoreItems BEGIN INSERT INTO Inventory.DatabaseOperations(ObjectType, ObjectName, PerformedBy, ActionPerformed, TimePerformed) VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(), N'Existing product deleted', GETDATE()); END GO
CREATE TRIGGER Inventory.ProductRemoved AFTER DELETE ON Inventory.StoreItems BEGIN INSERT INTO Inventory.DatabaseOperations(ObjectType, ObjectName, PerformedBy, ActionPerformed, TimePerformed) VALUES(DEFAULT, N'StoreItems', SUSER_SNAME(), N'Existing product deleted', GETDATE()); END GO
CREATE SCHEMA Management;
GO
CREATE TABLE Management.Operations
(
OperationID int identity(1,1) NOT NULL,
ObjectType nchar(20) default N'Table',
Employee nvarchar(50),
ActionPerformed nvarchar(max),
OccurredOn datetime,
CONSTRAINT PK_Operations PRIMARY KEY(OperationID)
);
GO
How can he create a trigger that creates a notification in the above table every time a table is created?
CREATE TRIGGER ObjectAdded
WHEN CREATE_TABLE
RETURN TABLE
AS
BEGIN
INSERT INTO Management.Operations(ObjectType, Employee,
ActionPerformed, OccurredOn)
VALUES(DEFAULT, SUSER_SNAME(),
N'Created a new table', GETDATE());
END
GOCREATE TRIGGER ObjectAdded
ON DATABASE
FOR CREATE_TABLE
AS
BEGIN
INSERT INTO Management.Operations(ObjectType, Employee,
ActionPerformed, OccurredOn)
VALUES(DEFAULT, SUSER_SNAME(),
N'Created a new table', GETDATE());
END
GOCREATE TRIGGER ObjectAdded
TARGET DATABASE
WHEN CREATE_TABLE
AS
INSERT INTO Management.Operations(ObjectType, Employee,
ActionPerformed, OccurredOn)
VALUES(DEFAULT, SUSER_SNAME(),
N'Created a new table', GETDATE());
END
GOCREATE OBJECT::ObjectAdded
RETURN TRIGGER
WHEN CREATE_TABLE
AS TABLE
BEGIN
SELECT INTO Management.Operations
SET ObjectType = N'Table',
Employee = SUSER_SNAME(),
ActionPerformed = N'Created a new table',
OccurredOn = GETDATE();
END
GOCREATE OBJECT::ObjectAdded
RETURN TRIGGER
WHEN CREATE_TABLE
AS TABLE
BEGIN
INSERT INTO Management.Operations(ObjectType, Employee,
ActionPerformed, OccurredOn)
VALUES(DEFAULT, SUSER_SNAME(),
N'Created a new table', GETDATE());
END
GOCREATE SCHEMA Management;
GO
CREATE TABLE Management.Operations
(
OperationID int identity(1,1) NOT NULL,
ObjectType nchar(20) default N'Table',
Employee nvarchar(50),
ActionPerformed nvarchar(max),
OccurredOn datetime,
CONSTRAINT PK_Operations PRIMARY KEY(OperationID)
);
GO
Now she wants to create a trigger that gets a notification if an employees
deletes one of the existing tables of the project. How can she create that
trigger?
CREATE TRIGGER TabledRemoved
WHEN DROP_TABLE
AS
INSERT INTO Management.Operations(ObjectType, Employee,
ActionPerformed, OccurredOn)
VALUES(DEFAULT, SUSER_SNAME(),
N'An existing table was deleted', GETDATE());
GOCREATE OBJECT::TabledRemoved
AS TRIGGER
WHEN DROP_TABLE
BEGIN
INSERT INTO Management.Operations(ObjectType, Employee,
ActionPerformed, OccurredOn)
VALUES(DEFAULT, SUSER_SNAME(),
N'An existing table was deleted', GETDATE());
END
GOCREATE TRIGGER::TabledRemoved
ON DATABASE
WHEN DROP_TABLE
BEGIN
INSERT INTO Management.Operations(ObjectType, Employee,
ActionPerformed, OccurredOn)
VALUES(DEFAULT, SUSER_SNAME(),
N'An existing table was deleted', GETDATE());
END
GOCREATE TabledRemoved
RETURNS TRIGGER
ON DATABASE
WHEN DROP_TABLE
BEGIN
INSERT INTO Management.Operations(ObjectType, Employee,
ActionPerformed, OccurredOn)
VALUES(DEFAULT, SUSER_SNAME(),
N'An existing table was deleted', GETDATE());
END
GOCREATE TRIGGER TabledRemoved
ON DATABASE
FOR DROP_TABLE
AS
BEGIN
INSERT INTO Management.Operations(ObjectType, Employee,
ActionPerformed, OccurredOn)
VALUES(DEFAULT, SUSER_SNAME(),
N'An existing table was deleted', GETDATE());
END
GOCREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus smallint,
HourlySalary money
);
GO
CREATE TABLE Commercial.Sales
(
SaleID int identity(1, 1),
EmployeeNumber nchar(7) not null,
SaleDate date,
Amount money
);
GO
INSERT Personnel.Employees
VALUES(N'284-680', N'Anselme', N'Bongos', 2, 18.62),
(N'730-704', N'June', N'Malea', 1, 9.95),
(N'735-407', N'Frank', N'Monson', 3, 14.58),
(N'281-730', N'Jerry', N'Beaulieu', 1, 16.65);
GO
INSERT INTO Commercial.Sales(EmployeeNumber, SaleDate, Amount)
VALUES(N'284-680', N'2011-02-14', 4250),
(N'735-407', N'2011-02-14', 5300),
(N'730-704', N'2011-02-14', 2880),
(N'281-730', N'2011-02-14', 4640),
(N'284-680', N'2011-02-15', 4250),
(N'281-730', N'2011-02-15', 3675);
GO
Hank
must produce a summary list that shows the employees and the average
sale they made during that period. How can he write code to get that result?
SELECT EmployeeNumber, AVG(Amount) FROM Sales HAVING EmployeeNumber;
SELECT EmployeeNumber, AVG(Amount) FROM Sales GROUP BY EmployeeNumber;
SELECT DISTINCT EmployeeNumber, AVG(Amount) FROM Sales; GO
SELECT EmployeeNumber, AVG(Amount) FROM Sales WHERE EmployeeNumber IS NOT NULL; GO
SELECT EmployeeNumber, AVG(Amount) FROM Sales GROUP BY Amount; GO
CREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
EmploymentStatus smallint,
HourlySalary money
);
GO
CREATE TABLE Commercial.Sales
(
SaleID int identity(1, 1),
EmployeeNumber nchar(7) not null,
SaleDate date,
Amount money
);
GO
INSERT Personnel.Employees
VALUES(N'284-680', N'Anselme', N'Bongos', 2, 18.62),
(N'730-704', N'June', N'Malea', 1, 9.95),
(N'735-407', N'Frank', N'Monson', 3, 14.58),
(N'281-730', N'Jerry', N'Beaulieu', 1, 16.65);
GO
INSERT INTO Commercial.Sales(EmployeeNumber, SaleDate, Amount)
VALUES(N'284-680', N'2011-02-14', 4250),
(N'735-407', N'2011-02-14', 5300),
(N'730-704', N'2011-02-14', 2880),
(N'281-730', N'2011-02-14', 4640),
(N'284-680', N'2011-02-15', 4250),
(N'281-730', N'2011-02-15', 3675);
GO
Hank
is asked to show a summary list of employees and the average
sale they made during that period. The list must contain the employee's full
name (made of last name followed by a comma and the first name) and the
average sale. How can he write code to get that result?
SELECT e.LastName + N', ' + e.FirstName AS [Full Name],
AVG(s.Amount) AS [Average Sales]
FROM Sales s INNER JOIN Employees e
ON s.EmployeeNumber = e.EmployeeNumber
GROUP BY e.LastName + N', ' + e.FirstName;
GOSELECT e.LastName + N', ' + e.FirstName AS [Full Name],
AVG(s.Amount) AS [Average Sales]
FROM Sales s INNER JOIN Employees e
ON s.EmployeeNumber = e.EmployeeNumber
GROUP BY s.EmployeeNumber;
GOSELECT e.EmployeeNumber, AVG(s.Amount) AS [Average Sales] FROM Sales s INNER JOIN Employees e ON s.EmployeeNumber = e.EmployeeNumber GROUP BY e.LastName + N', ' + e.FirstName; GO
SELECT e.LastName + N', ' + e.FirstName AS [Full Name],
AVG(s.Amount) AS [Average Sales]
FROM Sales s INNER JOIN Employees e
GROUP BY e.EmployeeNumber
ON s.EmployeeNumber = e.EmployeeNumber;
GOSELECT e.LastName + N', ' + e.FirstName AS [Full Name],
AVG(s.Amount) AS [Average Sales]
FROM Sales s INNER JOIN Employees e
ON s.EmployeeNumber = e.EmployeeNumber
HAVING e.EmployeeNumber;
GOCREATE SCHEMA Listing;
GO
CREATE TABLE Listing.Apartments
(
UnitNumber int not null,
Bedrooms int,
Bathrooms real,
Price money,
Deposit money,
Available bit
);
GO
INSERT Listing.Apartments
VALUES(104, 2, 1.00, 1050.00, 300.00, 0),
(306, 3, 2.00, 1350.00, 425.00, 1),
(105, 1, 1.00, 885.00, 250.00, 1),
(202, 1, 1.00, 950.00, 325.00, 0),
(304, 2, 2.00, 1250.00, 300.00, 0),
(106, 3, 2.00, 1350.00, 425.00, 1),
(308, 0, 1.00, 875.00, 225.00, 1),
(203, 1, 1.00, 885.00, 250.00, 1),
(204, 2, 2.00, 1125.00, 425.00, 1),
(205, 1, 1.00, 1055.00, 350.00, 0);
GO
What codes can Martha write to get a list of available apartments from the second floor
(Select 2)?
SELECT * FROM Listing.Apartments WHERE UnitNumber IN(200, 299) AND (Available = 1); GO
SELECT * FROM Listing.Apartments WHERE (UnitNumber >= 200) AND (UnitNumber <= 299) AND (Available = 1); GO
SELECT * FROM Listing.Apartments WHERE (UnitNumber BETWEEN 200 AND 299) AND (Available = 1); GO
SELECT * FROM Listing.Apartments WHERE UnitNumber IN(200, 299) OR (Available = TRUE); GO
SELECT * FROM Listing.Apartments WHERE UnitNumber >= 200 AND Available IS NOT NULL; GO
CREATE SCHEMA Personnel;
GO
CREATE SCHEMA Payroll;
GO
CREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money
);
GO
CREATE TABLE Payroll.TimeSheets
(
TimeSheetID int identity(1, 1) not null primary key,
EmployeeNumber nchar(7) not null
foreign key references Personnel.Employees(EmployeeNumber),
DateWorked date,
TimeWorked decimal(6, 2)
);
GO
INSERT Personnel.Employees
VALUES(N'795-074', N'Steve', N'Leland', 16.46),
(N'240-157', N'Alex', N'Randt', 10.55),
(N'482-259', N'Janice', N'Lane', 8.64),
(N'628-113', N'Jimmy', N'Walters', 20.24);
GO
INSERT INTO Payroll.TimeSheets(EmployeeNumber, DateWorked, TimeWorked)
VALUES(N'240-157', N'2011-04-04', 8.00),
(N'628-113', N'2011-04-04', 9.50),
(N'795-074', N'2011-04-04', 8.00),
(N'482-259', N'2011-04-04', 6.50),
(N'795-074', N'2011-04-05', 8.50),
(N'482-259', N'2011-04-05', 8.00),
(N'240-157', N'2011-04-05', 9.50),
(N'628-113', N'2011-04-05', 7.50),
(N'795-074', N'2011-04-06', 8.00),
(N'240-157', N'2011-04-06', 8.50),
(N'795-074', N'2011-04-07', 10.00),
(N'628-113', N'2011-04-07', 8.00);
GO
How can he write code to get a list that contains the employee number,
the date he or she worked, and the time spent at work, without repeating
records?
SELECT empl.EmployeeNumber [Empl #],
pts.DateWorked [Date Worked],
pts.TimeWorked [Time Worked]
FROM Personnel.Employees empl INNER JOIN Payroll.TimeSheets pts;
GOSELECT empl.FirstName [First Name], empl.LastName [Last Name],
pts.DateWorked [Date Worked],
pts.TimeWorked [Time Worked]
FROM Personnel.Employees empl OUTER JOIN Payroll.TimeSheets pts;
GOSELECT empl.EmployeeNumber [Empl #],
pts.DateWorked [Date Worked],
pts.TimeWorked [Time Worked]
FROM Personnel.Employees empl, Payroll.TimeSheets pts;
GOSELECT pts.EmployeeNumber [Empl #],
pts.DateWorked [Date Worked],
pts.TimeWorked [Time Worked]
FROM Payroll.TimeSheets pts;
GOSELECT DISTINCT empl.EmployeeNumber [Empl #],
pts.DateWorked [Date Worked],
pts.TimeWorked [Time Worked]
FROM Personnel.Employees empl, Payroll.TimeSheets pts;
GOCREATE SCHEMA Personnel;
GO
CREATE SCHEMA Payroll;
GO
CREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money
);
GO
CREATE TABLE Payroll.TimeSheets
(
TimeSheetID int identity(1, 1) not null primary key,
EmployeeNumber nchar(7) not null
foreign key references Personnel.Employees(EmployeeNumber),
DateWorked date,
TimeWorked decimal(6, 2)
);
GO
INSERT Personnel.Employees
VALUES(N'795-074', N'Steve', N'Leland', 16.46),
(N'240-157', N'Alex', N'Randt', 10.55),
(N'482-259', N'Janice', N'Lane', 8.64),
(N'628-113', N'Jimmy', N'Walters', 20.24);
GO
INSERT INTO Payroll.TimeSheets(EmployeeNumber, DateWorked, TimeWorked)
VALUES(N'240-157', N'2011-04-04', 8.00),
(N'628-113', N'2011-04-04', 9.50),
(N'795-074', N'2011-04-04', 8.00),
(N'482-259', N'2011-04-04', 6.50),
(N'795-074', N'2011-04-05', 8.50),
(N'482-259', N'2011-04-05', 8.00),
(N'240-157', N'2011-04-05', 9.50),
(N'628-113', N'2011-04-05', 7.50),
(N'795-074', N'2011-04-06', 8.00),
(N'240-157', N'2011-04-06', 8.50),
(N'795-074', N'2011-04-07', 10.00),
(N'628-113', N'2011-04-07', 8.00);
GO
He want to get a list that contains the employee number,
the first name, the last name, the date worked, and the time worked, without repeating
records. What code can he write to get that list?
SELECT empl.EmployeeNumber [Empl #],
empl.FirstName [First Name],
empl.LastName [Last Name],
pts.DateWorked [Date Worked],
pts.TimeWorked [Time Worked]
FROM Personnel.Employees empl INNER JOIN Payroll.TimeSheets pts
ON empl.EmployeeNumber = pts.EmployeeNumber;
GOSELECT empl.EmployeeNumber [Empl #],
empl.FirstName [First Name],
empl.LastName [Last Name],
pts.DateWorked [Date Worked],
pts.TimeWorked [Time Worked]
FROM Personnel.Employees empl CROSS JOIN Payroll.TimeSheets pts
ON empl.EmployeeNumber = pts.EmployeeNumber;
GOSELECT empl.EmployeeNumber [Empl #],
empl.FirstName + N' ' + empl.LastName [Full Name],
pts.DateWorked [Date Worked],
pts.TimeWorked [Time Worked]
FROM Personnel.Employees empl LEFT INNER JOIN Payroll.TimeSheets pts
ON empl.EmployeeNumber = pts.EmployeeNumber;
GO
SELECT DISTINCT(empl.EmployeeNumber,
empl.FirstName,
empl.LastName),
pts.DateWorked [Date Worked],
pts.TimeWorked [Time Worked]
FROM Personnel.Employees empl LEFT INNER JOIN Payroll.TimeSheets pts
ON empl.EmployeeNumber = pts.EmployeeNumber;
GO
SELECT empl.EmployeeNumber [Empl #],
empl.FirstName [First Name],
empl.LastName [Last Name],
pts.DateWorked [Date Worked],
pts.TimeWorked [Time Worked]
FROM Personnel.Employees empl LEFT JOIN Payroll.TimeSheets pts
ON empl.EmployeeNumber = pts.EmployeeNumber
GROUP BY pts.EmployeeNumber;
GO
CREATE SCHEMA Personnel;
GO
CREATE SCHEMA Payroll;
GO
CREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money
);
GO
CREATE TABLE Payroll.TimeSheets
(
TimeSheetID int identity(1, 1) not null primary key,
EmployeeNumber nchar(7) not null
foreign key references Personnel.Employees(EmployeeNumber),
DateWorked date,
TimeWorked decimal(6, 2)
);
GO
INSERT Personnel.Employees
VALUES(N'795-074', N'Steve', N'Leland', 16.46),
(N'240-157', N'Alex', N'Randt', 10.55),
(N'482-259', N'Janice', N'Lane', 8.64),
(N'628-113', N'Jimmy', N'Walters', 20.24);
GO
INSERT INTO Payroll.TimeSheets(EmployeeNumber, DateWorked, TimeWorked)
VALUES(N'240-157', N'2011-04-04', 8.00),
(N'628-113', N'2011-04-04', 9.50),
(N'795-074', N'2011-04-04', 8.00),
(N'482-259', N'2011-04-04', 6.50),
(N'795-074', N'2011-04-05', 8.50),
(N'482-259', N'2011-04-05', 8.00),
(N'240-157', N'2011-04-05', 9.50),
(N'628-113', N'2011-04-05', 7.50),
(N'795-074', N'2011-04-06', 8.00),
(N'240-157', N'2011-04-06', 8.50),
(N'795-074', N'2011-04-07', 10.00),
(N'628-113', N'2011-04-07', 8.00);
GO
What code can Leslie write to get a list that contains each employee number
and
the total time the employee worked during that time frame?
SELECT pts.EmployeeNumber [Empl #],
SUM(pts.TimeWorked [Time Worked])
FROM Payroll.TimeSheets pts
GROUP BY pts.EmployeeNumber
WHERE pts.EmployeeNumber IS NOT NULL;
GO
SELECT pts.EmployeeNumber [Empl #],
SUM(pts.TimeWorked [Time Worked])
FROM Payroll.TimeSheets pts
GROUP BY pts.EmployeeNumber
HAVING pts.EmployeeNumber IS NOT NULL;
GO
SELECT pts.EmployeeNumber [Empl #],
SUM(pts.TimeWorked) [Time Worked]
FROM Payroll.TimeSheets pts
GROUP BY pts.EmployeeNumber;
GOSELECT pts.EmployeeNumber [Empl #],
SUM(pts.TimeWorked) [Time Worked]
GROUP BY pts.EmployeeNumber
FROM Payroll.TimeSheets pts;
GOSELECT pts.EmployeeNumber [Empl #],
SUM(pts.TimeWorked) [Time Worked]
FROM Payroll.TimeSheets pts
GROUP BY pts.TimeWorked;
GOCREATE SCHEMA Personnel;
GO
CREATE SCHEMA Payroll;
GO
CREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money
);
GO
CREATE TABLE Payroll.TimeSheets
(
TimeSheetID int identity(1, 1) not null primary key,
EmployeeNumber nchar(7) not null
foreign key references Personnel.Employees(EmployeeNumber),
DateWorked date,
TimeWorked decimal(6, 2)
);
GO
INSERT Personnel.Employees
VALUES(N'795-074', N'Steve', N'Leland', 16.46),
(N'240-157', N'Alex', N'Randt', 10.55),
(N'482-259', N'Janice', N'Lane', 8.64),
(N'628-113', N'Jimmy', N'Walters', 20.24);
GO
INSERT INTO Payroll.TimeSheets(EmployeeNumber, DateWorked, TimeWorked)
VALUES(N'240-157', N'2011-04-04', 8.00),
(N'628-113', N'2011-04-04', 9.50),
(N'795-074', N'2011-04-04', 8.00),
(N'482-259', N'2011-04-04', 6.50),
(N'795-074', N'2011-04-05', 8.50),
(N'482-259', N'2011-04-05', 8.00),
(N'240-157', N'2011-04-05', 9.50),
(N'628-113', N'2011-04-05', 7.50),
(N'795-074', N'2011-04-06', 8.00),
(N'240-157', N'2011-04-06', 8.50),
(N'795-074', N'2011-04-07', 10.00),
(N'628-113', N'2011-04-07', 8.00);
GO
He want to get a list that contains the employee's name
(made of
the first name followed by space and the last name) and the time worked, without repeating
records. What code can he write to get that list?
SELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked]
FROM Payroll.TimeSheets pts JOIN Personnel.Employees empls
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY empls.FirstName + N' ' + empls.LastName;
GOSELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked]
FROM Payroll.TimeSheets pts LEFT OUTER JOIN Personnel.Employees empls
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY empls.EmployeeNumber;
GOSELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked]
FROM Payroll.TimeSheets pts LEFT OUTER JOIN Personnel.Employees empls
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY pts.TimeWorked;
GOSELECT DISTINCT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked]
FROM Payroll.TimeSheets pts CROSS JOIN Personnel.Employees empls
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY empls.FirstName + N' ' + empls.LastName;
GOSELECT DISTINCT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked]
ON pts.EmployeeNumber = empls.EmployeeNumber
FROM Payroll.TimeSheets pts CROSS JOIN Personnel.Employees empls
GROUP BY pts.EmployeeNumber;
GOCREATE SCHEMA Personnel;
GO
CREATE SCHEMA Payroll;
GO
CREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money
);
GO
CREATE TABLE Payroll.TimeSheets
(
TimeSheetID int identity(1, 1) not null primary key,
EmployeeNumber nchar(7) not null
foreign key references Personnel.Employees(EmployeeNumber),
DateWorked date,
TimeWorked decimal(6, 2)
);
GO
INSERT Personnel.Employees
VALUES(N'795-074', N'Steve', N'Leland', 16.46),
(N'240-157', N'Alex', N'Randt', 10.55),
(N'482-259', N'Janice', N'Lane', 8.64),
(N'628-113', N'Jimmy', N'Walters', 20.24);
GO
INSERT INTO Payroll.TimeSheets(EmployeeNumber, DateWorked, TimeWorked)
VALUES(N'240-157', N'2011-04-04', 8.00),
(N'628-113', N'2011-04-04', 9.50),
(N'795-074', N'2011-04-04', 8.00),
(N'482-259', N'2011-04-04', 6.50),
(N'795-074', N'2011-04-05', 8.50),
(N'482-259', N'2011-04-05', 8.00),
(N'240-157', N'2011-04-05', 9.50),
(N'628-113', N'2011-04-05', 7.50),
(N'795-074', N'2011-04-06', 8.00),
(N'240-157', N'2011-04-06', 8.50),
(N'795-074', N'2011-04-07', 10.00),
(N'628-113', N'2011-04-07', 8.00);
GO
He want to
create a list that shows the employee's name
(made of
the first name followed a space and the last name), the time worked, and the
weekly salary that mulitplies the time worked by the employee's hourly
salary. What code can he write to get that list?
SELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked],
SUM(pts.TimeWorked * empls.HourlySalary) [Weekly Salary]
FROM Payroll.TimeSheets pts JOIN Personnel.Employees empls
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY empls.FirstName + N' ' + empls.LastName;
GOSELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked],
pts.TimeWorked * empls.HourlySalary AS [Weekly Salary]
FROM Payroll.TimeSheets pts JOIN Personnel.Employees empls
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY empls.FirstName + N' ' + empls.LastName;
GOSELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked],
SUM(pts.TimeWorked) * SUM(empls.HourlySalary) AS [Weekly Salary]
FROM Payroll.TimeSheets pts JOIN Personnel.Employees empls
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY empls.FirstName + N' ' + empls.LastName;
GOSELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked],
MAX(pts.TimeWorked * empls.HourlySalary) AS [Weekly Salary]
FROM Payroll.TimeSheets pts JOIN Personnel.Employees empls
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY empls.FirstName + N' ' + empls.LastName;
GOSELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked],
VAL(pts.TimeWorked) * VAL(empls.HourlySalary) AS [Weekly Salary]
FROM Payroll.TimeSheets pts JOIN Personnel.Employees empls
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY empls.FirstName + N' ' + empls.LastName;
GO
CREATE SCHEMA Personnel;
GO
CREATE SCHEMA Payroll;
GO
CREATE TABLE Personnel.Employees
(
EmployeeNumber nchar(7) not null primary key,
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money
);
GO
CREATE TABLE Payroll.TimeSheets
(
TimeSheetID int identity(1, 1) not null primary key,
EmployeeNumber nchar(7) not null
foreign key references Personnel.Employees(EmployeeNumber),
DateWorked date,
TimeWorked decimal(6, 2)
);
GO
INSERT Personnel.Employees
VALUES(N'795-074', N'Steve', N'Leland', 16.46),
(N'240-157', N'Alex', N'Randt', 10.55),
(N'482-259', N'Janice', N'Lane', 8.64),
(N'628-113', N'Jimmy', N'Walters', 20.24);
GO
INSERT INTO Payroll.TimeSheets(EmployeeNumber, DateWorked, TimeWorked)
VALUES(N'240-157', N'2011-04-04', 8.00),
(N'628-113', N'2011-04-04', 9.50),
(N'795-074', N'2011-04-04', 8.00),
(N'482-259', N'2011-04-04', 6.50),
(N'795-074', N'2011-04-05', 8.50),
(N'482-259', N'2011-04-05', 8.00),
(N'240-157', N'2011-04-05', 9.50),
(N'628-113', N'2011-04-05', 7.50),
(N'795-074', N'2011-04-06', 8.50),
(N'482-259', N'2011-04-04', 6.50),
(N'240-157', N'2011-04-06', 9.50),
(N'795-074', N'2011-04-07', 10.00),
(N'628-113', N'2011-04-07', 8.00),
(N'240-157', N'2011-04-07', 10.00),
(N'240-157', N'2011-04-08', 8.50),
(N'482-259', N'2011-04-08', 6.00),
(N'628-113', N'2011-04-08', 8.00),
(N'795-074', N'2011-04-08', 7.50);
GO
To evaluate the overtime of employees, Daouda wants to get a list that contains the employee's name
(made of
the first name followed by space and the last name) and the time worked,
only for employees who worked over 40 hours. What code can he write to get that list?
SELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked]
FROM Payroll.TimeSheets pts JOIN Personnel.Employees empls
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY empls.FirstName + N' ' + empls.LastName
WHERE SUM(pts.TimeWorked) >= 40.00;
GOSELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked]
FROM Payroll.TimeSheets pts INNER JOIN Personnel.Employees empls
WHERE SUM(pts.TimeWorked) >= 40.00;
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY empls.FirstName + N' ' + empls.LastName
GOSELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked]
FROM Payroll.TimeSheets pts JOIN Personnel.Employees empls
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY empls.FirstName + N' ' + empls.LastName
HAVING SUM(pts.TimeWorked) >= 40.00;
GOSELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked]
FROM Payroll.TimeSheets pts INNER JOIN Personnel.Employees empls
HAVING SUM(pts.TimeWorked) >= 40.00;
ON pts.EmployeeNumber = empls.EmployeeNumber
GROUP BY empls.FirstName + N' ' + empls.LastName
GOSELECT empls.FirstName + N' ' + empls.LastName [Full Name],
SUM(pts.TimeWorked) [Time Worked]
FROM Payroll.TimeSheets pts INNER JOIN Personnel.Employees empls
ON pts.EmployeeNumber = empls.EmployeeNumber
HAVING SUM(pts.TimeWorked) >= 40.00
GROUP BY empls.FirstName + N' ' + empls.LastName;
GOCREATE OBJECT DATABASE KoloBank
ON PRIMARY
WITH FILEGROUP = KoloBank1
( NAME = N'KoloBankMain',
FILENAME = N'C:\Kolo Bank Primary\KoloBankMain.mdf',
SIZE = 100MB,
MAXSIZE = 500MB,
FILEGROWTH = 10MB),
FILEGROUP KoloBankPrimary
( NAME = N'KoloBankFirst',
FILENAME = N'C:\Kolo Bank Primary\KoloBankFirst.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB),
FILEGROUP = KoloBankSecondary
( NAME = N'KoloBankSecond',
FILENAME = N'D:\Kolo Bank Secondary\KoloBankSecondady.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB)
LOG ON FILEGROUP = KoloBankLog
( NAME = N'KoloBankLog',
FILENAME = N'C:\Kolo Bank Logs\KoloBankLogger.ldf',
SIZE = 10MB,
MAXSIZE = 20MB,
FILEGROWTH = 2MB);
GOCREATE DATABASE KoloBank
ON PRIMARY
( NAME = N'KoloBankMain',
FILENAME = N'C:\Kolo Bank Primary\KoloBankMain.mdf',
SIZE = 100MB,
MAXSIZE = 500MB,
FILEGROWTH = 10MB),
FILEGROUP KoloBankPrimary
( NAME = N'KoloBankFirst',
FILENAME = N'C:\Kolo Bank Primary\KoloBankFirst.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB),
FILEGROUP KoloBankSecondary
( NAME = N'KoloBankSecond',
FILENAME = N'D:\Kolo Bank Secondary\KoloBankSecondady.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB)
LOG ON
( NAME = N'KoloBankLog',
FILENAME = N'C:\Kolo Bank Logs\KoloBankLogger.ldf',
SIZE = 10MB,
MAXSIZE = 20MB,
FILEGROWTH = 2MB);
GOCREATE OBJECT::KoloBank
AS DATABASE
ON PRIMARY
WITH FILEGROUP = KoloBank1
( NAME = N'KoloBankMain',
FILENAME = N'C:\Kolo Bank Primary\KoloBankMain.mdf',
SIZE = 100MB,
MAXSIZE = 500MB,
FILEGROWTH = 10MB),
WITH SECONDARY FILEGROUP = KoloBankPrimary
( NAME = N'KoloBankFirst',
FILENAME = N'C:\Kolo Bank Primary\KoloBankFirst.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB),
WITH SECONDARY FILEGROUP = KoloBankSecondary
( NAME = N'KoloBankSecond',
FILENAME = N'D:\Kolo Bank Secondary\KoloBankSecondady.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB)
WITH LOG FILEGROUP = KoloBankLog
( NAME = N'KoloBankLog',
FILENAME = N'C:\Kolo Bank Logs\KoloBankLogger.ldf',
SIZE = 10MB,
MAXSIZE = 20MB,
FILEGROWTH = 2MB);
GOCREATE DATABASE KoloBank
ON PRIMARY
WITH PRIMARY FILEGROUP KoloBank1
( NAME = N'KoloBankMain',
FILENAME = N'C:\Kolo Bank Primary\KoloBankMain.mdf',
SIZE = 100MB,
MAXSIZE = 500MB,
FILEGROWTH = 10MB),
WITH SECONDARY FILEGROUP KoloBankPrimary
( NAME = N'KoloBankFirst',
FILENAME = N'C:\Kolo Bank Primary\KoloBankFirst.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB),
WITH SECONDARY FILEGROUP ADD KoloBankSecondary
( NAME = N'KoloBankSecond',
FILENAME = N'D:\Kolo Bank Secondary\KoloBankSecondady.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB)
ON LOG FILEGROUP KoloBankLog
( NAME = N'KoloBankLog',
FILENAME = N'C:\Kolo Bank Logs\KoloBankLogger.ldf',
SIZE = 10MB,
MAXSIZE = 20MB,
FILEGROWTH = 2MB);
GOCREATE DATABASE KoloBank
PRIMARY FILEGROUP = KoloBank1
( NAME = N'KoloBankMain',
FILENAME = N'C:\Kolo Bank Primary\KoloBankMain.mdf',
SIZE = 100MB,
MAXSIZE = 500MB,
FILEGROWTH = 10MB),
SECONDARY FILEGROUP = KoloBankPrimary
( NAME = N'KoloBankFirst',
FILENAME = N'C:\Kolo Bank Primary\KoloBankFirst.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB),
SECONDARY FILEGROUP = KoloBankSecondary
( NAME = N'KoloBankSecond',
FILENAME = N'D:\Kolo Bank Secondary\KoloBankSecondady.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB)
ON LOG FILEGROUP = KoloBankLog
( NAME = N'KoloBankLog',
FILENAME = N'C:\Kolo Bank Logs\KoloBankLogger.ldf',
SIZE = 10MB,
MAXSIZE = 20MB,
FILEGROWTH = 2MB);
GOCREATE DATABASE KoloBank
ON PRIMARY
( NAME = N'KoloBankMain',
FILENAME = N'C:\Kolo Bank Primary\KoloBankMain.mdf',
SIZE = 100MB,
MAXSIZE = 500MB,
FILEGROWTH = 10MB),
FILEGROUP KoloBankPrimary
( NAME = N'KoloBankFirst',
FILENAME = N'C:\Kolo Bank Primary\KoloBankFirst.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB),
FILEGROUP KoloBankSecondary
( NAME = N'KoloBankSecond',
FILENAME = N'D:\Kolo Bank Secondary\KoloBankSecondady.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB)
LOG ON
( NAME = N'KoloBankLog',
FILENAME = N'C:\Kolo Bank Logs\KoloBankLogger.ldf',
SIZE = 10MB,
MAXSIZE = 20MB,
FILEGROWTH = 2MB);
GO
Because of the large volume of records that the project will have, the
database must be partitioned. To start, Brian has been asked to create a
function that will partition records from left to right. The column used to manage the partitions will be of type
int. What code can Brian
use to create the partitions?
USE KoloBank; GO CREATE PARTITION FUNCTION KoloBankPartitions(int) WITH VALUES(1) IN RANGE LEFT; GO
USE KoloBank; GO CREATE FUNCTION KoloBankPartitions(int) RETURNS PARTITION FOR VALUES(1) AS RANGE LEFT; GO
USE KoloBank; GO CREATE OBJECT::FUNCTION KoloBankPartitions(int) AS PARTITION FOR VALUES(1) AS RANGE LEFT; GO
USE KoloBank; GO CREATE PARTITION FUNCTION KoloBankPartitions(int) AS RANGE LEFT FOR VALUES(1); GO
USE KoloBank; GO CREATE PARTITION FUNCTION KoloBankPartitions(int) FOR VALUES(1) AS RANGE LEFT; GO
CREATE DATABASE KoloBank
ON PRIMARY
( NAME = N'KoloBankMain',
FILENAME = N'C:\Kolo Bank Primary\KoloBankMain.mdf',
SIZE = 100MB,
MAXSIZE = 500MB,
FILEGROWTH = 10MB),
FILEGROUP KoloBankPrimary
( NAME = N'KoloBankFirst',
FILENAME = N'C:\Kolo Bank Primary\KoloBankFirst.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB),
FILEGROUP KoloBankSecondary
( NAME = N'KoloBankSecond',
FILENAME = N'D:\Kolo Bank Secondary\KoloBankSecondady.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB)
LOG ON
( NAME = N'KoloBankLog',
FILENAME = N'C:\Kolo Bank Logs\KoloBankLogger.ldf',
SIZE = 10MB,
MAXSIZE = 20MB,
FILEGROWTH = 2MB);
GO
Based on the large volume of records that the project will have, the
database must be partitioned. A partition function was already created as follows:
USE KoloBank; GO CREATE PARTITION FUNCTION KoloBankPartitions(int) AS RANGE LEFT FOR VALUES(1); GOTo tie the file groups to the scheme, Brian must create a partition function. How can he write code to create the appropriate partition scheme?
USE KoloBank; GO CREATE PARTITION SCHEME KoloBankScheme AS PARTITION KoloBankPartitions TO (KoloBankPrimary, KoloBankSecondary); GO
CREATE FUNCTION KoloBankScheme AS PARTITION SCHEME WITH PARTITION KoloBankPartitions FOR (KoloBankPrimary, KoloBankSecondary); GO
CREATE OBJECT::KoloBankScheme RETURNS PARTITION SCHEME FOR PARTITION KoloBankPartitions ON (KoloBankPrimary, KoloBankSecondary); GO
CREATE PARTITION SCHEME KoloBankScheme FOR PARTITION KoloBankPartitions ON (KoloBankPrimary, KoloBankSecondary); GO
CREATE OBJECT::KoloBankScheme AS PARTITION SCHEME ON PARTITION KoloBankPartitions TO (KoloBankPrimary, KoloBankSecondary); GO
CREATE DATABASE KoloBank
ON PRIMARY
( NAME = N'KoloBankMain',
FILENAME = N'C:\Kolo Bank Primary\KoloBankMain.mdf',
SIZE = 100MB,
MAXSIZE = 500MB,
FILEGROWTH = 10MB),
FILEGROUP KoloBankPrimary
( NAME = N'KoloBankFirst',
FILENAME = N'C:\Kolo Bank Primary\KoloBankFirst.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB),
FILEGROUP KoloBankSecondary
( NAME = N'KoloBankSecond',
FILENAME = N'D:\Kolo Bank Secondary\KoloBankSecondady.ndf',
SIZE = 20MB,
MAXSIZE = 100MB,
FILEGROWTH = 2MB)
LOG ON
( NAME = N'KoloBankLog',
FILENAME = N'C:\Kolo Bank Logs\KoloBankLogger.ldf',
SIZE = 10MB,
MAXSIZE = 20MB,
FILEGROWTH = 2MB);
GO
Another colleague created a partition function and a partition scheme:
USE KoloBank; GO CREATE PARTITION FUNCTION KoloBankPartitions(int) AS RANGE LEFT FOR VALUES(1); GO CREATE PARTITION SCHEME KoloBankScheme AS PARTITION KoloBankPartitions TO (KoloBankPrimary, KoloBankSecondary); GOAs the main database developer, Julia has to create a table that will store customers records. Among others, the table will have a column named CustomerID of type int. The above partition scheme will decide what file group must hold the records. How should the table be created?
WITH KoloBankScheme
CREATE TABLE Customers
(
CustomerID int identity(1, 1) primary key,
AccountNumber nchar(10) not null,
FirstName nvarchar(20),
LastName nvarchar(20) not null
)
USE CustomerID AS PARTITION;
GOCREATE TABLE Customers
(
CustomerID int identity(1, 1) primary key
WITH KoloBankScheme,
AccountNumber nchar(10) not null,
FirstName nvarchar(20),
LastName nvarchar(20) not null
);
GOCREATE TABLE Customers
(
CustomerID int identity(1, 1) primary key,
AccountNumber nchar(10) not null,
FirstName nvarchar(20),
LastName nvarchar(20) not null
) ON KoloBankScheme(CustomerID);
GOCREATE TABLE Customers1
(
CustomerID int identity(1, 1) primary key,
AccountNumber nchar(10) not null,
FirstName nvarchar(20),
LastName nvarchar(20) not null
);
SET PARTITION::KoloBankScheme FOR CustomerID;
GOUSING KoloBankScheme(CustomerID)
CREATE TABLE Customers
(
CustomerID int identity(1, 1) primary key,
AccountNumber nchar(10) not null,
FirstName nvarchar(20),
LastName nvarchar(20) not null
);
GO
CREATE TABLE Employees
(
EmployeeNumber nchar(60),
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money,
FullName AS LastName + N', ' + FirstName,
);
GO
He wants the value of the FullName column
to be saved in memory as an actual value. If it is possible, how should Marc
modify code to make it happen?
CREATE TABLE Employees
(
EmployeeNumber nchar(60),
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money,
FullName AS LastName + N', ' + FirstName PERSISTED,
);
GOCREATE TABLE Employees
(
EmployeeNumber nchar(60),
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money,
PERSIST FullName AS LastName + N', ' + FirstName,
);
GOCREATE TABLE Employees
(
EmployeeNumber nchar(60),
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money,
FullName AS LastName + N', ' + FirstName CONSTRAINT PERSITENT,
);
GOCREATE TABLE Employees
(
EmployeeNumber nchar(60),
FirstName nvarchar(20),
LastName nvarchar(20),
HourlySalary money,
FullName AS LastName + N', ' + FirstName,
CONSTRAINT P_FullName PERSISTANCE(FullName)
);
GO|
Answers |
SET IDENTITY_INSERT Products OFF; GO
USE SuperMarket1; GO GRANT SELECT ON OBJECT::Personnel.Employees TO [Hermine]; GO
SELECT TeacherID, FullName, Teachers.CourseID FROM Teachers
|
|
||
| Previous | Copyright © 2009-2011 FunctionX.com | Next |
|
|
||