Murach’s SQL for SQL Server – Exercise 13 – Guaranteed 100% Score
1. Write a script that declares and sets a variable that’s equal to the total outstanding
balance due. If that balance due is greater than $10,000.00, the script should return a
result set consisting of VendorName, InvoiceNumber, InvoiceDueDate, and Balance
for each invoice with a balance due, sorted with the oldest due date first. If the total
outstanding balance due is less than $10,000.00, return the message “Balance due is
less than $10,000.00.”
2. The following script uses a derived table to return the date and invoice total of the
earliest invoice issued by each vendor. Write a script that generates the same result
set but uses a temporary table in place of the derived table. Make sure your script
tests for the existence of any objects it creates.
USE AP
SELECT VendorName, FirstInvoiceDate, InvoiceTotal
FROM Invoices JOIN
(SELECT VendorID, MIN(InvoiceDate) AS FirstInvoiceDate
FROM Invoices
GROUP BY VendorID) AS FirstInvoice
ON (Invoices.VendorID = FirstInvoice.VendorID AND
Invoices.InvoiceDate = FirstInvoice.FirstInvoiceDate)
JOIN Vendors
ON Invoices.VendorID = Vendors.VendorID
ORDER BY VendorName, FirstInvoiceDate
3. Write a script that generates the same result set as the code shown in example 2, but
uses a view instead of a derived table. Also write the script that creates the view.
Make sure that your script tests for the existence of the view. The view doesn’t need
to be redefined each time the script is executed.
4. Write a script that uses dynamic SQL to return a single column that represents the
number of rows in a particular table in the current database. The script should
automatically choose the user base table that appears first alphabetically. Exclude
system tables, views, and the table named “dtproperties.” Name the column
CountOfTable, where Table is the chosen table name.
Hint: Use one of the information schema views.