Tài liệu Using SQL phần 1 doc

9 343 1
Tài liệu Using SQL phần 1 doc

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

Thông tin tài liệu

Using SQL SQL (pronounced sequel) is the standard language for accessing relational databases. As you'll see in this chapter, SQL is easy to learn and use. With SQL, you tell the database what data you want to access, and the database software figures out exactly how to get that data. There are many types of SQL statements, but the most commonly used types of SQL statements are these: • Data Manipulation Language (DML) statements • Data Definition Language (DDL) statements DML statements allow you to retrieve, add, modify, and delete rows stored in the database. DDL statements allow you to create database structures such as tables. Before you learn the basics of DML statements, you need to know how you can enter and run SQL statements. You can enter and run SQL statements against a SQL Server database using the Query Analyzer tool, and you'll learn about this next. Note As you'll see later in the "Accessing a Database Using Visual Studio .NET" section, you can also use Visual Studio .NET to create SQL statements. Visual Studio .NET enables you to create SQL statements visually, as well as entering them manually. Using Query Analyzer You use Query Analyzer to enter and run SQL statements. You start Query Analyzer by selecting Start ➣ Microsoft SQL Server ➣ Query Analyzer. In the following sections, you'll learn how to connect to a SQL server instance, enter and run a SQL statement, save a SQL statement, and load one. Connecting to a SQL Server Instance When you start Query Analyzer, the first thing it displays is the Connect to SQL Server dialog box, as shown in Figure 3.1 . In the SQL Server field, you enter the name of the SQL Server instance to which you want to connect. You can click the drop-down list and select an instance of SQL Server, or you can click the ellipsis button (three dots …) to the right of the drop-down list to display a list of SQL Server instances running on your network. Figure 3.1: Connecting to a SQL Server database If you select the Windows authentication radio button, then SQL Server will use the Windows 2000/NT user information to validate your request to connect to SQL Server. If you select the SQL Server authentication radio button, then you will need to enter a login name and password. In Figure 3.1 , I've entered localhost in the SQL Server field; this corresponds to the instance of SQL Server installed on the local computer. I've also selected the SQL Server authentication radio button, and entered sa in the Login Name field and sa in the Password field (this is the password I used when installing SQL Server). These details are then used to connect to SQL Server. If you have an instance of SQL Server running on your local computer or on your network, you may enter the relevant details and click the OK button to connect to SQL Server. Now that you've seen how to connect to the database, let's take a look at how you enter and run a SQL statement. Entering and Running a SQL Statement Once you've connected to SQL Server using Query Analyzer, you can use the Object Browser to view the parts of a database, and you enter and run SQL statements using a Query window. Figure 3.2 shows the Object Browser and an example Query window, along with the results of retrieving the CustomerID and CompanyName columns from the Customers table. Figure 3.2: Viewing database items using the Object Browser and executing a SELECT statement using the Query window As you can see from Figure 3.2 , you enter SQL statements into the top part of the Query window, and the results retrieved from the database are displayed in the bottom part. You specify the database to access with the USE statement, and you retrieve rows from the database using the SELECT statement. Tip You can also specify the database to access by using the drop-down list on the toolbar. If you want to follow along with this example, go ahead and enter the following USE statement into your Query window: USE Northwind This USE statement indicates that you want to use the Northwind database. Next, on a separate line, enter the following SELECT statement: SELECT CustomerID, CompanyName FROM Customers; This SELECT statement indicates that you want to retrieve the CustomerID and CompanyName columns from the Customers table. Note SELECT and FROM are SQL keywords. Although SQL isn't case sensitive, I use uppercase when specifying SQL keywords and mixed case when specifying column and table names. You may terminate a SQL statement using a semicolon (;), although this isn't mandatory. You can run the SQL statement entered in the Query window in five ways: • Selecting Execute from the Query menu • Clicking the Execute Query button (green triangle) on the toolbar • Pressing the F5 key on the keyboard • Pressing Ctrl+E on the keyboard • Pressing Alt+X on the keyboard Once you run the SQL statement, your statement is sent to the database for execution. The database runs your statement and sends results back. These results are then displayed in the bottom of your Query window. Saving and Loading a SQL Statement You can save a SQL statement previously entered into Query Analyzer as a text file. Later, you can load and run the SQL statement saved in that file. You can save a SQL statement by • Selecting Save or Save As from the File menu • Clicking the Save Query/Result button (disk) on the toolbar • Pressing Ctrl+S on the keyboard When you do any of these, the Query Analyzer opens the Save Query dialog box. Let's say you save the file as CustomerSelect.sql. Once you've saved the file, you can open it by • Selecting Open from the File menu • Clicking the Load SQL Script button (open folder) on the toolbar • Pressing Ctrl+Shift+P on the keyboard When you do any of these, the Query Analyzer opens the Open Query File dialog box. Let's say you open CustomerSelect.sql. Once you've opened a query file, you can run it using one of the techniques described earlier. Understanding Data Manipulation Language (DML) Statements As mentioned earlier, DML statements enable you to retrieve, add, modify, and delete rows stored in database tables. There are four types of DML statements: • SELECT Retrieves rows from one or more tables. • INSERT Adds one or more new rows to a table. • UPDATE Modifies one or more rows in a table. • DELETE Removes one or more rows from a table. You'll learn how to use these four statements in the following sections. Retrieving Rows From a Single Table You use the SELECT statement to retrieve rows from tables. The SELECT statement has many forms, and the simplest version allows you to specify a list of columns and the table name. For example, the following SELECT statement retrieves the CustomerID, CompanyName, ContactName, and Address columns from the Customers table: SELECT CustomerID, CompanyName, ContactName, Address FROM Customers; The columns to retrieve are specified after the SELECT keyword, and the table is specified after the FROM keyword. If you want to retrieve all columns from a table, specify the asterisk character (*) immediately after the SELECT keyword. Tip To avoid retrieving more information than you need, rather than use *, list only the columns you actually want. For example, the following SELECT statement retrieves all the columns from the Customers table using *: SELECT * FROM Customers; Figure 3.3 shows the results of this SELECT statement. Figure 3.3: Using a SELECT statement to retrieve rows from the Customers table To retrieve rows from a table containing a space in its name, you place that table name in square brackets. For example, the following SELECT statement retrieves rows from the Order Details table: SELECT * FROM [Order Details]; Note You can also use square brackets when you have a column with a name that contains a space. Restricting Retrieved Rows You use the WHERE clause to restrict the rows retrieved by a SELECT statement. For example, the following SELECT statement uses a WHERE clause to restrict the rows retrieved from the Customers table to those where the Country column is equal to 'UK': SELECT CustomerID, CompanyName, City FROM Customers WHERE Country = 'UK'; Figure 3.4 shows the results of this SELECT statement. Figure 3.4: Using a WHERE clause to restrict rows from the Customers table to those where Country is equal to 'UK' The next SELECT statement uses a WHERE clause to restrict the row retrieved from the Products table to the one where ProductID is equal to 10: SELECT ProductID, ProductName, QuantityPerUnit, UnitPrice FROM Products WHERE ProductID = 10; The equal operator (=) is not the only operator you can use in a WHERE clause. Table 3.1 shows other mathematical operators you can use. Table 3.1: SQL MATHEMATICAL OPERATORS OPERATOR DESCRIPTION = Equal <> or != Not equal < Less than > Greater than <= Less than or equal >= Greater than or equal The following SELECT statement uses the less-than-or-equal operator (<=) to retrieve the rows from the Products table where the ProductID column is less than or equal to 10: SELECT ProductID, ProductName, QuantityPerUnit, UnitPrice FROM Products WHERE ProductID <= 10; The next SELECT statement uses the not-equal operator (<>) to retrieve the rows from the Products table where the ProductID column is not equal to 10: SELECT ProductID, ProductName, QuantityPerUnit, UnitPrice FROM Products WHERE ProductID <> 10; Performing Pattern Matching You use the LIKE operator in a WHERE clause to perform pattern matching. You specify one or more wildcard characters to use in your pattern matching string. Table 3.2 lists the wildcard characters. Table 3.2: WILDCARD CHARACTERS CHARACTERS DESCRIPTION _ Matches any one character. For example, J_y matches Joy and Jay. % Matches any number of characters. For example, %wind matches Northwind and Southwind; %fire% matches starfire, firestarter, and fireman. [ ] Matches any one character in the brackets. For example, [sm]ay Table 3.2: WILDCARD CHARACTERS CHARACTERS DESCRIPTION matches say and may. [^ ] Matches any one character not in the brackets. For example, [^a] matches any character except a. [ - ] Matches a range of characters. For example, [a-c]bc matches abc, bbc, and cbc. # Matches any one number. For example, A# matches A1 through A9. Let's take a look at some examples that use some of the wildcard characters shown in Table 3.2 . The following SELECT statement uses the LIKE operator to retrieve products where the ProductName column is like 'Cha_': SELECT ProductID, ProductName FROM Products WHERE ProductName LIKE 'Cha_'; Figure 3.5 shows the results of this SELECT statement. LIKE 'Cha_' matches products with names that start with Cha and end with any one character. Figure 3.5: Products where ProductName is like 'Cha_' The next SELECT statement uses the LIKE operator to retrieve products where the ProductName column is like 'Cha%': SELECT ProductID, ProductName FROM Products WHERE ProductName LIKE 'Cha%'; Figure 3.6 shows the results of this SELECT statement. LIKE 'Cha%' matches products with names that start with Cha and end with any number of characters. . Using SQL SQL (pronounced sequel) is the standard language for accessing relational databases. As you'll see in this chapter, SQL is easy. to know how you can enter and run SQL statements. You can enter and run SQL statements against a SQL Server database using the Query Analyzer tool, and

Ngày đăng: 14/12/2013, 13:15

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan