Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 44 trang
THÔNG TIN TÀI LIỆU
Cấu trúc
Beginning VB 2008 Databases: From Novice to Professional
Contents at a Glance
Contents
About the Authors
About the Technical Reviewer
Acknowledgments
Introduction
Who This Book Is For
What This Book Covers
How This Book Is Organized
How to Download the Sample Code
Contacting the Author
Getting Your Tools
Obtaining Visual Studio 2008
Installing SQL Server Management Studio Express
Installing the Northwind Sample Database
Installing the Northwind Creation Script
Creating the Northwind Sample Database
Installing the AdventureWorks Sample Database
Installing the AdventureWorks Creation Script
Creating the AdventureWorks Sample Database
Summary
Getting to Know Your Tools
Microsoft .NET Framework Versions and the Green Bit and Red Bit Assembly Model
Using Microsoft Visual Studio 2008
Try It Out: Creating a Simple Console Application Project Using Visual Studio 2008
How It Works
Using SQL Server Management Studio Express
Summary
Getting to Know Relational Databases
What Is a Database?
Choosing Between a Spreadsheet and a Database
Why Use a Database?
Benefits of Using a Relational Database Management System
Comparing Desktop and Server RDBMS Systems
Desktop Databases
Server Databases
The Database Life Cycle
Mapping Cardinalities
Understanding Keys
Primary Keys
Foreign Keys
Understanding Data Integrity
Entity Integrity
Referential Integrity
Normalization Concepts
Drawbacks of Normalization
Summary
Writing Database Queries
Comparing QBE and SQL
Beginning with Queries
Try It Out: Running a Simple Query
How It Works
Common Table Expressions
Try It Out: Creating a CTE
How It Works
GROUP BY Clause
Try It Out: Using the GROUP BY Clause
How It Works
PIVOT Operator
Try It Out: Using the PIVOT Operator
How It Works
ROW_NUMBER() Function
Try It Out: Using the ROW_NUMBER() Function
How It Works
PARTITION BY Clause
Try It Out: Using the PARTITION BY Clause
How It Works
Pattern Matching
Try It Out: Using the % Character
How It Works
Try It Out: Using the _ (Underscore) Character
How It Works
Try It Out: Using the [ ] (Square Bracket) Characters
How It Works
Try It Out: Using the [^] (Square Bracket and Caret) Characters
How It Works
Aggregate Functions
Try It Out: Using the MIN, MAX, SUM, and AVG Functions
How It Works
Try It Out: Using the COUNT Function
How It Works
DATETIME Functions
Try It Out: Using T-SQL Date and Time Functions
How It Works
Joins
Inner Joins
Try It Out: Writing an Inner Join
How It Works
Try It Out: Writing an Inner Join Using Correlation Names
How It Works
Try It Out: Writing an Inner Join of Three Tables
How It Works
Outer Joins
Try It Out: Adding an Employee with No Orders
How It Works
Try It Out: Using LEFT OUTER JOIN
How It Works
Other Joins
Summary
Manipulating Database Data
Retrieving Data
Try It Out: Running a Simple Query
How It Works
Using the WHERE Clause
Try It Out: Refining Your Query
How It Works
Using Comparison Operators in a WHERE Clause
Combining Predicates
Sorting Data
Try It Out: Writing an Enhanced Query
How It Works
Using SELECT INTO Statements
Try It Out: Creating a New Table
How It Works
Try It Out: Using SELECT INTO to Copy Table Structure
How It Works
Inserting Data
Try It Out: Inserting a New Row
How It Works
Updating Data
Try It Out: Updating a Row
How It Works
Deleting Data
Summary
Using Stored Procedures
Creating Stored Procedures
Try It Out: Working with a Stored Procedure in SQL Server
How It Works
Try It Out: Creating a Stored Procedure with an Input Parameter
How It Works
Try It Out: Creating a Stored Procedure with an Output Parameter
How It Works
Modifying Stored Procedures
Try It Out: Modifying the Stored Procedure
How It Works
Displaying Definitions of Stored Procedures
Try It Out: Viewing the Definition of Your Stored Procedure
How It Works
Renaming Stored Procedures
Try It Out: Renaming a Stored Procedure
How It Works
Working with Stored Procedures in VB .NET
Try It Out: Executing a Stored Procedure with No Input Parameters
How It Works
Try It Out: Executing a Stored Procedure with Parameters
How It Works
Deleting Stored Procedures
Try It Out: Deleting a Stored Procedure
How It Works
Summary
Using XML
Defining XML
Why XML?
Benefits of Storing Data As XML
Understanding XML Documents
Understanding the XML Declaration
Converting Relational Data to XML
Using FOR XML RAW
Try It Out: Using FOR XML RAW (Attribute Centric)
How It Works
Try It Out: Using FOR XML RAW (Element Centric)
How It Works
Try It Out: Renaming the row Element
How It Works
Observations About FOR XML RAW Formatting
Using FOR XML AUTO
Try It Out: Using FOR XML AUTO
How It Works
Observations About FOR XML AUTO Formatting
Using the xml Data Type
Try It Out: Creating a Table to Store XML
How It Works
Try It Out: Storing and Retrieving XML Documents
How It Works
Summary
Understanding Transactions
What Is a Transaction?
When to Use Transactions
Understanding ACID Properties
Transaction Design
Transaction State
Specifying Transaction Boundaries
T-SQL Statements Allowed in a Transaction
Local Transactions in SQL Server 2005
Distributed Transactions in SQL Server 2005
Guidelines to Code Efficient Transactions
How to Code Transactions
Coding Transactions in T-SQL
Try It Out: Coding a Transaction in T-SQL
How It Works
Try It Out: What Happens When the First Operation Fails
How It Works
Try It Out: What Happens When the Second Operation Fails
How It Works
Try It Out: What Happens When Both Operations Fail
How It Works
Coding Transactions in ADO.NET
Try It Out: Working with ADO.NET Transactions
How It Works
Summary
Getting to Know ADO.NET
Understanding ADO.NET
The Motivation Behind ADO.NET
Moving from ADO to ADO.NET
ADO.NET Isn’t a New Version of ADO
ADO.NET and the .NET Base Class Library
Understanding ADO.NET Architecture
Working with the SQL Server Data Provider
Try It Out: Creating a Simple Console Application Using the SQL Server Data Provider
How It Works
Working with the OLE DB Data Provider
Try It Out: Creating a Simple Console Application Using the OLE DB Data Provider
How It Works
Working with the ODBC Data Provider
Creating an ODBC Data Source
Try It Out: Creating a Simple Console Application Using the ODBC Data Provider
How It Works
Data Providers As APIs
Summary
Making Connections
Introducing the Data Provider Connection Classes
Connecting to SQL Server Express with SqlConnection
Try It Out: Using SqlConnection
How It Works
Debugging Connections to SQL Server
Security and Passwords in SqlConnection
How to Use SQL Server Security
Connection String Parameters for SqlConnection
Connection Pooling
Improving Your Use of Connection Objects
Using the Connection String in the Connection Constructor
Displaying Connection Information
Try It Out: Displaying Connection Information
How It Works
Connecting to SQL Server Express with OleDbConnection
Try It Out: Connecting to SQL Server Express with the OLE DB Data Provider
How It Works
Summary
Executing Commands
Creating a Command
Try It Out: Creating a Command with a Constructor
How It Works
Associating a Command with a Connection
Try It Out: Setting the Connection Property
How It Works
Assigning Text to a Command
Try It Out: Setting the CommandText Property
How It Works
Executing Commands
Try It Out: Using the ExecuteScalar Method
How It Works
Executing Commands with Multiple Results
Try It Out: Using the ExecuteReader Method
How It Works
Executing Statements
Try It Out: Using the ExecuteNonQuery Method
How It Works
Command Parameters
Try It Out: Using Command Parameters
How It Works
Summary
Using Data Readers
Understanding Data Readers in General
Try It Out: Looping Through a Result Set
How It Works
Using Ordinal Indexers
Try It Out: Using Ordinal Indexers
How It Works
Using Column Name Indexers
Using Typed Accessor Methods
Try It Out: Using Typed Accessor Methods
How It Works
Getting Data About Data
Try It Out: Getting Information About a Result Set with a Data Reader
How It Works
Getting Data About Tables
Try It Out: Getting Schema Information
How It Works
Using Multiple Result Sets with a Data Reader
Try It Out: Handling Multiple Result Sets
How It Works
Summary
Using Datasets and Data Adapters
Understanding the Object Model
Datasets vs. Data Readers
A Brief Introduction to Datasets
A Brief Introduction to Data Adapters
A Brief Introduction to Data Tables, Data Columns, and Data Rows
Working with Datasets and Data Adapters
Try It Out: Populating a Dataset with a Data Adapter
How It Works
Filtering and Sorting in a Dataset
Try It Out: Dynamically Filtering and Sorting Data in a Dataset
How It Works
Comparing FilterSort to PopDataSet
Using Data Views
Try It Out: Refining Data with a Data View
How It Works
Modifying Data in a Dataset
Try It Out: Modifying a Data Table in a Dataset
How It Works
Propagating Changes to a Data Source
UpdateCommand Property
Try It Out: Propagating Dataset Changes to a Data Source
How It Works
InsertCommand Property
Try It Out: Propagating New Dataset Rows to a Data Source
How It Works
DeleteCommand Property
Try It Out: Propagating New Dataset Rows to a Data Source
How It Works
Command Builders
Try It Out: Using SqlCommandBuilder
How It Works
Concurrency
Using Datasets and XML
Try It Out: Extracting a Dataset to an XML File
How It Works
Using Data Tables Without Datasets
Try It Out: Populating a Data Table with a Data Adapter
How It Works
Understanding Typed and Untyped Datasets
Summary
Building Windows Forms Applications
Understanding Windows Forms
User Interface Design Principles
Best Practices for User Interface Design
Simplicity
Position of Controls
Consistency
Aesthetics
Color
Fonts
Images and Icons
Working with Windows Forms
Understanding the Design and Code Views
Sorting Properties in the Properties Window
Categorized View
Alphabetical View
Setting Properties of Solutions, Projects, and Windows Forms
Working with Controls
Try It Out: Working with the TextBox and Button Controls
How It Works
Setting Dock and Anchor Properties
Dock Property
Anchor Property
Try It Out: Working with the Dock and Anchor Properties
How It Works
Adding a New Form to the Project
Try It Out: Adding a New Form to the Windows Project
Try It Out: Setting the Startup Form
Implementing an MDI Form
Try It Out: Creating an MDI Parent Form with a Menu Bar
Try It Out: Creating an MDI Child Form and Running an MDI Application
How It Works
Summary
Building ASP.NET Applications
Understanding Web Functionality
The Web Server
The Web Browser and HTTP
Introduction to ASP.NET and Web Pages
Understanding the Visual Studio 2008 Web Site Types
File System Web Site
FTP Web Site
HTTP Web Site
Layout of an ASP.NET Web Site
Web Pages
Application Folders
The web.config File
Try It Out: Working with a Web Form
Try It Out: Working with Split View
Using Master Pages
Try It Out: Working with a Master Page
Summary
Handling Exceptions
Handling ADO.NET Exceptions
Try It Out: Handling an ADO.NET Exception (Part 1)
How It Works
Try It Out: Handling an ADO.NET Exception (Part 2)
How It Works
Handling Database Exceptions
Try It Out: Handling a Database Exception (Part 1): RAISERROR
How It Works
Try It Out: Handling a Database Exception (Part 2): Stored Procedure Error
How It Works
Try It Out: Handling a Database Exception (Part 3): Errors Collection
How It Works
Summary
Working with Events
Understanding Events
Properties of Events
Design of Events
Common Events Raised by Controls
Event Generator and Consumer
Try It Out: Creating an Event Handler
How It Works
Try It Out: Working with Mouse Movement Events
How It Works
Try It Out: Working with the Keyboard’s KeyDown and KeyUp Events
How It Works
Try It Out: Working with the Keyboard’s KeyPress Event
How It Works
Summary
Working with Text and Binary Data
Understanding SQL Server Text and Binary Data Types
Storing Images in a Database
Try It Out: Loading Image Binary Data from Files
How It Works
Rerunning the Program
Retrieving Images from a Database
Try It Out: Displaying Stored Images
How It Works
Working with Text Data
Try It Out: Loading Text Data from a File
How It Works
Retrieving Data from Text Columns
Try It Out: Retrieving Text Data
How It Works
Summary
Using LINQ
Introduction to LINQ
Architecture of LINQ
LINQ Project Structure
Using LINQ to Objects
Try It Out: Coding a Simple LINQ to Objects Query
How It Works
Using LINQ to SQL
Try It Out: Coding a Simple LINQ to SQL Query
How It Works
Try It Out: Using the where Clause
How It Works
Using LINQ to XML
Try It Out: Coding a Simple LINQ to XML Query
How It Works
Summary
Using ADO.NET 3.5
Understanding ADO.NET 3.5 Entity Framework
Understanding the Entity Data Model
Working with the Entity Data Model
Try It Out: Creating an Entity Data Model
How It Works
Try It Out: Schema Abstraction Using an Entity Data Model
Summary
Index
Nội dung
Figure 4-16. Using correlation names How It Works You simplify the table references by providing a correlation name for each table. (This is somewhat similar to providing column aliases, but correlation names are intended to be used as alternative names for tables. Column aliases are used more for labeling than for ref- erencing columns.) You can now refer to Orders as o and to Employees as e. Correlation names can be as long as table names and can be in mixed case, but obviously the shorter they are, the easier they are to code. Y ou use the correlation names in both the SELECT list: select o.orderid, o.customerid, e.lastname and the ON clause: on o.employeeid = e.employeeid CHAPTER 4 ■ WRITING DATABASE QUERIES 59 9470ch04final.qxd 2/21/08 3:03 PM Page 59 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Try It Out: Writing an Inner Join of Three Tables Open a New Query window in SSMSE (remember to make Northwind your query context). E nter the following query and click Execute. You should see the results shown in Figure 4-17. 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 = c.customerid Figure 4-17. Coding an INNER JOIN of three tables How It Works F irst, you modify the SELECT list, r eplacing CustomerID from the Orders table with Company- N ame fr om the Customers table: select o.orderid OrderID, c.companyname CustomerName, e.lastname Employee CHAPTER 4 ■ WRITING DATABASE QUERIES60 9470ch04final.qxd 2/21/08 3:03 PM Page 60 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Second, you add a second inner join, as always with two operands: the table produced by t he first join and the base table C ustomers . You reformat the first J OIN o perator, splitting it across three lines simply to make it easier to distinguish the tables and joins. You can also use parentheses to enclose joins, and you can make them clearer when you use multiple joins. (Furthermore, since joins produce tables, their results can also be associated with correlation names for reference in later joins and even in the SELECT list, but such complexity is beyond the scope of this discussion.) 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 matched orders to employees, is matched against the Customers table from which the appropriate customer name is retrieved for each matching row from the first join. Since referential integrity exists between Orders and both Employees and Customers, all Orders rows have matching rows in the other two tables. How the database actually satisfies such a query depends on a number of things, but joins are such an integral part of relational database operations that query optimizers are themselves optimized to find efficient access paths among multiple tables to perform multi- ple joins. However, the fewer joins needed, the more efficient the query, so plan your queries carefully. Usually you have several ways to code a query to get the same data, but almost always only one of them is the most efficient. Now you know how to retrieve data from two or more tables—when the rows match. What about rows that don’t match? That’s where outer joins come in. Outer Joins Outer joins return all rows from (at least) one of the joined tables even if rows in one table don’t match rows in the other. Three types of outer joins exist: left outer join, right outer join, and full outer join. The terms left and right refer to the operands on the left and right of the JOIN operator. (Refer to the basic syntax for the inner join, and you’ll see why we called the oper ands left-table and right-table.) I n a left outer join, all rows from the left table will be retrieved whether they have matching rows in the right table. Conversely, in a right outer join, all rows from the right table will be retrieved whether they have matching rows in the left table . I n a full outer join, all r o ws from both tables are returned. ■Tip Left and right outer joins are logically equivalent. It’s always possible to convert a left join into a right join by changing the opera tor and flipping the operands or a right join into a left with a similar change. So, only one of these operators is actually needed. Which one you choose is basically a matter of personal preference, but a useful rule of thumb is to use either left or right, but not both in the same query. The query optimizer won’t care, but humans find it much easier to follow a complex query if the joins al ways go in the same direction. CHAPTER 4 ■ WRITING DATABASE QUERIES 61 9470ch04final.qxd 2/21/08 3:03 PM Page 61 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com When is this useful? Quite frequently. In fact, whenever a parent-child relationship exists b etween tables, despite the fact that referential integrity is maintained, some parent rows may not have related rows in the child table, since child rows may be allowed to have null foreign key values and therefore not match any row in the parent table. This situation doesn’t exist in the original Orders and Employees data, so you’ll have to add some data before you can see the effect of outer joins. You need to add an employee so you have a row in the Employees table that doesn’t have related rows in Orders. To keep things simple, you’ll provide data only for the columns that aren’t nullable. Try It Out: Adding an Employee with No Orders To add an employee with no orders, open a New Query window in SSMSE (remember to make Northwind your query context). Enter the following query and click Execute. You should see the results shown in Figure 4-18. insert into employees ( firstname, lastname ) values ('Amy', 'Abrams') Figure 4-18. Adding an employee with no orders CHAPTER 4 ■ WRITING DATABASE QUERIES62 9470ch04final.qxd 2/21/08 3:03 PM Page 62 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com How It Works You submit a single INSERT statement, providing the two required columns. The first column, E mployeeID, is an I DENTITY c olumn, so you can’t provide a value for it, and the rest are nul- lable, so you don’t need to provide values for them. insert into employees ( firstname, lastname ) values ('Amy', 'Abrams') You now have a new employee, Amy Abrams, who has never taken an order. Now, let’s say you want a list of all orders taken by all employees—but this list must include all employees, even those who haven’t taken any orders. Try It Out: Using LEFT OUTER JOIN To list all employees, even those who haven’t taken any orders, open a New Query window in SSMSE (remember to make Northwind your query context). Enter the following query and click Execute. You should see the results shown in Figure 4-19. select e.firstname, e.lastname, o.orderid from employees e left outer join orders o on e.employeeid = o.employeeid order by 2, 1 CHAPTER 4 ■ WRITING DATABASE QUERIES 63 9470ch04final.qxd 2/21/08 3:03 PM Page 63 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 4-19. Using LEFT OUTER JOINs How It Works Had you used an inner join you would have missed the row for the new employee. (Try it for yourself.) The only new SQL in the FROM clause is the JOIN operator itself: left outer join You also add an ORDER BY clause to sort the result set by first name within last name, to see that the kind of join has no effect on the rest of the query, and to see an alternative way to specify columns, by position number within the SELECT list rather than by name. This technique is convenient (and may be the only way to do it for columns that are produced by expressions, for example, by the SUM function): order by 2, 1 N ote that the Or derID column for the new employ ee is null, since no value exists for it. The same holds true for any columns from the table that don’t have matching rows (in this case, the r ight table). Y ou can obtain the same r esult by placing the E mploy ees table on the right and the Orders table on the left of the JOIN operator and changing the operator to RIGHT OUTER JOIN . ( T ry it!) Remember to flip the correlation names, too. The keywor d OUTER is optional and is typically omitted. Left and r ight joins ar e always outer joins. CHAPTER 4 ■ WRITING DATABASE QUERIES64 9470ch04final.qxd 2/21/08 3:03 PM Page 64 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Other Joins The SQL standard also provides for FULL OUTER JOIN, UNION JOIN, and CROSS JOIN (and even NATURAL JOIN, basically an inner join using equality predicates), but these are much less used a nd beyond the scope of this book. We won’t provide examples, but this section contains a brief summary of them. A FULL OUTER JOIN is like a combination of both the LEFT and RIGHT OUTER joins. All rows from both tables will be retrieved, even if they have no related rows in the other table. A UNION JOIN is unlike outer joins in that it doesn’t match rows. Instead, it creates a table that has all the rows from both tables. For two tables, it’s equivalent to the following query: select * from table1 union all select * from table2 The tables must have the same number of columns, and the data types of corresponding columns must be compatible (able to hold the same types of data). A CROSS JOIN combines all rows from both tables. It doesn’t provide for a join specifica- tion, since this would be irrelevant. It produces a table with all columns from both tables and as many rows as the product of the number of rows in each table. The result is also known as a Cartesian product, since that’s the mathematical term for associating each element (row) of one set (table) with all elements of another set. For example, if there are five rows and five columns in table A and ten rows and three columns in table B, the cross join of A and B would produce a table with fifty rows and eight columns. This join operation is not only virtually inapplicable to any real-world query, but it’s also a potentially very expensive process for even small real-world databases. (Imagine using it for production tables with thousands or even millions of rows.) Summary In this chapter, we covered how to construct more sophisticated queries using SQL features such as aggregates, DATETIME functions, GROUP BY clauses, joins, and pattern matching. We also covered the features that are new in SQL Server 2005, such as common table expressions, the PIVOT operator, the ROW_NUMBER() function, and the PARTITION BY clause. In the next chapter, you will learn about manipulating the database. CHAPTER 4 ■ WRITING DATABASE QUERIES 65 9470ch04final.qxd 2/21/08 3:03 PM Page 65 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 9470ch04final.qxd 2/21/08 3:03 PM Page 66 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Manipulating Database Data Now that you know something about writing database queries, it’s time to turn your atten- tion to the different aspects of data modification, such as retrieving, inserting, updating, and deleting data. In this chapter, we’ll cover the following: • Retrieving data • Using SELECT INTO statements • Inserting data • Updating data • Deleting data Retrieving Data A SQL query retrieves data from a database. Data is stored as rows in tables. Rows are com- posed of columns. In its simplest form, a query consists of two parts: • A SELECT list, where the columns to be retrieved are specified • A FROM clause, where the table or tables to be accessed are specified ■Tip We’ve written SELECT and FROM in capital letters simply to indicate they’re SQL keywords. SQL isn’t case sensitive, and keywords are typically written in lowercase in code. In T-SQL, queries are called SELECT statements, but the ISO/ANSI standard clearly distinguishes “queries” from “statements.” The distinction is conceptually important. A quer y is an opera tion on a table tha t produces a table as a result; sta tements may (or may not) operate on tables and don’t produce tables as results. Furthermore, subqueries can be used in both queries and statements. So, we’ll typically call queries “queries” instead of SELECT statements. Call queries whatever you prefer, but keep in mind that queries are a special feature of SQL. 67 CHAPTER 5 9470ch05final.qxd 2/21/08 3:06 PM Page 67 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Using two keywords, SELECT and FROM, here’s the simplest possible query that will get all the data from the specified table: Select * from <table name> The asterisk (*) means you want to select all the columns in the table. You will be using a SQLEXPRESS instance of SQL Server 2005 in this chapter. Open SQL Server Management Studio Express and in the Connect to Server dialog box select <ServerName>\SQLEXPRESS as the server name and then click Connect. SQL Server Man- agement Studio Express (SSMSE) will open. Expand the Databases node and select the Northwind database. Your screen should resemble that shown in Figure 5-1. Figure 5-1. Selecting a database to query Try It Out: Running a Simple Query To submit a query to retrieve all employee data, open a New Query window in SSMSE (remember to make Northwind your query context). Enter the following query and click E xecute . You should see the results shown in Figure 5-2. Select * from employees CHAPTER 5 ■ MANIPULATING DATABASE DATA68 9470ch05final.qxd 2/21/08 3:06 PM Page 68 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... see when it needs to be used in the next example Try It Out: Creating a Stored Procedure with an Output Parameter Output parameters are usually used to pass values between stored procedures, but sometimes they need to be accessed from VB NET, so here you’ll see how to write a stored procedure with an output parameter so you can use it in a VB NET program later You’ll also learn how to return a value... procedures and understand how Visual Basic NET (VB NET) programs can interact with them In this chapter, we’ll cover the following: • Creating stored procedures • Modifying stored procedures • Displaying definitions of stored procedures • Renaming stored procedures • Working with stored procedures in VB NET • Deleting stored procedures Creating Stored Procedures Stored procedures can have parameters that... relationship exists from Orders (FK) to Shippers (PK), and SSMSE enforces it, preventing deletion of Shippers’ rows that are referred to by Orders rows If the database were to allow you to drop records from the PK table, the records in the FK table would be left as orphan records, leaving the database in an inconsistent state (Chapter 3 discusses keys.) Sometimes you do need to remove every row from a table... orderid, customerid from orders where employeeid = @employeeid; 9470ch06final.qxd 2/21/08 3: 02 PM Page 93 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 6 s USING STORED PROCEDURES 2 To execute the stored procedure, enter the following command along with the value for the parameter, select it, and then click Execute You should see the results shown in Figure 6 -3 execute... orderid,employeeid,customerid,orderdate,shipcountry into #myorder from orders Figure 5-6 Creating a new table 9470ch05final.qxd 2/21/08 3: 06 PM Page 77 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 5 s MANIPULATING DATABASE DATA How It Works In the following statement: select orderid,employeeid,customerid,orderdate,shipcountry into #myorder from orders you define... not necessary (or possible) to specify columns Its basic syntax is as follows (remember, the WHERE clause is optional, but without it all rows will be deleted): DELETE FROM WHERE If you need to remove some records from the Shippers table, you need to determine the primary key of the row you want to remove and use that in the DELETE statement: delete from shippers where shipperid... specific to T-SQL; for example, standard SQL doesn’t have the != operator and calls the not equals operator In fact, standard SQL calls the expressions in a WHERE clause predicates; we’ll use that term because predicates are either true or false, but other expressions don’t have to be If you work with another version of SQL, please refer to its documentation for specifics In addition to these operators,... [^abcd] Sometimes it’s useful to select rows where a value is unknown When no value has been assigned to a column, the column is NULL (This isn’t the same as a column that contains the value 0 or a blank.) To select a row with a column that’s NULL, use the IS [NOT] NULL operator (see Table 5-4) Table 5-4 The IS [NOT] NULL Operator Operator Description Example IS NULL Allows you to select rows where a column... Figure 6-1 Creating a stored procedure using SSMSE 3 To execute the stored procedure, enter the following query and click Execute You should see the results shown in Figure 6-2 execute sp_Select_All_Employees 9470ch06final.qxd 2/21/08 3: 02 PM Page 91 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 6 s USING STORED PROCEDURES Figure 6-2 Executing the stored procedure How... user-created stored procedure prefixed with sp_ may exist in the current database, the master database (which is where the sp_ prefixed stored procedures that come with SQL Server 2005 are stored) is always checked first, even if the stored procedure is qualified with the database name It is also important to note that if any user-defined stored procedure has the same name as a system stored procedure, . don’t have to be. If you work with another version of SQL, please refer to its documentation for specifics. In addition to these operators, the LIKE operator (see Table 5-2) allows you to match. orderid,employeeid,customerid,orderdate,shipcountry into #myorder from orders you define the SELECT list, the INTO clause with a table name prefixed by #, and then the FROM clause. This means that you want to. the Customers table from which the appropriate customer name is retrieved for each matching row from the first join. Since referential integrity exists between Orders and both Employees and Customers,