• Embed Doc
  • Readcast
  • Collections
  • 1
    CommentGo Back
 
Bonus Reference
Transact-SQL
In Chapter 20, you built
SQL statements to retrieve and update rows in a database. Youalso learned all the variations of the SELECT statement. Some restrictions, however, can’t beexpressed with a WHERE clause, no matter how complicated. To perform complicated searches,many programmers would rather write an application to retrieve the desired rows, process them,and then display some results. The processing could include running totals, formatting of thequery’s output, calculations involving multiple rows of the same table, and so on.Most database management systems include extensions, which enhance SQL and make itbehave more like a programming language. SQL Server provides a set of statements known as
Transact-SQL (T-SQL) 
. T-SQL recognizes statements that fetch rows from one or more tables,flow-control statements like IF…ELSE and WHILE, and numerous functions to manipulatestrings, numeric values, and dates, similar to Visual Basic’s functions. With T-SQL you can doeverything that can be done with SQL, as well as program these operations. At the very least, youcan attach lengthy SQL statements to a database as stored procedures, so that you can call them byname. In addition, you can use parameters, so that the same procedure can act on different data.This chapter is an overview of T-SQL and demonstrates the basic topic with stored proce-dures that perform complicated tasks on the server. We’ll start with the COMPUTE BY state-ment, which allows you to calculate totals on groups of the rows retrieved from the database.This statement looks and feels very much like the straight SQL statements, yet it’s not part of standard SQL.Then we’ll look at T-SQL in depth. If you need to look up a function or how to declare astored procedure’s arguments, you can use this chapter as reference material. If you’re new toT-SQL, you should read this material, because T-SQL is a powerful language, and if you’reworking with or plan to switch to SQL Server, you’ll need it sooner or later. In addition, you’llimprove your Visual Basic programming. T-SQL is the native language of SQL Server. By seeinghow the basic operations can be implemented in T-SQL and VB, you’ll gain a deeper under-standing of database programming.
 
The COMPUTE BY Clause
As you recall from Chapter 20, SQL SELECT statements return a set of rows, all of whichhave the same structure. In other words, a SQL query can return either details or totals, but notboth. For example, you can calculate the order totals for all customers with a GROUP BY clause,but this clause displays totals only. Let’s say you want a list of all customers in the Northwind data-base, their orders, and the total for each customer. Listing 1 provides a SQL SELECT statementthat retrieves the desired information from the database.
Listing 1: The OrderTotals.sql Query
USE NORTHWINDSELECT CompanyName, Orders.OrderID,SUM([Order Details].UnitPrice * Quantity * (1 - Discount))FROM Products, [Order Details], Customers, OrdersWHERE [Order Details].ProductID = Products.ProductID AND[Order Details].OrderID = Orders.OrderID ANDOrders.CustomerID=Customers.CustomerIDGROUP BY CompanyName, Orders.OrderIDORDER BY CompanyName, Orders.OrderID
This statement calculates the totals for each order. The
Orders.OrderID
field is included in theGROUP BY clause because it’s part of the SELECT list, but doesn’t appear in an aggregate func-tion’s arguments. This statement will display groups of customers and the totals for all orders placedby each customer:
Alfreds Futterkiste 10643 814.5Alfreds Futterkiste 10692 878.0Alfreds Futterkiste 10702 330.0Alfreds Futterkiste 10835 845.80Alfreds Futterkiste 10952 471.20Alfreds Futterkiste 11011 933.5Ana Trujillo Emparedados y helados 10308 88.80Ana Trujillo Emparedados y helados 10625 479.75. . .
If you want to see the totals per customer, you must modify Listing 1 as follows:
USE NORTHWINDSELECT CompanyName,SUM([Order Details].UnitPrice * Quantity * (1 - Discount))FROM Products, [Order Details], Customers, OrdersWHERE [Order Details].ProductID = Products.ProductID AND[Order Details].OrderID = Orders.OrderID ANDOrders.CustomerID=Customers.CustomerIDGROUP BY CompanyNameORDER BY CompanyName
Bonus Reference
TRANSACT-SQL
chT2
 
This time I’ve omitted the
Orders.OrderID
field from the SELECT list and the GROUP BYclause. This statement will display the total for each customer, since we are not grouping byOrderID:
Alfreds Futterkiste 4272.9999980926514Ana Trujillo Emparedados y helados 1402.9500007629395Antonio Moreno Taquería 7023.9775543212891Around the Horn 13390.650009155273Berglunds snabbköp 24927.57746887207. . .
What we need is a statement that can produce a report of the details with total breaks after eachorder and each customer, as shown here (I have shortened the product names to fit the lines on theprinted page without breaks):
Alfreds Futterkiste 10643 Rössle 45.60 15 25 513.00Alfreds Futterkiste 10643 Chartreuse 18.0 21 25 283.50Alfreds Futterkiste 10643 Spegesild 12.0 2 25 18.00814.50Alfreds Futterkiste 10692 Vegie-spread 43.90 20 0 878.00878.00Alfreds Futterkiste 10702 Aniseed Syrup 10.0 6 0 60.00Alfreds Futterkiste 10702 Lakkalikööri 18.0 15 0 270.00845.80Alfreds Futterkiste 10952 Grandma’s 25.00 16 5 380.00Alfreds Futterkiste 10952 Rössle 45.6 2 0 91.20471.20Alfreds Futterkiste 11011 Escargots 13.25 40 5 503.50Alfreds Futterkiste 11011 Flotemysost 21.50 20 0 430.00933.504273.00Ana Trujillo 10308 Gudbrand 28.80 1 0 28.80Ana Trujillo 10308 Outback 12.00 5 0 60.0088.80Ana Trujillo 10625 Tofu 23.25 3 0 69.75Ana Trujillo 10625 Singaporean 14.00 5 0 70.00Ana Trujillo 10625 Camembert 34.00 10 0 340.00479.75
T-SQL provides an elegant solution to this problem with the COMPUTE BY clause. TheCOMPUTE BY clause calculates aggregate functions (sums, counts, and so on) while a field doesn’tchange value. This field is specified with the BY keyword. When the field changes value, the totalcalculated so far is displayed and the aggregate function is reset. To produce the list shown here, youmust calculate the sum of line totals (quantity
×
price – discount) and group the calculations accord-ing to OrderID and CustomerID. Listing 2 presents the complete statement that produced the pre-ceding subtotaled list.
chT3
THE COMPUTE BY CLAUSE
of 00

Leave a Comment

You must be to leave a comment.
Submit
Characters: ...
You must be to leave a comment.
Submit
Characters: ...