Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 42 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
42
Dung lượng
1,1 MB
Nội dung
To get the latest-and-greatest view of everything about your SQL Server 2005 Express instance, right-click anywhere on the Object Explorer tree and choose Refresh. The Query window The Query window is where you and SQL Server 2005 Express get to know each other, up close and personal. The workspace contains input windows (described as the Query Editor) for queries and other data interaction. You can also elect to have your output show up at the bottom of the screen in the area (described as the Output window). You can create as many Query Editor windows as you need simply by clicking the New Query icon on the Standard toolbar. When you’re comfortable working in the workspace, you can decide how and where you want your results to appear. You have three options; click one of these icons at the top of the window: Figure 8-1: The SQL Server Management Studio Express Object Explorer. 110 Part III: Adding and Accessing a SQL Server 2005 Express Database 14_599275 ch08.qxp 6/1/06 8:43 PM Page 110 ߜ Text: This formats your output into simple text, and places it in the Output window. ߜ Grid: This option provides more attractive results, placing them into a grid at the bottom of the Output window. ߜ File: This is the “to-go” option for your queries. SQL Server 2005 Express takes the results and nicely places them in a text file. Creating Key Database Objects In this section, I show you how to use a combination of graphical and text tools to create and maintain major database objects. Databases Creating, altering, and deleting databases are significant events in the life of your SQL Server 2005 Express environment. However, none of these tasks requires much heavy lifting, as you’ll now see. Creating a database To create a database, just follow these steps: 1. Launch SQL Server Management Studio Express. 2. Connect to the appropriate SQL Server 2005 Express instance. 3. Expand the connection’s entry in the Object Explorer. 4. Highlight the Databases folder. 5. Right-click this folder, and choose New Database. The New Database dialog box appears (as shown in Figure 8-2) that lets you specify the new database’s name, as well as a collection of proper- ties about the new database. 6. Enter values for these prompts (as shown in Figure 8-3), and click OK. In many cases, you can safely accept the default values from the Options page. 111 Chapter 8: Creating Databases, Tables, and Relationships 14_599275 ch08.qxp 6/1/06 8:43 PM Page 111 Figure 8-3: Setting database properties in SQL Server Management Studio Express. Figure 8-2: Creating a database in SQL Server Management Studio Express. 112 Part III: Adding and Accessing a SQL Server 2005 Express Database 14_599275 ch08.qxp 6/1/06 8:43 PM Page 112 Renaming a database After you have a database in place, renaming it is easy: 1. Launch SQL Server Management Studio Express. 2. Connect to the appropriate SQL Server 2005 Express instance. 3. Expand the connection’s entry in the Object Explorer. 4. Expand the Databases folder. 5. Right-click the database whose name you want to change, and choose the Rename option. 6. Enter a new name of your choice for the database, and press Enter to save your modification. Deleting a database When the time comes to say goodbye to a database, all you need to do is follow these steps: 1. Launch SQL Server Management Studio Express. 2. Connect to the appropriate SQL Server 2005 Express instance. 3. Expand the connection’s entry in the Object Explorer. 4. Expand the Databases folder. 5. Right-click the database that you want to remove, and choose the Delete option. 6. Click OK in the confirmation dialog box. Renaming and dropping databases can be hazardous to your applications’ health. Creating a backup is a good idea before making changes of this magni- tude. The sanity you save may be your own. Check out Chapter 13 for more about archiving your information. Tables Tables are where the rubber meets the road in a database: they dutifully store your vital information. I show you how to create and maintain these important structures. Creating a table After you decide that you want to create a new table, bringing it into exis- tence is easy. You have two major routes that you can follow: SQL/application 113 Chapter 8: Creating Databases, Tables, and Relationships 14_599275 ch08.qxp 6/1/06 8:43 PM Page 113 code versus a graphical tool. In the following list, I describe the advantages and drawbacks of each: ߜ SQL/application code: Choosing this route means that you directly enter, via either SQL or an application programming language, the exact syntax that you want to create your table. This approach has some very compelling advantages: • Power and flexibility: You can specify exactly what you want to happen; a graphical tool may not be able to specify all the nuances that you can in SQL. • Repeatability: You can group your table creation statements into a script or program that you can run again and again. This is much less tedious than having to manually create the table in a graphical tool. • Automation: If you’re shipping a self-installing application to exter- nal locations or need other automation features, creating your tables with SQL or application code is the only way to go. You definitely don’t want to burden your users with the responsibility of using a graphical tool to manually create your tables. The main drawback to this approach is that it does require more under- standing of SQL or the programming language of your choice. ߜ Graphical tool: This is the flip side of SQL. Using a graphical tool might just mean that you can escape all the vagaries of the CREATE TABLE statement. This is a laudable goal, so if your table designs are simple, and you don’t want to learn any SQL, use the graphical tool of your choice to create your table. Many graphical tools on the market can create SQL Server 2005 Express tables. Figure 8-4 is an example of SQL Server Management Studio Express creating a table. Figure 8-4: Creating a table with SQL Server Management Studio Express. 114 Part III: Adding and Accessing a SQL Server 2005 Express Database 14_599275 ch08.qxp 6/1/06 8:43 PM Page 114 If you change your mind, and suddenly become very curious about the CREATE TABLE statement, many of these graphical tools can generate the SQL for you, as well as show you what SQL they used to create your table. Here’s how to build tables, using SQL or another programming language: 1. Open SQL Server Management Studio Express. 2. Open the Databases folder. 3. Expand the folder for your database. 4. Click the New Query button. 5. Type your SQL. Here’s a snippet of SQL that creates a basic table: CREATE TABLE partner ( partner_id INTEGER PRIMARY KEY, partner_name VARCHAR(30), partner_area VARCHAR(10) ); 6. After you’re ready to create the table, click the Execute button. 7. Check the results to make sure things ran correctly. If they did, you receive a message like this: Command(s) completed successfully. 8. If things ran successfully, save the code by clicking the Save button. Make sure that you’re in the Query window and not the results window before clicking the Save button. You now have a table that’s ready to be filled with important data, plus the actual code that built the table. How can you run this code again? You can run the code in at least two ways. First, you can simply open the file in SQL Server Management Studio Express, and click the Execute button to launch the SQL. Alternatively, you can use the SQLCMD tool to run the script from the command line. SQLCMD is a very helpful utility that allows both batch and interactive access to SQL Server 2005 Express. Follow these steps to use SQLCMD: 1. Open a command prompt. Choose Start➪Run and enter cmd. Or choose Programs➪Accessories➪ Command Prompt. When you see the friendly command prompt, it’s time to launch SQLCMD. 115 Chapter 8: Creating Databases, Tables, and Relationships 14_599275 ch08.qxp 6/1/06 8:43 PM Page 115 2. Run SQLCMD, passing the proper parameters. This can get a bit confusing: SQLCMD is rather picky about the exact syntax that it deigns to run. This is not surprising when you realize that it supports over two dozen parameters. Table 8-1 highlights a small group of key parameters. If you get in hot water, you can always ask SQLCMD for help: SQLCMD /? 3. Run your script. Here’s an example of how I ran SQLCMD, along with the parameters I provided: SQLCMD -S dbserver -U Nicole -P Sierra -d WestBay -i build_abc.sql Make sure that your script file is in the right directory; SQLCMD can’t find it otherwise. Alternatively, provide a full path to the file. Table 8-1 Key SQLCMD Parameters Parameter Purpose -S Specify the server that you want to connect to -U Provide your username -P Provide your password -d Which database to use -i The file containing your SQL script Modifying a table If you made a mistake when you created a table, don’t despair! Modifying the table to your liking is no big deal. You can choose from several approaches when amending an existing table. The right approach is largely dependent on what kind of modification you’re making. If you’re only renaming a table, here’s the simplest way to make it happen: 1. Open SQL Server Management Studio Express. 2. Open the Databases folder. 3. Expand the folder for your database. 116 Part III: Adding and Accessing a SQL Server 2005 Express Database 14_599275 ch08.qxp 6/1/06 8:43 PM Page 116 4. Expand the Tables folder. 5. Position the cursor on the table you want to rename, and click once. 6. Rename the table as you like, and press Enter. That’s all renaming takes! Now, if you want to make more complex changes, you’ll probably need to use straight SQL or a more robust graphical tool. This is true for any of these kinds of adjustments: ߜ Adding a column ߜ Changing a column’s data type ߜ Removing a column ߜ Changing default values, constraints, and so on This is just a partial list; several other types of alterations require a visit to SQL land. Luckily, the SQL for these kinds of modifications is quite easy. Here’s how to proceed: 1. Back up your table. Mistakes happen to the best of us. To help recover from the slight possi- bility of catastrophic error, creating a backup is always a good idea before undertaking any kind of major database change. 2. Launch SQL Server Management Studio Express, and click on the New Query button. Using SQL Server Management Studio Express makes the most sense; it’s free, and provides great functionality. You can see your table’s structure, which helps reduce the chance of any inadvertent SQL errors. 3. Type your SQL statement, or make the changes graphically. I describe the SQL approach; however, when given the choice, you can opt for the graphical approach. The ALTER statement is very flexible, and is generally the right choice for making table modifications. Of course, you need to make sure that you have permission to use this statement. After you have permission, here are some examples of ALTER in action. First, here’s the original CREATE TABLE statement: CREATE TABLE partner ( partner_id INTEGER PRIMARY KEY, partner_name VARCHAR(30), partner_area VARCHAR(10) ); 117 Chapter 8: Creating Databases, Tables, and Relationships 14_599275 ch08.qxp 6/1/06 8:43 PM Page 117 • Dropping a column: When you realize a certain column is no longer necessary, you can easily remove it: ALTER TABLE partner DROP COLUMN partner_area; • Adding a new column: After dropping a column , you may want to bring it back. Fortunately, you only need to run the ALTER state- ment to re-create the column: ALTER TABLE partner ADD partner_area VARCHAR(10) • Creating a default value constraint: SQL Server 2005 Express lets you set up restrictions on your tables. These are known as con- straints, and I discuss them a little later in this chapter. For now, here’s a simple default value constraint for the partner_area column: ALTER TABLE partner ADD CONSTRAINT partner_area_unassigned DEFAULT ‘unassigned’ FOR partner_area ; 4. Run your statement. 5. Check for any problems. If things work out okay, you receive a message like this: Command(s) completed successfully. If you receive an error message, try modifying your SQL statement to correct the problem. Removing a table Getting rid of tables you no longer need is very easy. Just follow these simple steps. 1. Back up your data. Unless you’re sure that you’ll never need to set eyes on this data again, consider making a backup. Even if you don’t need the data, you might need to re-create the table’s structure at some point later. 2. Choose the method you want to use. You have numerous tools at your disposal when you create a table. The same holds true when dropping a table. Of all your choices, however, SQL Server Management Studio Express is the safest: Because you can see all your tables, you more than likely won’t delete the wrong table. 118 Part III: Adding and Accessing a SQL Server 2005 Express Database 14_599275 ch08.qxp 6/1/06 8:43 PM Page 118 3. Drop the table. The SQL syntax for deleting a table is very simple: DROP TABLE SoonToBeGone; You don’t need to first delete any of the table’s data or remove any of its indexes or relationships: The DROP statement takes care of all cleanup. Relationships In terms of SQL Server 2005 Express, relationships do not mean how well your data gets along with its friends, co-workers, or neighbors. Instead, rela- tionships describe the interdependencies among the data stored in different tables. Relationships have three main classes: ߜ One-to-one: A one-to-one relationship means that a row in Table A has one (and only one) corresponding row in Table B. For example, you might track client information such as name, address, and so on in a Customers table. At the same time, you might want to follow details about each client’s credit rating in a secondary CreditStatus table. These two tables have a one-to-one relationship. A client can have one and only one credit rating; a credit rating can belong to one and only one client. ߜ One-to-many: A one-to-many relationship exists whenever rows from Table A can have many related rows in Table B, yet Table B’s rows can only be related back to one row in Table A. Continuing with the previous example, suppose that you want to track order information for each client. These details reside in an Orders table. A customer can have many orders, but each order belongs to one and only one customer. ߜ Many-to-many: This kind of relationship exists when a row in Table A can have many related rows in Table B, and vice-versa. This kind of rela- tionship is very common in relational databases, and generally requires that you create an intermediate table to store both sides of the relation- ship. Continuing with the previous customer and order examples, sup- pose that you’re tracking the items that each customer has ordered. You keep your master item list in an Items table. A customer can order many items; an item can be ordered by many different customers. In this case, you need to create a table to store an identifier for each cus- tomer who has ordered an item, and the identifiers for this item. These kinds of tables usually take the names of both sides of the relationship, so CustomerItems is a good choice. Using this intermediary table, you can then construct useful queries from both perspectives. You can ask SQL Server 2005 Express for a list of all customers who purchased an item, as well as all the items purchased by a given customer. 119 Chapter 8: Creating Databases, Tables, and Relationships 14_599275 ch08.qxp 6/1/06 8:43 PM Page 119 [...]... overview of the various types of tools at your disposal for easy communication with SQL Server 2005 Express Finally, I show how you can use SQL to straightforwardly create, modify, and remove information in your SQL Server 2005 Express database What Is Transact -SQL? Like many people new to SQL Server 2005 Express, you probably keep hearing of “Transact -SQL, ” and you wonder what it is Another question you... instruct SQL Server 2005 Express what table these columns come from 143 144 Part III: Adding and Accessing a SQL Server 2005 Express Database 2 Join the data from each table for any rows that have the FlavorID columns in common 3 Apply a filter to make sure the flavor is Watermelon Whale 4 Return the results sorted by the date of sale The join takes place during Step 2 Note that SQL Server 2005 Express. .. Management Studio Express Chapter 9: Talking to a SQL Server Figure 9-2: Microsoft Access working with SQL Server 2005 Express Figure 9-3: Microsoft Query identifying information to return to a spreadsheet 129 130 Part III: Adding and Accessing a SQL Server 2005 Express Database After you make your request, Microsoft Query returns data to your spreadsheet, which is what Figure 9 -4 shows ߜ Application... history of SQL and its powerful progeny, Transact -SQL (refer to the earlier sections of this chapter), you can use the SQL Server 2005 Express database for what it does best: store, manage, and retrieve information 127 128 Part III: Adding and Accessing a SQL Server 2005 Express Database Your first decision is to pick one or more tools to get access to your data The market abounds with choices: ߜ SQL Server. .. Server 2005 Express Storing Information in Your Database After you choose one or more data access technologies, your next task is to start using your database Because a vacant database is quite boring to explore, the first thing I do here is show you how to insert information into your SQL Server 2005 Express tables To keep things straightforward, I use SQL Server Management Studio Express as the tool for. .. built for you, or by you In fact, you may be developing your own database application right now In any case, just like clothing that’s made to measure, these applications are tailored for your organization’s specific data processing needs Figure 9 -4: Microsoft Excel displaying SQL Server 2005 Express data Chapter 9: Talking to a SQL Server Figure 9-5: Microsoft Visual Studio interacting with SQL Server. .. and Accessing a SQL Server 2005 Express Database Enforcing relationships As a database designer or developer, you specify relationships when you create the table You can also add them after the fact, by creating or altering tables But after you create your relationships, how do you enforce them? Thankfully, enforcement in SQL Server 2005 Express doesn’t require guilt or the threat of force Instead,... in database “WestBay”, table “flavors”, column ‘FlavorID’ The statement has been terminated 133 1 34 Part III: Adding and Accessing a SQL Server 2005 Express Database In addition to the foreign key constraint you just saw, SQL Server 2005 Express has other capabilities that help protect your information For example, see what happens if you try to insert a row with a duplicate primary key in the Sales... Studio Express: Available for free download from Microsoft, this tool provides interfaces for managing and maintaining your database, along with a workspace for entering SQL For most database interactions, it’s hard to beat this free tool Figure 9-1 shows a Query window within SQL Server Management Studio Express ߜ Data access tools: The market abounds with choices to help you make the most of your SQL Server. .. Server 2005 Express data These include reporting tools, business intelligence products, and simple application development platforms Figure 9-2 shows one of the more popular platforms, Microsoft Access, caught in the act of importing data from two SQL Server 2005 Express tables ߜ Office productivity tools: Even if you’re not a sophisticated software developer, you can still get value from your SQL Server . with SQL Server 2005 Express. Finally, I show how you can use SQL to straightforwardly create, modify, and remove information in your SQL Server 2005 Express database. What Is Transact -SQL? Like. 8-7: The Foreign Key Rela- tionships dialog box. 1 24 Part III: Adding and Accessing a SQL Server 2005 Express Database 14_ 599275 ch08.qxp 6/1/06 8 :43 PM Page 1 24 Chapter 9 Talking to a SQL Server In. Management Studio Express creating a table. Figure 8 -4: Creating a table with SQL Server Management Studio Express. 1 14 Part III: Adding and Accessing a SQL Server 2005 Express Database 14_ 599275 ch08.qxp