15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Comm<strong>and</strong>s ❘ 829<br />

}<br />

}<br />

{<br />

data = xr.ReadOuterXml();<br />

if (!string.IsNullOrEmpty(data))<br />

Console.WriteLine(data);<br />

} while (!string.IsNullOrEmpty(data));<br />

conn.Close();<br />

code download ExecuteReaderExample.cs<br />

Note that you have to import the System.Xml namespace in order to output the returned XML. This<br />

namespace <strong>and</strong> further XML capabilities of .<strong>NET</strong> Framework are explored in more detail in Chapter 33,<br />

“Manipulating XML.” Here, you include the FOR XML AUTO clause in the SQL statement, then call the<br />

ExecuteXmlReader() method. Figure 30-3 shows the output of this code.<br />

figure 30-3<br />

In the SQL clause, you specified FROM Customers, so an element of type Customers is shown in the output.<br />

To this are added attributes, one for each column selected from the database. This builds up an XML<br />

fragment for each row selected from the database.<br />

Calling stored Procedures<br />

Calling a stored procedure with a comm<strong>and</strong> object is just a matter of defining the name of the stored<br />

procedure, adding a definition for each parameter of the procedure, <strong>and</strong> then executing the comm<strong>and</strong> with<br />

one of the methods presented in the previous section.<br />

To make the examples in this section more useful, a set of stored procedures has been defined that can be<br />

used to insert, update, <strong>and</strong> delete records from the Region table in the Northwind sample database. Despite<br />

its small size, this is a good c<strong>and</strong>idate to choose for the example because it can be used to define examples<br />

for each of the types of stored procedures you will commonly write.<br />

Calling a stored Procedure That returns nothing<br />

The simplest example of calling a stored procedure is one that returns nothing to the caller. Two such<br />

procedures are defined in the following two subsections: one for updating a preexisting Region record <strong>and</strong><br />

one for deleting a given Region record.<br />

Record Update<br />

Updating a Region record is fairly trivial because there is only one column that can be modified (assuming<br />

primary keys cannot be updated). You can type these examples directly into the SQL Server Query<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!