9767408 - Implementing Managed Code in the Database

1,487 views

Published on

SQL - Implementing Managed Code in
the Database

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,487
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

9767408 - Implementing Managed Code in the Database

  1. 1. Module 8Implementing Managed Code inthe DatabaseContents:Lesson 1: Introduction to the SQL ServerCommon Language Runtime 8-2Lesson 2: Importing andConfiguring Assemblies 8-9Lesson 3: Creating ManagedDatabase Objects 8-17Lab: Implementing Managed Codein the Database 8-25
  2. 2. Information in this document, including URL and other Internet Web site references, is subject to changewithout notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with anyreal company, organization, product, domain name, e-mail address, logo, person, place or event is intended orshould be inferred. Complying with all applicable copyright laws is the responsibility of the user. Withoutlimiting the rights under copyright, no part of this document may be reproduced, stored in or introduced intoa retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying,recording, or otherwise), or for any purpose, without the express written permission of MicrosoftCorporation.The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoftmakes no representations and warranties, either expressed, implied, or statutory, regarding thesemanufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer orproduct does not imply endorsement of Microsoft of the manufacturer or product. Links are provided tothird party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for thecontents of any linked site or any link contained in a linked site, or any changes or updates to such sites.Microsoft is not responsible for webcasting or any other form of transmission received from any linked site.Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not implyendorsement of Microsoft of the site or the products contained therein.Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rightscovering subject matter in this document. Except as expressly provided in any written license agreementfrom Microsoft, the furnishing of this document does not give you any license to these patents, trademarks,copyrights, or other intellectual property.©2006 Microsoft Corporation. All rights reserved.Microsoft, JScript, MSDN, Outlook, PowerPoint, Visual Basic, Visual C#, Visual C++, Visual FoxPro, Windows,and Windows Server are either registered tradmarks or trademarks of Microsoft Corporation in the UnitedStates and/or other countries.The names of actual companies and products mentioned herein may be the trademarks of their respectiveowners.
  3. 3. Module 8: Implementing Managed Code in the Database 8–1**************************************** Illegal for non-trainer use ***************************************Module objectives After completing this module, students will be able to: ■ Identify appropriate scenarios for managed code in the database. ■ Import and configure assemblies. ■ Create managed database objects.Introduction The Microsoft® .NET common language runtime (CLR) provides a hosted environment for managed code. In Microsoft SQL Server™ 2005, developers can use managed code to implement database objects such as stored procedures, user-defined data types, user- defined functions, and triggers. This brings the power, scalability, and security of the .NET Framework to database applications. In this module, you will learn how to implement managed code in a SQL Server 2005 database.
  4. 4. 8–2 Module 8: Implementing Managed Code in the DatabaseLesson 1: Introduction to the SQL Server Common LanguageRuntime**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Describe the features of the .NET common language runtime. ■ Describe the advantages of managed code. ■ Describe SQL Server 2005 CLR integration and the benefits of the integration. ■ Explain the guidelines for using managed code and Transact-SQL.Introduction This lesson describes the integration between SQL Server 2005 and the Microsoft .NET CLR. You will learn how managed code provides powerful features for database applications and when it is appropriate to use managed code.
  5. 5. Module 8: Implementing Managed Code in the Database 8–3What Is the .NET Common Language Runtime?**************************************** Illegal for non-trainer use ***************************************Introduction Runtimes are not new to programming. Many programming languages have used runtimes, including Microsoft Visual Basic®, Visual C++®, Visual FoxPro®, and JScript®, in addition to third-party languages such as SmallTalk, Perl, and Java. The critical role of the .NET Framework, and what really sets it apart from other runtimes, is that it provides a unified environment across all programming languages. This environment is also referred to as a managed environment.Features of the CLR The main CLR features are described in the following table. Component Description .NET Framework Integrates code with the runtime that supports the .NET class library support Framework class library. Thread support Provides classes and interfaces that enable multithreaded programming. COM marshaler Provides marshaling to and from Component Object Model (COM) code. Type checker Does not allow unsafe casts or uninitialized variables. Microsoft intermediate language (MSIL) can be verified to guarantee type safety. Exception manager Provides structured exception handling, which is integrated with Microsoft Windows® structured exception handling. Security engine Provides evidence-based security, based on user identity and the origin of the code. Debug engine Enables the developer to debug an application and trace the execution of code. MSIL to native Converts MSIL to native code on a just-in-time (JIT) basis. compilers Code manager Manages code execution.
  6. 6. 8–4 Module 8: Implementing Managed Code in the Database Component Description Garbage collector Provides automatic lifetime management of all objects in the .NET Framework. Class loader Manages metadata and the loading and layout of classes. While a component is running, the CLR is responsible for managing memory allocation, starting and terminating threads and processes, enforcing security policy, and satisfying any dependencies that the component has on other components. During development, the runtime’s role changes slightly. Because it automates many of the “housekeeping” tasks that a program must perform (such as memory management), the CLR makes the developer’s work easier. In particular, the CLR ensures code correctness and type safety. The CLR also dramatically reduces the amount of code that a developer must write to transform business logic into a reusable component.
  7. 7. Module 8: Implementing Managed Code in the Database 8–5Advantages of Managed Code**************************************** Illegal for non-trainer use ***************************************Introduction The managed code environment provides several advantages over older programming environments. SQL Server 2005 allows database developers to make use of these advantages within a database.Programming language You can create managed code in the .NET language of your choice, including Visual Basic and Microsoft Visual C#®. This flexibility in programming language choice enables you to choose the language most appropriate for your business requirements or current skill set instead of forcing you to use a particular language.Type safety The .NET Framework class library is type-safe; therefore, your managed code is also type-safe, regardless of the programming language you use. Type safety is ensured through the common type system, which is part of the common language runtime. For example, type safety ensures that no memory is read that has not been written to.Security The .NET Framework class library provides rich security for managed applications. You can use both code access security and role-based security within your applications. Code access security limits the actions that your application can perform, while role- based security provides authorization of the user in a similar way to SQL Server roles.Fast development The .NET Framework provides an extensive base class library. Using these classes within your managed code reduces the developer effort required to perform common tasks.Interoperability Managed code can interoperate with unmanaged code such as COM components and Windows application programming interfaces (APIs).
  8. 8. 8–6 Module 8: Implementing Managed Code in the DatabaseSQL Server 2005 CLR Integration**************************************** Illegal for non-trainer use ***************************************Introduction SQL Server 2005 integrates the CLR into the Database Engine. This integration provides you with considerable flexibility when designing your database application.Running managed code The integration of the CLR into SQL Server 2005 allows you to run managed codewithin a database directly within a database. In its most basic form, this is a similar concept to calling extended stored procedures in earlier versions of SQL Server. However, the CLR integration provides much more power and flexibility than traditional extended stored procedures do. A deployable unit of managed code is called an assembly. SQL Server 2005 can load and host in-process assemblies (.dll class libraries) only. SQL Server cannot host out of process executables (.exe files).Creating managed CLR integration allows you to create managed objects, including stored procedures,objects triggers, user-defined functions, user-defined types, and aggregates, in any .NET language. You can use these managed objects directly from your SQL Server 2005 databases as you would any other database object.Benefits of integration CLR integration in SQL Server 2005 provides you with many benefits when developing database applications. These benefits include: Enhanced programming mode. The .NET languages offer richer development capabilities than Transact-SQL does. Enhanced safety and security. Managed code runs in a CLR environment hosted by the SQL Server Database Engine. This provides a safer and more secure system than extended stored procedures do. Common development environment. You use the same tools for developing and debugging database objects and scripts as developers use to write .NET components and applications. Performance and scalability. Managed code and managed execution can deliver improved performance over Transact-SQL in many situations.
  9. 9. Module 8: Implementing Managed Code in the Database 8–7For More Information For more information about how to use CLR integrationwithin SQL Server 2005, see “Overview of CLR Integration” in SQL Server BooksOnline.
  10. 10. 8–8 Module 8: Implementing Managed Code in the Database Managed Code vs. Transact-SQL**************************************** Illegal for non-trainer use ***************************************Introduction Now that you can create several database objects by using either Transact-SQL or managed code, you will need to consider each scenario individually before choosing an approach. You can base this decision on some basic guidelines.When to use managed In general, you should use managed code for creating database objects in the followingcode situations: You require complex programmatic logic to complete a task. The managed .NET languages provide powerful features such as object orientation, structured exception handling, and advanced conditional constructs. Features such as namespaces and the ability to create private helper functions make complex logic more manageable. You need to use the .NET Framework base class library. The base class library contains powerful classes that can perform tasks such as the calling of Web services, working with the file system, and many other tasks that are difficult or impossible in Transact-SQL. Your required functionality will be central processing unit (CPU) intensive. Because of the compiled nature of managed code, any functionality that is CPU intensive will run more efficiently than it would if it were implemented by using Transact-SQL.When to use Transact- You should use Transact-SQL for creating database objects when the code will mainlySQL perform data access with little or no procedural logic. This is because Transact-SQL is optimized for set-based operations on data. You should avoid creating managed database objects whose sole purpose is to work with traditional database objects such as tables and views; in this case, use Transact-SQL instead.
  11. 11. Module 8: Implementing Managed Code in the Database 8–9Lesson 2: Importing and Configuring Assemblies**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Explain what an assembly is. ■ Describe the syntax for importing an assembly. ■ Explain assembly trust levels and how to configure security for an assembly. ■ Import and configure an assembly.Introduction To use managed code within a SQL Server 2005 database, you must create a managed assembly and then import it into the database and configure its security options. This lesson describes what an assembly is and how to import and configure an assembly within a database.
  12. 12. 8–10 Module 8: Implementing Managed Code in the DatabaseWhat Is an Assembly?**************************************** Illegal for non-trainer use ***************************************Definition An assembly is a compiled executable that contains types such as classes or structures, methods within the types, and metadata about those types to describe their structure to calling applications. An assembly is the unit of deployment for a managed application; it contains everything necessary to execute successfully, provided that the computer has the .NET Framework installed. Assemblies can be out of process (.exe files) or in process (.dll files). SQL Server 2005 supports the use of in-process assemblies through the SQLCLR. This provides optimal performance because the managed code is actually running within the SQL Server executable, rather than as a separate executable, which would dramatically decrease performance. Therefore, developers must create class libraries when developing for SQL Server.Using an assembly in SQL To use a .NET assembly within a SQL Server 2005 database, you must perform theServer following tasks: 1. Create the required code within a .NET class library project. 2. Compile the .NET assembly. 3. Import the assembly into SQL Server 2005. For More Information For more information about assemblies and the .NET Framework in general, see “Microsoft .NET Framework FAQ” on the MSDN® Web site.
  13. 13. Module 8: Implementing Managed Code in the Database 8–11Syntax for Importing an Assembly**************************************** Illegal for non-trainer use ***************************************Introduction To use a managed assembly within SQL Server 2005, you must import the assembly information into the appropriate database. You can import an assembly by using Object Explorer in SQL Server Management Studio or by using the CREATE ASSEMBLY statement.Syntax for importing The syntax of the CREATE ASSEMBLY statement is shown in the following code.assemblies CREATE ASSEMBLY [ assembly_name ] [ AUTHORIZATION owner_name ] FROM { assembly_file_path | assembly_bits [ ,...n ] } [ WITH PERMISSION_SET = { SAFE | EXTERNAL_ACCESS | UNSAFE } ] To remove an assembly from SQL Server, use the DROP ASSEMBLY statement. You must drop all database objects that reference code in an assembly before dropping the assembly.CREATE ASSEMBLY The CREATE ASSEMBLY statement has the following parameters:statement parameters assembly_name. The assembly_name parameter of the CREATE ASSEMBLY statement specifies the database object name for the assembly. You will use this name when you link database objects, such as stored procedures, to the assembly. The name must be a valid SQL Server identifier and must be unique within the database. assembly_file_path. You reference the assembly file location by using the assembly_file_path parameter in the FROM clause of the CREATE ASSEMBLY statement. You can use a local or network path, but you must provide the address by using Universal Naming Convention (UNC) notation if you are using a network location. The assembly must consist of only one file because SQL Server 2005 does not support multifile assemblies. During the import of an assembly, SQL Server checks for any assembly dependencies within the same path as the main assembly. If dependencies are required but not found within the path, CREATE ASSEMBLY fails. SQL Server also validates the assembly to
  14. 14. 8–12 Module 8: Implementing Managed Code in the Database ensure that managed code does not contain any unsafe code operations. Once again, CREATE ASSEMBLY fails if SQL Server finds any unsafe code. Alternatively, you can use an in-memory binary image of the assembly and its dependent assemblies by specifying a varbinary value in the assembly_bits parameter. PERMISSION_SET. The value assigned in the PERMISSION_SET clause specifies the security trust level assigned to the assembly. The security trust level determines the resources that code in the assembly is allowed to access. The available PERMISSION_SET values are described in the next topic.Example of importing an The following example shows how to import an assembly named Contacts that isassembly located on the local drive. CREATE ASSEMBLY Contacts FROM C:ContactsAppContacts.dll For More Information For more information about the CREATE ASSEMBLY syntax, see “CREATE ASSEMBLY (Transact-SQL)” in SQL Server Books Online.
  15. 15. Module 8: Implementing Managed Code in the Database 8–13Assembly Trust Levels**************************************** Illegal for non-trainer use ***************************************Assembly trust levels You specify a set of code access security permissions for the assembly by using the WITH PERMISSION_SET clause of the CREATE ASSEMBLY statement. The following table describes the three possible options. Value Description SAFE This is the most restrictive option available, and you should use it whenever possible. Assemblies cannot access external system resources such as files, the network, environment variables, or the registry. This is the default value. EXTERNAL_ACCESS Assemblies can access some external system resources, including files, the network, environmental variables, and registry values. UNSAFE Assemblies have unrestricted access to external resources. Assemblies can also call unmanaged code such as COM components and Windows APIs. Only highly trusted assemblies should be granted this permission. You must be a member of sysadmin to create assemblies using this permission. For More Information For more information about assembly trust levels, see “Managing CLR Integration Assemblies” in SQL Server Books Online. If an assembly requires the EXTERNAL_ACCESS or UNSAFE trust level, you must grant the impersonated context used by the assembly the EXTERNAL ACCESS ASSEMBLY permission. You can do this by using a certificate for an individual assembly’s security context, or by making the database trustworthy and allowing all code assemblies that impersonate dbo to access external resources.
  16. 16. 8–14 Module 8: Implementing Managed Code in the Database To use a certificate for an individual assembly’s security context, perform the following tasks: 1. Sign the assembly with a digital signature. 2. Create an asymmetric key from the assembly. 3. Create a login from the assembly key. 4. Grant the login EXTERNAL ACCESS ASSEMBLY permission. To make the database trustworthy and allow all code assemblies that impersonate dbo to access external resources, perform the following tasks: 1. Grant the login for the dbo user EXTERNAL ACCESS ASSEMBLY (this permission is granted to dbo by default). 2. Set the database to be TRUSTWORTHY.Example of setting the The following example shows how to import an assembly named Contacts that isassembly trust level located on a local drive that requires access to the file system. Note that the assembly is signed with a digital signature, and a certificate based on that signature is used to control the assembly’s security context. Use master GO CREATE ASYMMETRIC KEY AdventureWorks_Login FROM EXECUTABLE FILE = C:ContactsAppContacts.dll CREATE LOGIN AWorksCLR FROM ASYMMETRIC KEY AdventureWorks_Login GRANT EXTERNAL ACCESS ASSEMBLY TO AWorksCLR USE AdventureWorks GO CREATE ASSEMBLY Contacts FROM C:ContactsAppContacts.dll WITH PERMISSION_SET = EXTERNAL_ACCESS
  17. 17. Module 8: Implementing Managed Code in the Database 8–15Demonstration: Importing and Configuring an Assembly**************************************** Illegal for non-trainer use ***************************************Introduction In this demonstration, you will see how to enable SQL Server CLR integration and how to import and configure an assembly by using Transact-SQL and SQL Server Management Studio.Importing and To import and configure an existing assembly:configuring an assembly 1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and then click SQL Server Management Studio. 2. In the Connect to Server dialog box, specify the values in the following table, and then click Connect. Property Value Server type Database Engine Server name MIAMI Authentication Windows Authentication 3. On the File menu, point to Open, and then click File. 4. Open the RegisterAssembly.sql query file in the D:Democode folder. Connect to MIAMI by using Windows authentication when prompted. 5. Select the code under the comment Enable CLR integration, and then click the Execute button on the toolbar. This allows SQL Server to execute managed code. 6. Select the code under the comment Register assembly, and then click the Execute button. This imports the managed assembly. 7. Select the code under the comment Drop assembly, and then click the Execute button. This removes the managed assembly. 8. If Object Explorer is not visible, click Object Explorer on the View menu. 9. In Object Explorer, expand Databases and the AdventureWorks database, and then expand Programmability.
  18. 18. 8–16 Module 8: Implementing Managed Code in the Database 10. Right-click Assemblies, and then click New Assembly. 11. In the New Assembly dialog box, click Browse, select the D:DemocodeUtilities.dll file, and then click Open. Click OK to create the assembly reference. 12. Expand the Assemblies folder and verify that the assembly has been imported. 13. Do not close SQL Server Management Studio. You will use it in the next demonstration.
  19. 19. Module 8: Implementing Managed Code in the Database 8–17Lesson 3: Creating Managed Database Objects**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Describe how database objects are mapped to managed code. ■ Describe how managed stored procedures, triggers, and user-defined functions are created. ■ Describe how managed aggregates and user-defined types are created. ■ Create managed database objects.Introduction In this lesson, you will learn how the different managed items within an assembly map to database objects such as stored procedures and triggers. You will also learn how to reference and execute managed code within the database.
  20. 20. 8–18 Module 8: Implementing Managed Code in the DatabaseOverview of Managed Database Objects**************************************** Illegal for non-trainer use ***************************************Introduction Each managed database object must map to a specific .NET code item. To understand this mapping, you must understand the different code items within a .NET assembly..NET assemblies As described in a previous topic, .NET assemblies contain compiled code that can include complex business logic and access to the .NET Framework. This compiled code is broken down into the following items: Namespaces. A namespace is a logical grouping of classes, structures, enumerations, and other code items. It allows a developer to place logically related items together in a single namespace for ease of use and maintenance. Namespaces also allow developers to create two or more items with the same name but within different namespaces. For example, a developer could legitimately create two classes named Address, one in a Customer namespace and one in a Supplier namespace. Classes. A class usually contains a series of internal storage variables, publicly accessible properties (attributes of the class), and publicly accessible methods (operations that the class can perform). At run time, an object is created (or instantiated) based on a specific class definition. It is this object that actually exists in memory and performs the operations on the variables. Methods. A method contains code to perform a specific task. A class can provide multiple methods.Mapping database SQL Server 2005 allows you to map database objects to managed code to take advantageobjects to managed code of .NET assemblies within your database. The following table describes the mapping between .NET code and database objects and shows how aggregate functions and user- defined types are mapped to classes in the assembly, while stored procedures, triggers, and user-defined functions are mapped to individual methods. Code item Database objects Classes ■ Aggregate functions ■ User-defined types
  21. 21. Module 8: Implementing Managed Code in the Database 8–19Code item Database objectsMethods ■ Stored procedures ■ Triggers ■ User-defined functionsNote Creating an aggregate allows you to perform aggregations on groups of data inthe same way as the inbuilt SUM or AVG functions.Creating user-defined types allows you to store serialized .NET objects as columns orvariables within your database.For more information about when to create user-defined types, see “CLR User-DefinedTypes” in SQL Server Books Online.
  22. 22. 8–20 Module 8: Implementing Managed Code in the DatabaseManaged Stored Procedures, Triggers, and Functions**************************************** Illegal for non-trainer use ***************************************Introduction To use managed code from your database, you need to create a database object that calls the managed code. You must have already registered the assembly by using the CREATE ASSEMBLY statement before linking to any managed code. You can create managed code for stored procedures, triggers, and user-defined functions by mapping them to methods in an assembly. You must use the appropriate CREATE PROCEDURE, CREATE TRIGGER, or CREATE FUNCTION statement for the type of object that you want to create.Mapping stored The syntax of the CREATE statements is the same as for standard database objects,procedures, triggers, and except for the AS clause of the statement. This is where you would normally specify theuser-defined functions to Transact-SQL statements that implement the stored procedure, trigger, or function.methods When linking to a managed assembly, you use the EXTERNAL NAME keywords to specify the assembly, class name, and method name of the method that contains the managed code. The EXTERNAL NAME clause has the following syntax. EXTERNAL NAME AssemblyName.[[Namespace].ClassName].MethodName Namespaces are used in managed code to group related functionality within a logical naming context. The following example shows how to create a stored procedure that executes some managed code whenever the stored procedure is called. CREATE PROCEDURE Person.UpdatePhoneList AS EXTERNAL NAME Contacts.[Contacts.PhoneList].SaveList In this example, the Contacts assembly has already been registered with SQL Server by using the CREATE ASSEMBLY statement. The assembly contains a class named PhoneList in a namespace named Contacts, which in turn includes a method named SaveList. The SaveList method is the procedure that executes whenever a client calls the UpdatePhoneList stored procedure.
  23. 23. Module 8: Implementing Managed Code in the Database 8–21 If the assembly had contained no namespaces, the stored procedure could have been registered as shown in the following example. CREATE PROCEDURE Person.UpdatePhoneList AS EXTERNAL NAME Contacts.PhoneList.SaveList If the managed code expects parameters, the stored procedure or user-defined function definition must also list the appropriate parameters.Using the database After linking the managed code to the database object, you can execute the code byobject using the standard syntax for calling a stored procedure or user-defined function. If you use a trigger to call managed code, the code is automatically invoked when the trigger fires. The following example shows how to call the Person.UpdatePhoneList stored procedure. EXEC Person.UpdatePhoneList Note By default, execution of user code in the .NET Framework is disabled within SQL Server 2005. You must use the command sp_configure clr enabled, 1 or enable CLR integration by using the Surface Area Configuration tool to enable execution of user code.
  24. 24. 8–22 Module 8: Implementing Managed Code in the DatabaseManaged Aggregates and User-Defined Types**************************************** Illegal for non-trainer use ***************************************Introduction The process of using managed aggregates and user-defined types is the same as for stored procedures, as described in the preceding topic. The main difference is that you will reference a managed class rather than a method from within the database.Mapping aggregates and Aggregates and user-defined types map to managed classes, so the EXTERNAL NAMEuser-defined types to clause has the following syntax.classes EXTERNAL NAME AssemblyName.[[Namespace].ClassName] The following example shows how to create an aggregate that concatenates strings from a table. CREATE AGGREGATE Concatenate(@input nvarchar(4000)) RETURNS nvarchar(4000) EXTERNAL NAME Utilities.[Utilities.Concatenate] In this example, the Utilities assembly has already been registered with SQL Server by using the CREATE ASSEMBLY statement. The assembly contains a class named Concatenate in a namespace named Utilities that must adhere to a well-defined programmatic contract. The aggregation contract includes the mechanism to save the intermediate state of the aggregation, and the mechanism to accumulate new values, which consists of four methods: Init, Accumulate, Merge, and Terminate. For More Information For more information about creating aggregates, see “Requirements for CLR User-Defined Aggregates” in SQL Server Books Online.Using the database After linking the managed code to the database object, you can execute the code byobject using the standard syntax for calling an aggregate or a standard data type.
  25. 25. Module 8: Implementing Managed Code in the Database 8–23The following example shows how to call the Concatenate aggregate to list the salesorder numbers for each account number. SELECT AccountNumber, dbo.Concatenate(SalesOrderNumber) Orders FROM Sales.SalesOrderHeader GROUP BY AccountNumberThis SELECT statement would produce the following results. AccountNumber Orders -------------- ----------------------------------------------- 10-4020-000001 SO43860,SO44501,SO45283,SO46042 10-4020-000002 SO46976,SO47997,SO49054,SO50216,SO51728,SO57044 etc.
  26. 26. 8–24 Module 8: Implementing Managed Code in the DatabaseDemonstration: Creating Managed Database Objects**************************************** Illegal for non-trainer use ***************************************Introduction In this demonstration, you will see how to create managed database objects that use a managed user-defined function and a user-defined type.Creating a managed To create a managed user-defined function:user-defined function 1. On the File menu in SQL Server Management Studio, point to Open, and then click File. 2. Open the CreateManagedObjects.sql query file in the D:Democode folder. Connect to MIAMI by using Windows authentication when prompted. 3. Select the code under the comment Create the managed user-defined function, and then click the Execute button on the toolbar. This creates the GetOSVersion function. 4. Select the code under the comment Test the managed user-defined function, and then click the Execute button. This displays the operating system version information that the managed code retrieves from the .NET Framework.Creating a managed To create a managed user-defined type:user-defined type 1. Select the code under the comment Create managed user-defined type, and then click the Execute button on the toolbar. This creates the Point managed data type. 2. Select the code under the comment Test the managed user-defined type, and then click the Execute button. This creates a Point local variable, assigns a value to the variable, and then displays the X and Y values from Point. 3. Select the code under the comment Create table using managed user-defined type, and then click the Execute button. This creates a table that uses the Point data type for one of the table columns and then inserts data into the table and displays the information. 4. Select the code under the comment Clean up, and then click the Execute button. This removes all of the managed code created during the demonstrations. 5. Close SQL Server Management Studio.
  27. 27. Module 8: Implementing Managed Code in the Database 8–25Lab: Implementing Managed Code in the Database**************************************** Illegal for non-trainer use ***************************************Scenario Adventure Works is enhancing the current database by adding some managed code to perform some extra functionality not currently available within the database. The senior database developer has created the managed assembly named AWorksUtilities.dll; you will only need to import, configure, and test the assembly. The AWorksUtilities.dll managed assembly is located in the D:LabfilesStarter folder. The AWorksUtilities.dll managed assembly contains the following items: ■ A stored procedure named SaveXML to store XML data in a file. The XML data and file name are passed as parameters to managed code. ■ A user-defined function named GetLongDate returns a long date string based on a date parameter. ■ A trigger named EmailChange for use with updates to the Person.Contact table. Currently, this trigger simply prints out the new e-mail address on the screen, but in a future version, this trigger will perform complex validation on the e-mail address. ■ An aggregate named Concatenate that joins string values together into a larger string, separated by commas. ■ A user-defined type named IPAddress for storing network addresses while allowing for querying of individual parts of the address. This type also contains a Ping method that in a future version will test the IP address by “pinging” it to check whether it is valid. The senior database developer has provided you with a SQL Server Scripts solution named AWorks_CLR.ssmssln in the D:LabfilesStarter folder and the following requirements for the modifications you must make. ■ The SaveXML stored procedure should accept one xml parameter named @XmlData and one nvarchar(100) parameter named @FileName. The external name of the managed stored procedure is AWorksUtilities.StoredProcedures.SaveXML.
  28. 28. 8–26 Module 8: Implementing Managed Code in the Database ■ The GetLongDate user-defined function should accept one datetime parameter named @DateVal and should return an nvarchar(50) value. The external name of the managed function is AWorksUtilities.UserDefinedFunctions.GetLongDate. ■ The EmailChange trigger should fire only on updates to the Person.Contact table. The external name of the trigger is AWorksUtilities.Triggers.EmailChange. ■ The Concatenate aggregate accepts one nvarchar(4000) parameter named @input and returns an nvarchar(4000) value. The external name of the aggregate is AWorksUtilities.Concatenate. ■ The IPAddress user-defined type has the external name AWorksUtilities.IPAddress.Additional information When performing database development tasks, it can be helpful to use SQL Server Management Studio to create a SQL Server Scripts project, and use it to document the Transact-SQL code necessary to re-create the solution if necessary. Use the following procedure to create a SQL Server Scripts project: 1. Open SQL Server Management Studio, connecting to the server you want to manage. 2. On the File menu, point to New, and then click Project. 3. Select the SQL Server Scripts template and enter a suitable name and location for the project. Note that you can create a solution that contains multiple projects, but in many cases a single project per solution is appropriate. To add a query file to a project: 1. Click New Query on the Project menu, or right-click the Queries folder in Solution Explorer and click New Query. If Solution Explorer is not visible, you can display it by clicking Solution Explorer on the View menu. 2. When prompted, connect to the server on which you want to execute the query. This will add a connection object to the project. 3. Change the name of the query file from the default name (SQLQuery1.sql) by right-clicking it in Solution Explorer and clicking Rename. Although you can perform all database development tasks by executing Transact-SQL statements, it is often easier to use the graphical user interface in SQL Server Management Studio. However, you should generate the corresponding Transact-SQL scripts and save them in the project for future reference. Often, you can generate the Transact-SQL script for an action before clicking OK in the Properties dialog box used to perform the action. Many Properties dialog boxes include a Script drop-down list with which you can script the action to a new query window, a file, the Clipboard, or a SQL Server Agent job. A common technique is to add a blank query file to a project, and then script each action to the Clipboard as it is performed and paste the generated script into the query file. You can also generate scripts for many existing objects, such as databases and tables. To generate a script, right-click the object in Object Explorer and script the CREATE action. If Object Explorer is not visible, you can display it by clicking Object Explorer on the View menu.
  29. 29. Module 8: Implementing Managed Code in the Database 8–27Preparation Ensure that virtual machine 2779A-MIA-SQL-08 is running and that you are logged on as Student. If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd.
  30. 30. 8–28 Module 8: Implementing Managed Code in the DatabaseExercise 1: Importing an AssemblyImporting theAWorksUtilities assembly Task Supporting information Import the AWorksUtilities 1. Start SQL Server Management Studio, and then assembly. connect to MIAMI when prompted. 2. Open the D:LabfilesStarterAWorks_CLR.ssmssln solution. 3. Open the Initialize.sql query file, and then execute the query, and confirm that no errors occur. 4. Open the ImportAssembly.sql query file, and under the Enable CLR integration comment, add code to use sp_configure to enable CLR integration in SQL Server. Execute the configuration change, and then call RECONFIGURE to force the change to occur immediately. 5. Under the Create assembly comment, add code to import the AWorksUtilities assembly into the AdventureWorks database with the default security permissions. You will change the permissions in a later exercise. 6. Execute your CREATE ASSEMBLY statement, and confirm that no errors occur.
  31. 31. Module 8: Implementing Managed Code in the Database 8–29Exercise 2: Creating Managed Database ObjectsCreating the SaveXMLmanaged stored Task Supporting informationprocedure Create the SaveXML 1. Open the SaveXML.sql query file. managed stored procedure 2. Under the Create managed stored procedure referencing the external comment, add code to create the SaveXML stored assembly. procedure in the AdventureWorks database, as described in the scenario. 3. Execute your CREATE PROCEDURE statement, and confirm that no errors occur. 4. Under the Test managed stored procedure comment, select the DECLARE, SET, and EXEC statements. Execute these statements, and confirm that an error message is displayed because the assembly does not have the required permissions to write to the file system. 5. Under the Change security permissions to allow file access comment, type an ALTER ASSEMBLY statement granting EXTERNAL_ACCESS for the AWorksUtilities assembly. 6. Execute your ALTER ASSEMBLY statement, and confirm that no errors occur. 7. Under the Retest managed stored procedure comment, select the DECLARE, SET, and EXEC statements. Execute these statements, and confirm that no errors occur. 8. In Microsoft Windows Explorer, verify the existence of the Output.xml file in the D:LabfilesStarter folder. Double-click the file to display the XML in Microsoft Internet Explorer. Close Internet Explorer when you have confirmed that the file contains XML. Create the GetLongDate 1. Open the GetLongDate.sql query file. managed user-defined 2. Locate the Create managed user-defined function function referencing the comment, and then add code to create the external assembly. GetLongDate function in the AdventureWorks database, as described in the scenario. 3. Execute your CREATE FUNCTION statement, and confirm that no errors occur. 4. Locate the Test managed user-defined function comment, and then select the SELECT statement. Execute the statement, and confirm that records are displayed with a long OrderDate value.
  32. 32. 8–30 Module 8: Implementing Managed Code in the Database Task Supporting information Create the EmailChange 1. Open the EmailChange.sql query file. managed trigger on the 2. Under the Create trigger comment, add code to Person.Contact table create the EmailChange trigger on the referencing the external Person.Contact table in the AdventureWorks assembly. database, as described in the scenario. 3. Execute your CREATE TRIGGER statement, and confirm that no errors occur. 4. Under the Test trigger comment, select the first SELECT statement. Execute the statement, and then confirm that a message is displayed, noting the new e-mail address within the results pane. 5. Select the second SELECT statement. Execute the statement, and then confirm that there is no message because the statement did not update the e-mail address. This is because the managed code checks to see which columns were updated and performs the trigger logic only if the e-mail column is modified. Create the Concatenate 1. Open the Concatenate.sql query file. managed aggregate function 2. Under the Create aggregate function comment, referencing the external add code to create the Concatenate aggregate in assembly. the AdventureWorks database, as described in the scenario. 3. Execute your CREATE AGGREGATE statement, and confirm that no errors occur. 4. Under the Test aggregate function comment, select the SELECT statement. Execute the statement, and then confirm that orders are displayed as a concatenated string for each account. Create the IPAddress 1. Open the IPAddress.sql query file. managed user-defined type 2. Under the Create managed user-defined type referencing the external comment, add code to create the IPAddress type in assembly. the AdventureWorks database, as described in the scenario. 3. Execute your CREATE TYPE statement, and confirm that no errors occur. 4. Under the Test managed user-defined type comment, select the DECLARE, SET, and SELECT statements. Execute the statements, and then confirm that three result sets are displayed showing the IPAddress value in various forms. 5. Close SQL Server Management Studio, saving your changes if prompted.
  33. 33. Module 8: Implementing Managed Code in the Database 8–31Results checklist You can use the following checklist of results to verify whether you have successfully performed this lab: ■ Referenced the AWorksUtilities.dll assembly ■ Created and tested the SaveXML stored procedure ■ Created and tested the GetLongDate user-defined function ■ Created and tested the EmailChange trigger ■ Created and tested the Concatenate aggregate function ■ Created and tested the IPAddress user-defined type

×