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
Thông tin cơ bản
Định dạng
Số trang
44
Dung lượng
1,31 MB
Nội dung
Try It Out: Executing a Stored Procedure with Parameters In this example, you’ll call the sp_Orders_By_EmployeeId2 stored procedure, supplying the employee ID as an input parameter and displaying the result set, the output parameter, and t he return value. 1. Add a new VB .NET Console Application project named CallSp2 to your Chapter6 solu- tion. Rename Module1.vb to CallSp2.vb. 2. Replace the code in CallSp2.vb with the code in Listing 6-2. Listing 6-2. CallSp2.vb Imports System Imports System.Data Imports System.Data.SqlClient Namespace Chapter6 Class CallSp2 Shared Sub Main() ' create connection Dim conn As New SqlConnection conn.ConnectionString = "Data Source=.\sqlexpress;Initial Catalog=Northwind;Integrated Security=True" Try ' open connection conn.Open() ' create command Dim cmd As SqlCommand = conn.CreateCommand() ' specify stored procedure to execute cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = "sp_orders_by_employeeid2" ' create input parameter Dim inparm As SqlParameter = cmd.Parameters.Add( _ "@employeeid", SqlDbType.Int) inparm.Direction = ParameterDirection.Input inparm.Value = 2 ' create output parameter Dim ouparm As SqlParameter = cmd.Parameters.Add( _ "@ordercount", SqlDbType.Int) ouparm.Direction = ParameterDirection.Output CHAPTER 6 ■ USING STORED PROCEDURES 103 9470ch06final.qxd 2/21/08 3:02 PM Page 103 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ' create return value parameter Dim retval As SqlParameter = cmd.Parameters.Add( _ "return_value", SqlDbType.Int) retval.Direction = ParameterDirection.ReturnValue ' execute command Dim rdr As SqlDataReader = cmd.ExecuteReader() ' Process the result set While rdr.Read() Console.WriteLine("{0} {1}", rdr(0).ToString().PadRight(5), rdr(1).ToString()) End While rdr.Close() ' display output parameter value Console.WriteLine("The output parameter value is {0}" _ , cmd.Parameters("@ordercount").Value) ' display return value Console.WriteLine( _ "The return value is {0}" _ , cmd.Parameters("return_value").Value) Catch ex As SqlException Console.WriteLine(ex.ToString()) Finally conn.Close() End Try End Sub End Class End Namespace 3. Make this the startup project and run it by pressing Ctrl+F5. You should see the results shown in F igure 6-10. CHAPTER 6 ■ USING STORED PROCEDURES104 9470ch06final.qxd 2/21/08 3:02 PM Page 104 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 6-10. Using parameters and the return value with VB .NET How It Works This is very much like the previous example. The main difference is that you add three com- mand parameters, specifying the kind of parameter with the Direction property: ' create input parameter Dim inparm As SqlParameter = cmd.Parameters.Add( _ "@employeeid", SqlDbType.Int) inparm.Direction = ParameterDirection.Input inparm.Value = 2 ' create output parameter Dim ouparm As SqlParameter = cmd.Parameters.Add( _ "@ordercount", SqlDbType.Int) ouparm.Direction = ParameterDirection.Output ' create return value parameter Dim retval As SqlParameter = cmd.Parameters.Add( _ "return_value", SqlDbType.Int) retval.Direction = ParameterDirection.ReturnValue Y ou set the input parameter value to 2 before the call: inparm.Value = 2 and retrieve the values for the output parameter and return value by indexing into the com- mand’s parameters collection after the stored procedure is returned: CHAPTER 6 ■ USING STORED PROCEDURES 105 9470ch06final.qxd 2/21/08 3:02 PM Page 105 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ' display output parameter value Console.WriteLine("The output parameter value is {0}" _ , cmd.Parameters("@ordercount").Value) ' display return value Console.WriteLine( _ "The return value is {0}" _ , cmd.Parameters("return_value").Value) You can create as many input and output parameters as you need. You must provide command parameters for all input parameters that don’t have default values. You don’t have to provide command parameters for any output parameters you don’t need to use. Input and output parameter names must agree with the parameter names in the stored procedure, except for case (remember that T-SQL is not case sensitive). Though it’s handled in ADO.NET as a command parameter, there is always only one return value. Like output parameters, you don’t need to create a command parameter for the return value unless you intend to use it. But unlike input and output parameters, you can give it whatever parameter name you choose. Deleting Stored Procedures Once a stored procedure is created, it can also be deleted if its functionality is not required. Try It Out: Deleting a Stored Procedure You’ll delete your first stored procedure (sp_Select_All_Employees), which you renamed to sp_Select_Employees_Details. 1. Replace the query with the following statement in the query window and click Execute. Drop procedure sp_Select_Employees_Details You will see the following message: “Command(s) completed successfully.” 2. Navigate to Object Explorer, expand the Northwind database node, and then expand the Pr ogrammability node . Select the Stored Procedures node, right-click, and select Refresh. Notice that the procedure sp_Select_Employees_Details has been deleted, as it is no longer listed in Object Explorer (see Figure 6-11). CHAPTER 6 ■ USING STORED PROCEDURES106 9470ch06final.qxd 2/21/08 3:02 PM Page 106 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 6-11. Deleting a stored procedure How It Works SQL Server offers the DROP statement to remove objects. To remove the stored procedure, you use drop procedure sp_Select_Employees_Details In this statement, DROP takes the procedure sp_Select_Employees_Details as its value and will thus remove it. Summary In this chapter, you created stored procedures; you developed an understanding of what’s involved in calling stored procedures from VB .NET. You saw that calling stored procedures isn’t inherently different from executing queries and statements; you simply create appropri- ate command parameters for the stored procedure parameters you need to use. You also learned about modifying a stored procedure, retrieving metadata information, and renaming and deleting a stor ed pr ocedur e , as well as calling a stored procedure from VB .NET applica- tions using ADO .NET. In the next chapter, you will see how to work with XML. CHAPTER 6 ■ USING STORED PROCEDURES 107 9470ch06final.qxd 2/21/08 3:02 PM Page 107 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 9470ch06final.qxd 2/21/08 3:02 PM Page 108 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Using XML XML has been around for many years; with the release of Microsoft .NET technology, XML has become even more popular. Microsoft’s development tools and technologies have built-in features to support XML. The advantages of using XML and its related technologies are major foundations of both the Internet and .NET. Our goal in this chapter is to introduce you to the most essential XML concepts and ter- minology and the most basic techniques for using XML with SQL Server 2005. This will enable you to handle some common programming tasks while writing a software application. In this chapter, we’ll cover the following: • Defining XML • Why XML? • Benefits of storing data as XML • Understanding XML documents • Understanding the XML declaration • Converting relational data to XML • How to store and retrieve XML documents using the xml data type Defining XML XML stands for eXtensible Markup Language. XML, which is derived from SGML (Standard Generalized Markup Language), is a metalanguage. A metalanguage isn’t used for program- ming but rather for defining other languages, and the languages XML defines are known as mar kup languages . M arkup is exactly what it implies: a means of “ marking up” something. The XML document is in the form of a text document, and it can be read by both humans and computers. 109 CHAPTER 7 9470ch07final.qxd 2/21/08 3:01 PM Page 109 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ■Note In essence, each XML document is an instance of a language defined by the XML elements used in the document. The specific language may or may not have been explicitly defined, but professional use of XML demands carefully planning one’s XML vocabulary and specifying its definition in a schema that can be used to validate that documents adhere to both the syntax and semantics of a vocabulary. The XML Schema Definition language (usually referred to as XSD) is the language for defining XML vocabularies. The World Wide Web Consortium (W3C) developed XML in 1996. Intended to support a wide variety of applications, XML was used by the W3C to create eXtensible HTML (XHTML), an XML vocabulary. Since 1996, the W3C has developed a variety of other XML-oriented tech- nologies, including eXtensible Stylesheet Language (XSL), which provides the same kind of facility for XHTML that Cascading Style Sheets (CSS) does for HTML, and XSL Transformations (XSLT), which is a language for transforming XML documents into other XML documents. Why XML? XML is multipurpose, extensible data representation technology. XML increases the possibili- ties for applications to consume and manipulate data. XML data is different from relational data in that it can be structured, semistructured, or unstructured. XML support in SQL Server 2005 is fully integrated with the relational engine and query optimizer, allowing the retrieval and modification of XML data and even the conversion between XML and relational data representations. Benefits of Storing Data As XML XML is a platform-independent, data-representation format that offers certain benefits over a relational format for specific data representation requirements. Storing data as XML offers many benefits, such as the following: • Since XML is self-describing, applications can consume XML data without knowing the schema or str uctur e . XML data is always arranged hierarchically in a tree structure form. XML tree structure must always have a root, or parent node, which is known as an XML document. • XML maintains document ordering. Because XML is arranged in tree structure, main- taining node order becomes easy. • XML Schema is used to define valid XML document structure. • Because of XML’s hierarchical structure, you can search inside the tree structures. X Query and XPath are the query languages designed to search XML data. • Data stored as XML is extensible. It is easy to manipulate XML data by inserting, modi- fying, and deleting nodes . CHAPTER 7 ■ USING XML110 9470ch07final.qxd 2/21/08 3:01 PM Page 110 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ■Note Well-formed XML is an XML document that meets a set of constraints specified by the W3C recommendation for XML 1.0. For example, well-formed XML must contain a root-level element, and any other nested elements must open and close properly without intermixing. SQL Server 2005 validates some of the constraints of well-formed XML. Some rules such as the requirement for a root-level element are not enforced. For a complete list of requirements for well-formed XML, refer to the W3C recommendations for XML 1.0 at http://www.w3.org/TR/REC-xml. Understanding XML Documents An XML document could be a physical file on a computer, a data stream over a network (in theory, formatted so a human could read it, but in practice, often in compressed binary form), or just a string in memory. It has to be complete in itself, however, and even without a schema, it must obey certain rules. The most fundamental rule is that XML documents must be well formed. At its simplest, this means that overlapping elements aren’t allowed, so you must close all child elements before the end tag of their parent element. For example, this XML document is well formed: <states> <state> <name>Delaware</name> <city>Dover</city> <city>Wilmington</city> </state> </states> It has a root (or document) element, states, delimited by a start tag, <states>, and an end tag, </states>. The root element is the parent of the state element, which is in turn the parent of a name element and two city elements. An XML document can have only one root element. Elements may have attributes. In the following example, name is used as an attribute with the state element: <states> <state name="Delaware"> <city>Dover</city> <city>Wilmington</city> </state> </states> This r etains the same infor mation as the earlier example , r eplacing the name element, which occurs only once, with a name attribute and changing the content of the original element ( Delaware) into the v alue of the attr ibute ( "Delaware"). An element may hav e any number of attributes , but it may not hav e duplicate attr ibutes , so the city elements w er en ’ t candidates for replacement. CHAPTER 7 ■ USING XML 111 9470ch07final.qxd 2/21/08 3:01 PM Page 111 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Elements may have content (text data or other elements), or they may be empty. For e xample, just for the sake of argument, if you want to keep track of how many states are in the document, you could use an empty element to do it: <states> <controlinfo count="1"/> <state name="Delaware"> <city>Dover</city> <city>Wilmington</city> </state> </states> The empty element, controlinfo, has one attribute, count, but no content. Note that it isn’t delimited by start and end tags, but exists within an empty element tag (that starts with < and ends with />). An alternative syntax for empty elements, using start and end tags, is also valid: <controlinfo count="1"></controlinfo> Many programs that generate XML use this form. ■Note Though it’s easy to design XML documents, designing them well is as much a challenge as designing a database. Many experienced XML designers disagree over the best use of attributes and even whether attributes should be used at all (and without attributes, empty elements have virtually no use). While elements may in some ways map more ideally to relational data, this doesn’t mean that attributes have no place in XML design. After all, XML isn’t intended to (and in principle can’t) conform to the relational model of data. In fact, you’ll see that a “pure” element-only design can be more diffi- cult to work with in T-SQL. Understanding the XML Declaration In addition to elements and attributes, XML documents can have other parts, but most of them are important only if you need to delve deeply into XML. Though it is optional, the XML declaration is one part that should be included in an XML document to precisely con- form to the W3C recommendation. If used, it must occur before the root element in an XML document. The XML declaration is similar in format to an element, but it has question marks immediately next to the angle br ackets. It always has an attribute named version; curr ently, this has two possible values: "1.0" and "1.1". (A couple other attributes are defined but aren’t required.) So, the simplest form of an XML declaration is <?xml version="1.0" ?> CHAPTER 7 ■ USING XML112 9470ch07final.qxd 2/21/08 3:01 PM Page 112 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... 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 117 947 0ch07final.qxd... 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... return number for it begin transaction Add a customer insert into customers (customerid, companyname) values(@newcustid, @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... Figure 8-7 Figure 8-7 ADO.NET transaction form 5 Add an Imports directive to Transaction .vb: Imports 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() Dim conn As New SqlConnection conn.ConnectionString = "Data Source=.\sqlexpress;"... 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 947 0ch08final.qxd 3/3/08 5:16 PM Page 131 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 8 s UNDERSTANDING TRANSACTIONS CompanyName, don’t allow null values, whereas the rest do, so you’ll use just the CustomerID and... Transactions In this ADO.NET example, you’ll code a VB NET equivalent of sp_Trans_Test 1 Create a new Windows Forms Application project named Chapter8 When Solution Explorer opens, save the solution 2 Rename Form1 .vb to Transaction .vb 3 Change the Text property of Transaction form to ADO.NET Transaction in VB NET 4 Add three labels, three text boxes, and a button to the form as shown in Figure 8-7 Figure 8-7... 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... 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 To create a table to hold XML documents, replace the existing... in Figure 8-3 one more 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 133 947 0ch08final.qxd 3/3/08 5:16 PM Page 1 34 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 1 34 CHAPTER 8 s UNDERSTANDING TRANSACTIONS How It Works In the stored procedure, you define three input parameters:... 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 123 947 0ch08final.qxd 3/3/08 5:16 PM Page 1 24 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 1 24 CHAPTER 8 s UNDERSTANDING TRANSACTIONS from the checking account but not added to . 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 To create a table to hold XML documents,. created stored procedures; you developed an understanding of what’s involved in calling stored procedures from VB .NET. You saw that calling stored procedures isn’t inherently different from executing. well as calling a stored procedure from VB .NET applica- tions using ADO .NET. In the next chapter, you will see how to work with XML. CHAPTER 6 ■ USING STORED PROCEDURES 107 947 0ch06final.qxd