• No results found

Creating QBE Queries in Microsoft SQL Server

N/A
N/A
Protected

Academic year: 2021

Share "Creating QBE Queries in Microsoft SQL Server"

Copied!
21
0
0

Loading.... (view fulltext now)

Full text

(1)

1

Creating QBE Queries in Microsoft SQL Server

When you ask SQL Server or any other DBMS (including Access) a question about the data in a database, the question is called a query. A query is simply a question represented in a way that the DBMS can recognize and process. In this section, you will investigate Query-By-Example (QBE), an approach to writing queries that is very visual. With QBE, users ask their questions by entering column names and other criteria using an on-screen grid, and data appears on the screen in tabular form.

In SQL Server, you create queries using the “View” window. Start Visual Studio and open the Web Site that contains the database. To reach the View window for a new query, in “Server Explorer”

click the “expand” * ] arrow for the database to view its objects. Right-click on the “Views” group and from the drop-down menu click on the “Add New View” command.

The “Add Table” dialog window is displayed (see next page). You should select the table (or more than one table if this is to be a query that joins fields from multiple tables) from which the fields will be selected for your query (make certain the “Tables” tab in the window is selected). Click the

<Add> button to insert the table into the top section of the “View Designer” window. When you are finished with the “Add Table” dialog, click the <Close> button to close the window.

(2)

2

The SQL Server “View Designer” window has four panes (see image on the following page):

Field list for each table—the upper portion of the window contains a field list for each table you want to query; note that the table’s primary key displays in a bold font

The design grid—the second pane contains the design grid, the area in which you specify the format of your output, the fields to be included in the query results, a sort order for the query results, and any criteria the records you are looking for must satisfy

SQL equivalent—the third pane displays the SQL language equivalent of the query that you are creating in the design grid (this is not important to use now, so you can ignore whatever appears there; but in the next chapter you will be learning the SQL language for querying a database, so we will use that part of the “View” window then

Output window—the bottom portion is the output window where the results of the query (the records and fields returned) will be displayed when you run your queries

(3)

3

The following figures and examples will show you how to retrieve data using the SQL Server version of QBE.

SIMPLE QUERIES

To include a field in the results of a query, you place it in the design grid.

EXAMPLE 1

List the number, name, balance, and credit limit of all customers in the database.

To include a field in a SQL ServerView query, click the check mark () in front of the fieldname which places it in the design grid, as shown in the image on the next page. The checksin the check boxes in the “Column” column in the design grid indicate that the fields that will appear in the query results.

To omit a field from the query results, remove the check mark from the field’s check box.

(4)

4

You should take note of two other columns in the design grid:

 The “Table” column indicates the name of the table from which the field was taken

 The “Output” column indicates that a particular field will be displayed in the output window;

there are instances in which a field is being used for some other operation in the query but will not actually be displayed; perhaps it is being used as a criteria or for grouping of data results (examples to follow later)

Clicking the <Run>( ) button (actually called the “Execute SQL” button) on the “View Designer”

toolbarruns the query and displays the query results, as shown above.

(5)

5

A SQL Server view is an object that must be saved. You should click the <Save> button on the

“Standard” toolbar.

The “Choose Name” dialog window is displayed. As directed you should enter a name for the view. Although SQL Server allows spaces in object names, there will be few problems later when working with views if you enter single word names with no spaces as per the “Example” name below.

Click the <OK> button when you are ready to save the view.

If you make subsequent changes to the view, you can click the <Save> button again to save the modifications. You will not see the “Choose Name” dialog window when you do this since the view object already has been given a name.

When you are done working on the view, click the close (X) button on the tab of View Designer to close the window.

EXAMPLE2

List all fields and all rows in the Orders table.

To display all fields and all rows in the Orders table, you could add each field to the design grid.

There is a shortcut, however. In SQL Server, you can add all fields from a table to the design grid by clicking the check mark () in front of the asterisk (*) shown as (All Columns) in the table’s field list. As seen in the image on the next page, the asterisk appears in the “Column” column of the design grid, indicating that all fields will be included in the query results.

(6)

6

The query results above are displayed in the output window when the <Run> button is clicked.

SIMPLE CRITERIA

When the records that you want to display in a query’s results must satisfy a condition, you enter the condition in the appropriate column in the design grid. Conditions that data must satisfy are also called criteria. (A single condition is called a criterion.) The following example illustrates the use of a criterion to select data.

EXAMPLE3

Find the name of customer 148.

To enter a criterion for a field, include the field in the design grid, and then enter the criterion in the column labeled “Filter” for that field, as shown in the image on the next page.

(7)

7

It is common to omit the “equal to” (=) comparison operator when entering criteria for Numeric type fields. It was not necessary to type the “=” along with the criterion number 148. However SQL Server automatically adds it when you run the query, move to another line or column, or save the query.

The query results in the image above show an exact match; the query selects a record only when CustomerNum equals 148. Please note that the CustomerNum field is entered into the grid design only for the purpose of specifying the criterion. The check box for it in the “Output” column is unchecked so it is not displayed in the output window.

Q & A

Question: Sometimes a field like the CustomerNum field will be defined as a Text field and not a Numeric field? Why might this be true? Doesn’t it contain numbers?

Answer: Fields such as the CustomerNum field that contain numbers, but are not involved in calculations, are frequently assigned the Text data type.

NOTE

When you enter a criterion for a Text field, such as CustomerNum, SQL Server automatically adds double quotation marks around the value when you run the query or move the insertion point to another box in the design grid. Typing the quotation marks is optional. (Some DBMSs use single quotation marks to enclose Text values.)

If you want something other than an exact match, you must enter the appropriate comparison operator, also called a relational operator, as you will see in the next example. The comparison

(8)

8

operators are = (equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to), and NOT (not equal to).

COMPOUND CRITERIA

You can use the comparison operators by themselves to create conditions. You can also combine criteria to create compound criteria, or compound conditions. In many query languages, you create compound criteria by including the word AND or OR between the separate criteria. In an AND criterion, both criteria must be true for the compound criterion to be true. In an OR criterion, the overall criterion is true if either of the individual criteria is true.

In QBE, to create an AND criterion, place the criteria for multiple fields on the same Criteria row in the design grid; to create an OR criterion, place the criteria for multiple fields on different Criteria rows in the design grid.

EXAMPLE 4

List the description, on hand value, and warehouse number for all parts that have more than 10 units on hand and that are located in warehouse 3.

To indicate that two criteria must both be true to select a record, place the conditions for each field in the same Criteria row, as shown in the image on the next page. In this case, you want the query to select those parts where the value in the OnHand field is greater than 10 (which requires the use of the “greater than” (>) comparison operator) and the value in the Warehouse field is 3.

(9)

9

The query results above are displayed in the output window when the <Run> button is clicked.

EXAMPLE 5

List the description, on hand value, and warehouse number for all parts that have more than 10 units on hand or that are located in warehouse 3.

To indicate that either of two conditions must be true to select a record, place the first criterion in the Criteria row for the first column and place the second criterion in the row labeled “or,” as shown on the next page.

(10)

10

The query results above are displayed in the output window when the <Run> button is clicked.

EXAMPLE 6

List the number, name, and balance for each customer whose balance is between $ 1,000 and $ 5,000.

This example requires you to search for a range of values to find all customers with balances between $ 1,000 and $ 5,000. When you ask this kind of question, you are looking for all balances that are greater than $ 1,000 and all balances that are less than $ 5,000; the answer to this question requires using a compound criterion, or two criteria in the same field.

To place two criteria in the same field, separate the criteria with the AND operator to create an AND condition. The image on the next page shows the AND condition to select all records with a value of more than 1000 and less than 5000 in the Balance field.

(11)

11

The query results above are displayed in the output window when the <Run> button is clicked.

COMPUTED FIELDS

Sometimes you’ll need to include calculated fields that are not in the database in queries. A computed field or calculated field is a field that is the result of a calculation using one or more existing fields. Example 7 illustrates the use of a calculated field.

EXAMPLE 7

List the number, name, and available credit for all customers.

Available credit is computed by subtracting the balance from the credit limit. Because there is no available credit field in the Customer table, you must calculate it from the existing Balance and CreditLimit fields. To include a computed field in a query, you enter a name for the computed field, followed by a colon, and then followed by an expression in one of the columns in the Field row.

To calculate available credit, you can enter the expression CreditLimit-Balance in the desired

“Column” column in the design grid. By default SQL Server gives the calculated field a name of “Expr1” in the “Alias” column. A more descriptive name “AvailableCredit” (again no spaces in the name) can be

(12)

12

assigned which then is displayed as the column heading in the output windowas shown in the image below.

NOTE

When a field name contains spaces or SQL reserved words, you must enclose the field name in square brackets ([ ]). For example, if the field name were Credit Limit instead of CreditLimit, you would enter the expression as [Credit Limit]-Balance. You can also enclose a field name that does not contain spaces in square brackets, but you do not need to do so.

The query results above are displayed in the output window when the <Run> button is clicked.

You are not restricted to subtraction in computations. You can also use addition (+), multiplication (*), or division (/). You can include parentheses in your expressions to indicate which computations SQL Server should perform first.

FUNCTIONS

All products that support QBE, including SQL Server, support the following built-in functions (also called aggregate functions): Count, Sum, Avg (average), Max (largest value), Min (smallest value),

(13)

13

StDev (standard deviation), Var (variance), First, and Last. To use any of these functions in a query, you include them in the “Group By”column for the desired row in the design grid. By default, the Group By columns does not appear automatically in the design grid. To add the column to the design grid, right- click anywhere in the design grid and select “Add Group By” from the drop-down menu.

Example 8 illustrates how to use a function in a query by counting the number of customers represented by sales rep 35.

EXAMPLE 8

How many customers does sales rep 35 represent?

To count the number of rows in the Customer table that have the value 35 in the RepNum column, you select the “Count” function from the drop-down list in the “Group By”column for the * (All Columns)field. In the RepNumrow, “Group By” is entered automatically in the “Group By” column. In the “Filter”column for the RepNumrow, the entry 35 selects only those records for sales rep number 35, as shown in the image on the next page. The check mark in the “Output” column is not necessary as it need not be displayed in response to the question above.

(14)

14

The query results appear in image above. Notice that SQL Server used the default name “Expr1”

for the new column. You could create your own column name by entering it in the “Alias” column in the query design (for example “NumberOfCustomers”).

EXAMPLE 9

What is the average balance of all customers of sales rep 35?

To calculate the average balance, use the Avgfunction, as shown in the image on the next page.

(15)

15

The query results above are displayed in the output window when the <Run> button is clicked.

GROUPING

You can also use functions in combination with grouping, where calculations affect groups of records. For example, you might need to calculate the average balance for all customers of each sales rep.Grouping simply means creating groups of records that share some common characteristic. In grouping by RepNum, for example, the customers of sales rep 20 would form one group, the customers of sales rep 35 would form a second group, and the customers of sales rep 65 would form a third group.

The calculations are then made for each group.

EXAMPLE 10

What is the average balance for all customers of each sales rep?

In this example, include the RepNum and Balance fields in the design grid. To group the customer records for each sales rep, select the Group By operator in the Total row for the RepNum column. To calculate the average balance for each group of customers, select the Avg function in the Total row for the Balance column, as shown in Figure 2-21.

(16)

16

The query results above are displayed in the output window when the <Run> button is clicked.

SORTING

In most queries, the order in which records appear doesn’t matter. In other queries, however, the order in which records appear can be very important. You might want to see customers listed alphabetically by customer name or listed by rep number. Further, you might want to see customer records listed alphabetically by customer name and grouped by sales rep number.

To list the records in query results in a particular way, you need to sort the records. The field on which records are sorted is called the sort key; you can sort records using more than one field when necessary. When you are sorting records by more than one field (such as sorting by rep number and then by customer name), the first sort field (RepNum) is called the major sort key (also called the primary sort key) and the second sort field (CustomerName) is called the minor sort key (also called the secondary sort key).

To sort in SQL Server, specify the sort order (Ascending or Descending) in the Sort Type column of the design grid for the sort key field(s).

EXAMPLE 11

List the customer number, name, balance, and rep number for each customer. Sort the output alphabetically by customer name.

(17)

17

To sort the records alphabetically using the CustomerName field, select the “Ascending” sort order in the Sort Type column for the CustomerName column, as shown in Figure 2-23. (To sort the records in reverse alphabetical order, select the “Descending” sort order.)

The query results above are displayed in the output window when the <Run> button is clicked.

Notice that the customer names appear in alphabetical order.

Sorting on Multiple Keys

You can specify more than one sort key in a query; in this case, the sort key with the value “1” in the Sort Order column of the design grid will be the major (primary) sort key and the sort key with the value “2” in the Sort order column will be the minor (secondary) sort key. Example 12 illustrates the process.

EXAMPLE 12

List the customer number, name, balance, and rep number for each customer. Sort the output by sales rep number. Within the customers of each sales rep, sort the output by customer name.

(18)

18

In the image below, the value “1” is selected in the Sort Order column for the RepNum field in the design grid so RepNum is the major sort key. The value “2” is selected in the Sort Order column for the CustomerName field in the design grid so CustomerName is the minor sort key.

The query results when the <Run> button is clicked as shown in the image above shows the ascending sort order for the RepNum field. The first group of customers served by rep #20 are sorted within that RepNumb group; then a second group of customer served by rep #35 are sorted separately within the second RepNumb group, and so on for all sales reps.

JOINING TABLES

So far, the queries used in the examples have displayed records from a single table. In many cases, you’ll need to create queries to select data from more than one table. To do so, it is necessary to join the tables based on matching fields in corresponding columns. To join tables in SQL Server, first you add the field lists for both tables to the upper pane of the Query window. SQL Server will draw a line, called a join line, between matching fields in the two tables, indicating that the tables are related. (If the corresponding fields have the same field name and at least one of the fields is the primary key of the table that contains it, SQL Server will join the tables automatically.) Then, you can select fields from either or both tables, as you will see in the next example.

(19)

19 EXAMPLE 13

List each customer’s number and name, along with the number, last name, and first name of each customer’s sales rep.

You cannot create this query using a single table— the customer name is in the Customer table and the sales rep name is in the Rep table. The sales rep number can come from either table because it is the matching field. To select the correct data, you need to join the tables by adding both the

Customer and Rep table field lists to the upper pane and then adding the desired fields from the field lists to the design grid, as shown in the image below.

Notice that the “Table”column in the design grid indicates the table with which each field is associated. The query results above are displayed in the output window when the <Run> button is clicked.

EXAMPLE 14

For each customer whose credit limit is $ 10,000, list the customer’s number and name, along with the number, last name, and first name of the corresponding sales rep.

(20)

20

The only difference between this query and the one illustrated in Example 13 is that there is an extra restriction— the credit limit must be $10,000. To include this new condition, add the CreditLimit field to the design grid, enter 10000 as the criterion, and remove the check mark from the

CreditLimitfield’s “Output” check box (because the CreditLimit column should not appear in the query results). The query design appears in the image below.

Only customers with credit limits of $10,000 are included in the query results, as shown in the output window when the <Run> button is clicked.

Joining Multiple Tables

Joining three or more tables is similar to joining two tables. First, you add the field lists for all the tables involved in the join to the upper pane, and then you add the fields to appear in the query results to the design grid in the desired order.

EXAMPLE 15

For each order, list the order number, order date, customer number, and customer name. In addition, for each order line within the order, list the part number, description, number of units ordered, and quoted price.

(21)

21

This query requires data from four tables: Orders (for basic order data), Customer (for the customer number and name), OrderLine (for the part number, number ordered, and quoted price), and Part (for the description). The image below shows the query design.

The query results above are displayed in the output window when the <Run> button is clicked.

Beginning on page 55 of the Pratt and Adamski textbook update, delete and make-table queries are discussed. These operations are not available in the SQL Server “View” queries. However you should read about them in the textbook so that you have a general concept how such queries work and be able to any answer Review Questions concerning them. You will not be required to perform these types of queries.

References

Related documents

The main optimization of antichain-based algorithms [1] for checking language inclusion of automata over finite alphabets is that product states that are subsets of already

effect of government spending on infrastructure, human resources, and routine expenditures and trade openness on economic growth where the types of government spending are

○ If BP elevated, think primary aldosteronism, Cushing’s, renal artery stenosis, ○ If BP normal, think hypomagnesemia, severe hypoK, Bartter’s, NaHCO3,

Furthermore, while symbolic execution systems often avoid reasoning precisely about symbolic memory accesses (e.g., access- ing a symbolic offset in an array), C OMMUTER ’s test

Aptness of Candidates in the Pool to Serve as Role Models When presented with the candidate role model profiles, nine out of ten student participants found two or more in the pool

more than four additional runs were required, they were needed for the 2 7-3 design, which is intuitive as this design has one more factor than the 2 6-2 design

Results suggest that the probability of under-educated employment is higher among low skilled recent migrants and that the over-education risk is higher among high skilled