1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning C# 2005 Databases From Novice to Professional phần 7 ppsx

52 286 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 52
Dung lượng 2,23 MB

Nội dung

Other Aggregates SQL has several built-in functions that aggregate the values of a column. Aggregate func- tions return a single value. For example, you can use the aggregate functions to calculate the total number or average value of orders placed. You can find the order with the least value or the most expensive order. Aggregate functions, as their name indicates, work on a set of records and then calculate the appropriate aggregated value. SUM, MIN, MAX, AVG, and COUNT are frequently used aggregate functions. Try It Out: Using the MIN, MAX, and AVG Functions Let’s find the minimum, maximum, and average number of items of each product from the Order Details table: 1. Enter the following query into SSMSE and execute it. You should see the results shown in Figure 11-7: select productid 'Product ID', min(quantity) 'Minimum', max(quantity) 'Maximum', avg(quantity) 'Average' from "order details" group by productid order by productid CHAPTER 11 ■ LEARNING MORE ABOUT QUERIES 287 777Xch11final.qxd 11/18/06 2:38 PM Page 287 Ho w It Works You use the MIN and MAX functions to find the minimum and maximum values, and you use the AVG function to calculate the average value: min(quantity) 'Minimum', max(quantity) 'Maximum', avg(quantity) 'Average' Since you want the results listed by product, you use the GROUP BY clause. From the result set, you see that product 1 has a minimum order quantity of 2, a maximum order quantity of 80, and an average order quantity of 21. ■Note You use an ORDER BY clause to assure the results are in product ID sequence. As with DISTINCT, some DBMSs would have inferred this sequence from the GROUP BY clause. But, in general, unless you explicitly use ORDER BY, you can’t predict the sequence of the rows in a result set. CHAPTER 11 ■ LEARNING MORE ABOUT QUERIES288 Figure 11-7. Using aggregate functions 777Xch11final.qxd 11/18/06 2:38 PM Page 288 Datetime Functions Although the SQL standard defines a D ATETIME data type and its components Y EAR , M ONTH , D AY , H OUR , M INUTE , and S ECOND , it doesn’t dictate how a DBMS makes this data available. Each DBMS offers a suite of functions that extract parts of D ATETIME s. Let’s look at some examples of T-SQL datetime functions. Try It Out: Using Transact-SQL Date and Time Functions Follow these steps to practice with Transact-SQL date and time functions: 1. Enter the following query into SSMSE and execute it. You should see the results shown in Figure 11-8: select current_timestamp 'standard datetime', getdate() 'Transact-SQL datetime', datepart(year, getdate()) 'datepart year', year(getdate()) 'year function', datepart(hour, getdate()) 'hour' How It Works Y ou use a nonstandar d v ersion of a quer y , omitting the FROM clause , to display the curr ent date and time and individual par ts of them. The first two columns in the select list giv e the complete date and time: CHAPTER 11 ■ LEARNING MORE ABOUT QUERIES 289 Figure 11-8. Using date and time functions 777Xch11final.qxd 11/18/06 2:38 PM Page 289 current_timestamp 'standard datetime', getdate() 'Transact-SQL datetime', The first line uses the CURRENT_TIMESTAMP value function of standard SQL; the second uses the GETDATE function of T-SQL. They’re equivalent in effect, both returning the com- plete current date and time. (Note that the output format is specific to each DBMS.) The next two lines each provide the current year. The first uses the T-SQL DATEPART function; the second uses the T-SQL YEAR function. Both take a datetime argument and return the integer year. The DATEPART function’s first argument specifies what part of a datetime to extract. Note that T-SQL doesn’t provide a date specifier for extracting a complete date, and it doesn’t have a separate DATE function: datepart(year, getdate()) 'datepart year', year(getdate()) 'year function', The final line gets the current hour. You must use the T-SQL DATEPART function here, since no HOUR function is analogous to the YEAR function. Note that T-SQL doesn’t pro- vide a time specifier for extracting a complete time, and it doesn’t have a separate TIME function: datepart(hour, getdate()) 'hour' You can format dates and times and alternative functions for extracting and convert- ing them in various ways. You can also add, subtract, increment, and decrement dates and times. How this is done is DBMS-specific, though all DBMSs comply to a reasonable extent with the SQL standard in how they do it. Whatever DBMS you use, you’ll find that dates and times are the most complicated data types to use. But, in all cases, you’ll find that functions (sometimes a richer set of them than in T-SQL) are the basic tools for working with dates and times . ■Tip When providing date and time input, character string values are typically expected; for example, 6/28/2004 would be the a ppropriate way to specify the value for a column holding the current date from the example. Ho wever, DBMSs store datetimes in system-specific encodings. When you use date and time data, read the SQL manual for your database carefully to see how to best handle it. CHAPTER 11 ■ LEARNING MORE ABOUT QUERIES290 777Xch11final.qxd 11/18/06 2:38 PM Page 290 CASE Expressions The C ASE expression allows an alternative value to be displayed depending on the value of a column. For example, a C ASE expression can provide Texas in a result set for rows that have the value TX in the s tate column. Let’s take a look at the syntax of the C ASE expres- sion. It has two different forms: the simple CASE and the searched CASE. Simple CASE Expressions This is the simple CASE syntax, where the ELSE part is optional: CASE <case operand> WHEN <when operand> THEN <when result> ELSE <else result> END The CASE keyword is followed by a column name or an expression that’s to be tested against the operand (a scalar value) following the WHEN keyword. If <case operand> has the same value as <when operand>, <when result> is used; otherwise, <else result> is used as the selection list value. Try It Out: Using a Simple CASE Expression Let’s use a simple CASE expression: 1. Enter the following query into SSMSE and execute it. You should see the results shown in Figure 11-9: select distinct year(orderdate) NumYear, case year(orderdate) when 1998 then 'Last year' else 'Prior year' end LabYear from orders CHAPTER 11 ■ LEARNING MORE ABOUT QUERIES 291 777Xch11final.qxd 11/18/06 2:38 PM Page 291 How It Works You simply label years as either Last year or Prior year depending on whether they were 1998 (the last year for orders in this version of the Northwind database) or earlier (in this database, none are later than 1998). The first two lines get a list of the distinct years (in the Orders table): select distinct year(orderdate) NumYear, Note that you specify an alias NumYear, but since it doesn’t include blanks, you don’t have to enclose it in single quotes (or brackets). The next item in the select list (note that a CASE expression is used just like a column name or function call) is a simple CASE expression, where you provide the result of the YEAR function applied to the order date as the <case operand>, the numeric literal 1998 as the <when operand>, and two strings to label the last year and the prior year, depending on whether the year is 1998 (in other words, whether it matches the <when operand>): CHAPTER 11 ■ LEARNING MORE ABOUT QUERIES292 Figure 11-9. Using a simple CASE expression 777Xch11final.qxd 11/18/06 2:38 PM Page 292 case year(orderdate) when 1998 then 'Last year' else 'Prior year' end LabYear Note that since a CASE expression is merely another member of a select list, you can (and do) give it an alias, LabYear. Try It Out: Using a More Complex Simple CASE Expression Let’s modify this CASE expression to get an idea of how flexible it can be: 1. Enter the following query into SSMSE and execute it. You should see the results shown in Figure 11-10: select distinct year(orderdate) NumYear, case year(orderdate) when 1998 then str(year(orderdate)) else case year(orderdate) when 1997 then 'Prior' else 'Earlier' end end LabYear from orders CHAPTER 11 ■ LEARNING MORE ABOUT QUERIES 293 777Xch11final.qxd 11/18/06 2:38 PM Page 293 Ho w It Works You do a couple interesting things here. First, you change the label for the last year to the year itself rather than a string, showing that the <when operand> can be a data value (here, in fact, the result of a function applied to a column): when 1998 then str(year(orderdate)) Note that you use the STR function to convert the integer returned by YEAR to a string, since you’re planning to use strings for the alternative labels, and a CASE expression must return values of a single data type. You then nest a CASE expression inside the original ELSE (they can also be nested in the WHEN part) to support labeling the other years separately. You label 1997 as Prior and all others as Earlier: CHAPTER 11 ■ LEARNING MORE ABOUT QUERIES294 Figure 11-10. Using a more complex simple CASE expr ession 777Xch11final.qxd 11/18/06 2:38 PM Page 294 else case year(orderdate) when 1997 then 'Prior' else 'Earlier' end Many other variations are possible. The simple CASE expression can be quite com- plex. Exploit it to achieve query results that would otherwise require a lot more work—for both you and the database! Now, let’s examine the searched CASE. Sear ched CASE Expressions The following is the searched CASE syntax, where the ELSE part is optional: CASE WHEN <search condition> THEN <when result> ELSE <else result> END Note the differences between the searched and simple CASEs. The searched CASE has no <case operand>, and the <when operand> is replaced by a <search condition>. These seemingly minor changes add an enormous amount of power. Try It Out: Using a Searched CASE Expression Let’s modify the simple CASE example to demonstrate searched CASE: 1. E nter the follo wing quer y into SSMSE and execute it. Y ou should see the results sho wn in F igur e 11-11: select distinct year(orderdate) NumYear, case when year(orderdate) = CHAPTER 11 ■ LEARNING MORE ABOUT QUERIES 295 777Xch11final.qxd 11/18/06 2:38 PM Page 295 ( select max(year(orderdate)) from orders ) then 'Last year' else 'Prior year' end LabYear from orders CHAPTER 11 ■ LEARNING MORE ABOUT QUERIES296 Figure 11-11. Using a searched CASE expression 777Xch11final.qxd 11/18/06 2:38 PM Page 296 [...]... object, the stored procedure 77 7Xch12final.qxd 11/18/06 2: 37 PM CHAPTER Page 313 12 sss Using Stored Procedures S tored procedures are programs run on the database server that allow you to package SQL in an optimal fashion for reuse Writing stored procedures is a major study in itself Our goal here is to introduce you to the rudiments of stored procedures so you understand how C# programs need to interact... discussion): 77 7Xch11final.qxd 11/18/06 2:38 PM Page 3 07 CHAPTER 11 s LEARNING MORE ABOUT QUERIES from orders o inner join employees e on o.employeeid = e.employeeid inner join customers c on o.customerid = c.customerid The result of the first join, which matches orders to employees, is matched against the Customers table from which the appropriate customer name is retrieved for each matching row from the... a semicolon to terminate the query It’s optional here, but we’ll see when it needs to be used in our next example 319 77 7Xch12final.qxd 320 11/18/06 2: 37 PM Page 320 CHAPTER 12 s USING STORED PROCEDURES Try It Out: Creating a Stored Procedure with an Output Parameter Output parameters are typically used to pass values between stored procedures, but sometimes they need to be accessed from C#, so let’s... orderid, customerid from orders where employeeid = @employeeid; and execute it to create the stored procedure 2 To execute the stored procedure, refresh the Stored Procedures node, right-click dbo.sp_Orders_By_EmployeeId, and click Execute Stored Procedure… Enter 2 in the Value column of the prompt window and click OK You should get the result in Figure 12-6 77 7Xch12final.qxd 11/18/06 2: 37 PM Page... stored procedures Figure 12-3 Creating a stored procedure in SSMSE 315 77 7Xch12final.qxd 316 11/18/06 2: 37 PM Page 316 CHAPTER 12 s USING STORED PROCEDURES 5 To execute the stored procedure, expand the Stored Procedures node, right-click it, and click Refresh, to display the new stored procedure node Then right-click dbo.sp_Select_All_Employees and click Execute Stored Procedure… A prompt window will... customer ID with the customer name To get it, you have to access the Customers table Enter the following query into SSMSE and execute it If you widen the CustomerName column, you should see the results shown in Figure 11-16: select o.orderid OrderID, c.companyname CustomerName, e.lastname Employee from orders o inner join employees e on o.employeeid = e.employeeid inner join customers c on o.customerid... select employeeid, firstname, lastname from employees All this stored procedure does is run a query SSMSE submitted the CREATE PROCEDURE statement and once the stored procedure was created, you ran it from Object Explorer 3 17 777 Xch12final.qxd 318 11/18/06 2: 37 PM Page 318 CHAPTER 12 s USING STORED PROCEDURES That’s it There’s nothing complicated about creating stored procedures The challenge is coding... way to demonstrate how to use the RETURN statement s Input parameters can also be assigned default values Tip There are other ways to do these (and many other) things with stored procedures We’ve done all we need for this chapter, since our main objective is not learning how to write stored procedures but how to use them in C# But let’s see how to modify and delete stored procedures Modifying Stored... join, all rows from both tables are returned 3 07 777 Xch11final.qxd 308 11/18/06 2:38 PM Page 308 CHAPTER 11 s LEARNING MORE ABOUT QUERIES s Left and right outer joins are logically equivalent It’s always possible to convert a left join into a right Tip join by changing the operator and flipping the operands, or a right join into a left with a similar change So, only one of these operators is actually... Results and the row in Return Value 77 7Xch12final.qxd 11/18/06 2: 37 PM Page 3 17 CHAPTER 12 s USING STORED PROCEDURES Figure 12-5 Results of running a stored procedure How It Works The CREATE PROCEDURE statement creates stored procedures The AS keyword separates the signature (the procedure’s name and parameter list, but here you define no parameters) of the stored procedure from its body (the SQL that makes . Tables You’ll replace the customer ID with the customer name. To get it, you have to access the Customers table. Enter the following query into SSMSE and execute it. If you widen the CustomerName column,. QUERIES 305 77 7Xch11final.qxd 11/18/06 2:38 PM Page 305 Ho w It Works First, you modify the select list, replacing CustomerID from the Orders table with CompanyName from the Customers table: select o.orderid. 'Average' from "order details" group by productid order by productid CHAPTER 11 ■ LEARNING MORE ABOUT QUERIES 2 87 777 Xch11final.qxd 11/18/06 2:38 PM Page 2 87 Ho w It Works You

Ngày đăng: 09/08/2014, 14:20

TỪ KHÓA LIÊN QUAN