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

Beginning C# 2008 Databases From Novice to Professional phần 4 ppsx

52 395 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 777,04 KB

Nội dung

the FOR XML RAW mode, as shown in the following example. To achieve this, you need to add an alias after the FOR XML RAW clause, which you’ll do now. 1. Replace the existing query in the query window with the following query, and click Execute. SELECT ProductModelID, Name FROM Production.ProductModel WHERE ProductModelID between 98 and 101 FOR XML RAW ('ProductModelDetail'),ELEMENTS 2. You will see a link in the results pane of the query window. Click the link, and you should see the results shown in Figure 7-3. Figure 7-3. Renaming the row element How It Works FOR XML RAW ('alias') mode produces output where the row element is renamed to the alias specified in the query. Because the ELEMENTS directive is added in the query, the result is element centric, and this is why the row element is renamed with the alias specified. If you don’t add the ELEMENTS keyword in the query, the output will be attribute centric, and the row element will be renamed to the alias specified in the query. CHAPTER 7 ■ USING XML 127 9004ch07final.qxd 12/13/07 4:14 PM Page 127 Observations About FOR XML RAW Formatting FOR XML RAW does not provide a root node, and this is why the XML structure is not a well- formed XML document. FOR XML RAW supports attribute- and element-centric formatting, which means that all the columns must be formatted in the same way. Hence it is not possible to have the XML structure returned with both the XML attributes and XML elements. FOR XML RAW generates a hierarchy in which all the elements in the XML structure are at the same level. Using FOR XML AUTO FOR XML AUTO mode returns query results as nested XML elements. This does not provide much control over the shape of the XML generated fr om a query result. FOR XML AUTO mode queries are useful if you want to generate simple hierarchies. Each table in the FROM clause, from which at least one column is listed in the SELECT clause, is represented as an XML element. The columns listed in the SELECT clause are mapped to attributes or subelements. Try It Out: Using FOR XML AUTO To see how to use FOR XML AUTO to format query results as nested XML elements, follow these steps: 1. Replace the existing query in the query window with the following query and click Execute: SELECT Cust.CustomerID, OrderHeader.CustomerID, OrderHeader.SalesOrderID, OrderHeader.Status, Cust.CustomerType FROM Sales.Customer Cust, Sales.SalesOrderHeader OrderHeader WHERE Cust.CustomerID = OrderHeader.CustomerID ORDER BY Cust.CustomerID FOR XML AUTO 2. You will see a link in the results pane of the query window. Click the link, and you should see the results shown in Figure 7-4. CHAPTER 7 ■ USING XML128 9004ch07final.qxd 12/13/07 4:14 PM Page 128 Figure 7-4. Using FOR XML AUTO How It Works The CustomerID references the Cust table. Therefore, a Cust element is created and CustomerID is added as its attribute. Next, three columns, OrderHeader.CustomerID, OrderHeader.SaleOrderID, and OrderHeader.Status, reference the OrderHeader table. Therefore, an OrderHeader element is added as a subelement of the Cust element, and the three columns are added as attrib- utes of OrderHeader. Next, the Cust.CustomerType column again references the Cust table that was already identified by the Cust.CustomerID column. Therefore, no new element is cre- ated. I nstead, the CustomerType attr ibute is added to the Cust element that was pr evi- ously created. The query specifies aliases for the table names. These aliases appear as correspon- ding element names. ORDER BY is required to group all children under one parent. Observations About FOR XML AUTO Formatting FOR XML AUTO does not pr ovide a root node, and this is why the XML structure is not a w ell-for med XML document. CHAPTER 7 ■ USING XML 129 9004ch07final.qxd 12/13/07 4:14 PM Page 129 FOR XML AUTO supports attribute- and element-centric formatting, which means that all the columns must be formatted in the same way. Hence it is not possible to have the XML structure returned with both the XML attributes and XML elements. FOR XML AUTO does not provide a renaming mechanism the way FOR XML RAW does. However, FOR XML AUTO uses table and column names and aliases if present. Using the xml Data Type SQL Server 2005 has a new data type, xml, that is designed not only for holding XML doc- uments (which are essentially character strings and can be stored in any character col- umn big enough to hold them), but also for processing XML documents. When we discussed parsing an XML document into a DOM tree, we didn’t mention that once it’s parsed, the XML document can be updated. You can change element contents and attrib- ute values, and you can add and remove element occurrences to and from the hierarchy. We won’t update XML documents here, but the xml data type provides methods to do it. It is a very different kind of SQL Server data type, and describing how to exploit it would take a book of its own—maybe more than one. Our focus here will be on what every database programmer needs to know: how to use the xml type to store and retrieve XML documents. ■Note There are so many ways to process XML documents (even in ADO.NET and with SQLXML, a sup- port package for SQL Server 2000) that only time will tell if incorporating such features into a SQL Server data type was worth the effort. Because XML is such an important technology, being able to process XML documents purely in T-SQL does offer many possibilities, but right now it’s unclear how much more about the xml data type you’ll ever need to know. At any rate, this chapter will give you what you need to know to start experimenting with it. Try It Out: Creating a Table to Store XML T o cr eate a table to hold XML documents , replace the existing query in the query window with the follo wing quer y and click Execute: create table xmltest ( xid int not null primary key, xdoc xml not null ) CHAPTER 7 ■ USING XML130 9004ch07final.qxd 12/13/07 4:15 PM Page 130 How It Works This works in the same way as a CREATE TABLE statement is expected to work. Though we’ve said the xml data type is different from other SQL Server data types, columns of xml type are defined just like any other columns. ■Note The xml data type cannot be used in primary keys. Now, you’ll insert your XML documents into xmltest and query it to see that they were stored. Try It Out: Storing and Retrieving XML Documents To insert your XML documents, follow these steps: 1. Replace the code in the SQL query window with the following two INSERT statements: insert into xmltest values( 1, ' <states> <state> <abbr>CA</abbr> <name>California</name> <city>Berkeley</city> <city>Los Angeles</city> <city>Wilmington</city> </state> <state> <abbr>DE</abbr> <name>Delaware</name> <city>Newark</city> <city>Wilmington</city> </state> </states> ' ) CHAPTER 7 ■ USING XML 131 9004ch07final.qxd 12/13/07 4:15 PM Page 131 insert into xmltest values( 2, ' <states> <state abbr="CA" name="California"> <city name="Berkeley"/> <city name="Los Angeles"/> <city name="Wilmington"/> </state> <state abbr="DE" name="Delaware"> <city name="Newark"/> <city name="Wilmington"/> </state> </states> ' ) 2. Run the two INSERT statements by clicking Execute, and then display the table with select * from xmltest. You see the two rows displayed. Click the xdoc column in the first row, and you should see the XML shown in Figure 7-5. Figure 7-5. Viewing an XML document CHAPTER 7 ■ USING XML132 9004ch07final.qxd 12/13/07 4:15 PM Page 132 How It Works This works the same way all INSERTs work. You simply provide the primary keys as inte- gers and the XML documents as strings. The query works just as expected, too. Summary This chapter covered the fundamentals of XML that every C# programmer needs to know. It also showed you how to use the most frequently used T-SQL features for extract- ing XML from tables and querying XML documents like tables. Finally, we discussed the xml data type and gave you some practice using it. How much more you need to know about XML or T-SQL and ADO.NET facilities for using XML documents depends on what you need to do. As for many developers, this chapter may be all you ever really need to know and understand. If you do more sophisticated XML processing, you now have a strong foundation for experimenting on your own. In the next chapter, you will learn about database transactions. CHAPTER 7 ■ USING XML 133 9004ch07final.qxd 12/13/07 4:15 PM Page 133 9004ch07final.qxd 12/13/07 4:15 PM Page 134 Understanding Transactions For any business, transactions, which may comprise many individual operations and even other transactions, play a key role. Transactions are essential for maintaining data integrity, both for multiple related operations and when multiple users update the data- base concurrently. This chapter will talk about the concepts related to transactions and how trans- actions can be used in SQL Server 2005 and C#. In this chapter, we’ll cover the following: • 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 • G uidelines to code efficient tr ansactions • How to code transactions What Is a Transaction? A transaction is a set of oper ations per formed so all operations are guaranteed to succeed or fail as one unit. 135 CHAPTER 8 9004ch08final.qxd 12/13/07 4:13 PM Page 135 A common example of a transaction is the process of transferring money from a checking account to a savings account. This involves two operations: deducting money from the checking account and adding it to the savings account. Both must succeed together and be committed to the accounts, or both must fail together and be rolled back so that the accounts are maintained in a consistent state. Under no circumstances should money be deducted from the checking account but not added to the savings account (or vice versa)—at least you would not want this to happen with the transactions occurring with your bank accounts. By using a transaction, both the operations, namely debit and credit, can be guaranteed to succeed or fail together. So both accounts remain in a con- sistent state all the time. When to Use Transactions You should use transactions when several operations must succeed or fail as a unit. The following are some frequent scenarios where use of transactions is recommended: • In batch processing, where multiple rows must be inserted, updated, or deleted as a single unit • Whenever a change to one table requires that other tables be kept consistent • When modifying data in two or more databases concurrently • In distributed transactions, where data is manipulated in databases on different servers When y ou use transactions, you place locks on data pending permanent change to the database. No other operations can take place on locked data until the lock is r eleased. You could lock anything from a single row up to the whole database. This is called con- currency , which means how the database handles multiple updates at one time. In the bank example, locks ensure that two separate transactions don’t access the same accounts at the same time. If they did, either deposits or withdrawals could be lost. ■Note It’s important to keep transactions pending for the shortest period of time. A lock stops others from accessing the locked database resource. Too many locks, or locks on frequently accessed resources, can seriously degrade performance. CHAPTER 8 ■ UNDERSTANDING TRANSACTIONS136 9004ch08final.qxd 12/13/07 4:13 PM Page 136 [...]... in C# 4 Add three labels, three text boxes, and a button to the form as shown in Figure 8-7 Figure 8-7 ADO.NET transaction form 5 Add a using directive to Transaction.cs using System.Data.SqlClient; 6 Next you want to add a click event for the button Double-click button1, and it will open the code editor with the button1_click event Insert the code in Listing 8-2 into the code editor Listing 8-2 button1_Click()... transaction to both add a customer to and delete one from the Northwind Customers table The Customers table has eleven columns; two columns, CustomerID and CompanyName, don’t allow null values, whereas the rest do, so you’ll use just the CustomerID and CompanyName columns for inserting values You’ll also use arbitrary customer IDs to make it easy to find the rows you manipulate when viewing customers sorted... @newconame) Save error number returned from Insert statement set @inserr = @@error if @inserr > @maxerr set @maxerr = @inserr Delete a customer delete from customers where customerid = @oldcustid Save error number returned from Delete statement set @delerr = @@error if @delerr > @maxerr set @maxerr = @delerr 147 9004ch08final.qxd 148 12/13/07 4: 13 PM Page 148 CHAPTER 8 s UNDERSTANDING TRANSACTIONS... sorted by ID 143 9004ch08final.qxd 144 12/13/07 4: 13 PM Page 144 CHAPTER 8 s UNDERSTANDING TRANSACTIONS 1 Open SQL Server Management Studio Express, and in the Connect to Server dialog box, select \SQLEXPRESS as the server name and then click Connect 2 In Object Explorer, expand the Databases node, select the Northwind database, and click the New Query button 3 Create a stored procedure... of customer “aa” 149 9004ch08final.qxd 150 12/13/07 4: 13 PM Page 150 CHAPTER 8 s UNDERSTANDING TRANSACTIONS Try It Out: What Happens When the Second Operation Fails In this example, you’ll insert a valid new customer and try to delete a customer who has child records in Orders table Add customer “aaa” and delete customer ALFKI by entering the following statement, and then click the Execute button exec... nvarchar (40 ), @oldcustid nchar(5) as declare @inserr int declare @delerr int declare @maxerr int set @maxerr = 0 begin transaction Add a customer insert into customers (customerid, companyname) values(@newcustid, @newcompname) Save error number returned from Insert statement set @inserr = @@error if @inserr > @maxerr set @maxerr = @inserr Delete a customer delete from customers where customerid... when you execute the stored procedure You run it twice, first by adding customer “a” and next by adding customer “aa”, but you also enter the same nonexistent customer to delete each time If all statements in a transaction are supposed to succeed or fail as one unit, why does the INSERT succeed when the DELETE doesn’t delete anything? 9004ch08final.qxd 12/13/07 4: 13 PM Page 149 CHAPTER 8 s UNDERSTANDING... time You should see that customer “aa” has been added to the Customers table Both customer “a” and “aa” have no child records in the Orders table 9004ch08final.qxd 12/13/07 4: 13 PM Page 147 CHAPTER 8 s UNDERSTANDING TRANSACTIONS How It Works In the stored procedure, you define three input parameters: create procedure sp_Trans_Test @newcustid nchar(5), @newcompname nvarchar (40 ), @oldcustid nchar(5) as... failure of the commit to the application 141 9004ch08final.qxd 142 12/13/07 4: 13 PM Page 142 CHAPTER 8 s UNDERSTANDING TRANSACTIONS Guidelines to Code Efficient Transactions We recommend you use the following guidelines while coding transactions to make them as efficient as possible: • Do not require input from users during a transaction Get all required input from users before a transaction is started... 12/13/07 4: 12 PM Page 159 CHAPTER 9 s GETTING TO KNOW ADO.NET Moving from ADO to ADO.NET ADO is a collection of ActiveX objects that are designed to work in a constantly connected environment It was built on top of OLE DB (which we’ll look at in the “Working with the OLE DB Data Provider” section) OLE DB provides access to non-SQL data as well as SQL databases, and ADO provides an interface designed to make . XML128 9004ch07final.qxd 12/13/07 4: 14 PM Page 128 Figure 7 -4. Using FOR XML AUTO How It Works The CustomerID references the Cust table. Therefore, a Cust element is created and CustomerID is. T-SQL H ere, you’ll code a transaction to both add a customer to and delete one from the N orthwind Customers table. The Customers table has eleven columns; two columns, C ustomerID and CompanyName, don’t. stor ed pr ocedure CHAPTER 8 ■ UNDERSTANDING TRANSACTIONS 145 9004ch08final.qxd 12/13/07 4: 13 PM Page 145 5. In the same query window, enter the following SELECT statement: S elect * from Customers Select

Ngày đăng: 08/08/2014, 18:21

TỪ KHÓA LIÊN QUAN