Introduction to Threading in .Net


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Introduction to Threading in .Net

  1. 1. You Can Do Anything If You Think “Yukon” <ul><li>Presented by: </li></ul><ul><li>Richard Broida </li></ul><ul><li>Senior Architect </li></ul>
  2. 2. Agenda <ul><li>Overview of SQL Server 2005 </li></ul><ul><li>Enhancements to Database Engine and T-SQL </li></ul><ul><li>CLR Hosting </li></ul><ul><ul><li>Writing CLR functions, procedures and triggers </li></ul></ul><ul><ul><li>Creating user-defined data types and aggregates </li></ul></ul><ul><li>Resources </li></ul><ul><li>Q & A </li></ul>
  3. 3. History of Microsoft SQL Server <ul><li>1988 – MS/Sybase version for OS/2 </li></ul><ul><li>1993 – 4.21 for NT 3.1 </li></ul><ul><li>1994 – MS/Sybase partnership ends </li></ul><ul><li>1995 – 6.0, major rewrite </li></ul><ul><li>1996 – 6.5 </li></ul><ul><li>1997 – 6.5 Enterprise Edition </li></ul><ul><li>1998 – 7.0, total rewrite </li></ul><ul><li>2000 – 2000 </li></ul>
  4. 4. SQL Server 2000 Has Lived to See … <ul><li>Windows XP and Windows 2003 Server </li></ul><ul><li>.NET Framework 1.0 and 1.1 </li></ul><ul><li>BizTalk 2000, 2002 and 2004 </li></ul><ul><li>Commerce Server 2000 and 2002 </li></ul><ul><li>CMS 2000 and 2003 </li></ul><ul><li>SharePoint 2001 and 2003 </li></ul><ul><li>Exchange Server 2000 and 2003 </li></ul><ul><li>Oracle 9i and 10g </li></ul><ul><li>DB2 8.1 and 8.2 </li></ul>
  5. 5. New Features in SQL Server 2005 <ul><li>SQLCLR </li></ul><ul><li>XML as Native Data Type </li></ul><ul><li>Hosting Web Services </li></ul><ul><li>Enhancements to T-SQL </li></ul><ul><li>Client API Enhancements </li></ul><ul><li>Service Broker </li></ul><ul><li>Notification Services </li></ul><ul><li>Enhanced Reporting Services </li></ul><ul><li>Enhanced Analysis Services </li></ul>
  6. 6. SQL Server 2005 Editions <ul><li>Express Edition </li></ul><ul><ul><li>Replaces MSCE </li></ul></ul><ul><ul><li>Freely downloadable and redistributable </li></ul></ul><ul><li>Workgroup Edition </li></ul><ul><ul><li>Less expensive than Standard </li></ul></ul><ul><li>Standard Edition </li></ul><ul><li>Enterprise Edition </li></ul><ul><li>Developer Edition </li></ul>
  7. 7. Where is It Now? <ul><li>First Technology Preview released at PDC in October 2003 </li></ul><ul><li>Betas 1 and 2 Released in 2004 </li></ul><ul><li>Most current version on MSDN is February 2005 Community Technology Preview </li></ul><ul><li>A “Beta 3” was announced for April 2005 release, along with Beta 2 of Visual Studio 2005. Not out yet. </li></ul>
  8. 8. Big Disclaimer <ul><li>This presentation is based on the February 2005 Community Technology Previews of SQL Server 2005 and Visual Studio 2005. Anything and everything could change between now and the final release of these products. To the extent of such changes, the information in this presentation could end up wrong! </li></ul>
  9. 9. Beta/CTP Installation Tips <ul><li>Use a clean VM </li></ul><ul><ul><li>Or, completely remove old build before installing new one using Setup ToolsBuild Uninstall Wizardsqlbuw.exe in installation media </li></ul></ul><ul><li>Install SQL Server and Visual Studio on separate VMs </li></ul><ul><ul><li>They tend to have incompatible builds of the CLR </li></ul></ul><ul><li>Even on separate VMs, not all Yukon/Whidbey combinations work together. These do: </li></ul><ul><ul><li>Yukon Beta 1 with Whidbey Beta 1 </li></ul></ul><ul><ul><li>Yukon Dec CTP with Whidbey Oct CTP </li></ul></ul><ul><ul><li>Yukon Feb CTP with Whidbey Feb CTP </li></ul></ul>
  10. 10. Enhancements to the Database Engine and T-SQL
  11. 11. Does a SQL Server 2005 Programmer Need to Know T-SQL? <ul><li>Absolutely! </li></ul><ul><ul><li>SQLCLR relies on T-SQL for querying and updating the database </li></ul></ul><ul><ul><li>T-SQL is still the fastest and most powerful for what it does </li></ul></ul><ul><ul><li>New T-SQL enhancements reduce the situations where procedural code is necessary </li></ul></ul>
  12. 12. Enhancements to the Database Engine <ul><li>SNAPSHOT Isolation Level </li></ul><ul><ul><li>Uses versioning instead of locks, like that “Greek” database </li></ul></ul><ul><ul><li>Can provide better concurrency than traditional SERIALIZABLE and READ_COMMITTED </li></ul></ul><ul><li>Large Value Data Types </li></ul><ul><ul><li>VARCHAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX) can hold up to 2 31 bytes </li></ul></ul><ul><ul><li>Use instead of TEXT and IMAGE </li></ul></ul><ul><li>Statement-Level Recompilation for SPs </li></ul>
  13. 13. Enhancements to T-SQL <ul><li>TRY … CATCH Exception Handling </li></ul><ul><ul><li>With support for Transactions </li></ul></ul><ul><li>OUTPUT Command </li></ul><ul><ul><li>Use with INSERT, UPDATE and DELETE to save copies of the affected rows in a temporary table </li></ul></ul><ul><li>TOP Command </li></ul><ul><ul><li>Supported in INSERT, UPDATE and DELETE </li></ul></ul><ul><ul><li>Quantity can be a calculated value </li></ul></ul><ul><li>PIVOT command </li></ul><ul><ul><li>Rotates rows into columns and columns into rows </li></ul></ul>
  14. 14. Common Table Expressions <ul><li>The “WITH” Clause </li></ul><ul><ul><li>Creates a “virtual” table for use in a single query </li></ul></ul><ul><ul><li>Often provides a simpler syntax than using a VIEW or subquery, and may be easier for Optimizer to optimize </li></ul></ul><ul><ul><li>Allows recursive queries </li></ul></ul>
  15. 15. Simple WITH Clause <ul><li>WITH BigSales(RepID) AS </li></ul><ul><li>(SELECT RepId from Sales WHERE TotSales > 50000) </li></ul><ul><li>SELECT ‘Big Seller’, * FROM SalesReps </li></ul><ul><li>WHERE SalesReps.Id = BigSales.RepId </li></ul><ul><li>UNION </li></ul><ul><li>SELECT ‘Small Seller’, * FROM SalesReps </li></ul><ul><li>WHERE SalesReps.Id NOT IN </li></ul><ul><li>(SELECT RepId FROM BigSales) </li></ul>
  16. 16. Recursion Example: a “Linked List” Table: OrgChart <ul><li>ID Name ReportsTo </li></ul><ul><li>1 Dubya NULL </li></ul><ul><li>2 Bill 3 </li></ul><ul><li>3 Rama 1 </li></ul><ul><li>4 Sal 2 </li></ul><ul><li>5 Jane 3 </li></ul><ul><li>6 Shu 1 </li></ul>
  17. 17. Query: How Many Levels from the Top Are You? <ul><li>Levels From Top </li></ul><ul><li>Dubya 0 </li></ul><ul><li>Rama 1 </li></ul><ul><li>Shu 1 </li></ul><ul><li>Bill 2 </li></ul><ul><li>Jane 2 </li></ul><ul><li>Sal 3 </li></ul>
  18. 18. Performing the Query <ul><li>WITH LevelsDown (Id, Tot) AS </li></ul><ul><li>( </li></ul><ul><li>SELECT Id, 0 FROM OrgChart </li></ul><ul><li> WHERE ReportsTo is NULL </li></ul><ul><li>UNION ALL </li></ul><ul><li>SELECT OrgChart.Id, LevelsDown.Tot + 1 </li></ul><ul><li>FROM LevelsDown JOIN OrgChart </li></ul><ul><li> ON LevelsDown.Id = OrgChart.ReportsTo </li></ul><ul><li>) </li></ul><ul><li>SELECT Name, Tot </li></ul><ul><li>FROM OrgChart JOIN LevelsDown </li></ul><ul><li>ON OrgChart.ID = LevelsDown.Id </li></ul><ul><li>ORDER BY 2 </li></ul>
  19. 19. New Ranking Commands <ul><li>Require an OVER clause to specify the sorting order </li></ul><ul><li>ROW_NUMBER </li></ul><ul><ul><li>Inserts a column showing absolute position in the sort order </li></ul></ul><ul><li>RANK </li></ul><ul><ul><li>Assigns same value to all rows with same rank in the sort order </li></ul></ul><ul><li>DENSE_RANK </li></ul><ul><ul><li>Like RANK, but doesn’t leave “holes” </li></ul></ul><ul><li>NTILE </li></ul><ul><ul><li>Divides results into equal or near-equal divisions </li></ul></ul><ul><ul><li>Great for efficient paging in a DataGrid </li></ul></ul>
  20. 20. Adding Row Numbers to Query Output <ul><li>SELECT ROW_NUMBER() </li></ul><ul><li>OVER( ORDER BY L ast N ame) </li></ul><ul><li>AS RowNumber, </li></ul><ul><li>F irst N ame, L ast N ame </li></ul><ul><li>FROM P erson </li></ul>
  21. 21. Selecting the 78 th of 83 “Pages” of Data <ul><li>SELECT LastName, FirstName FROM </li></ul><ul><li>( </li></ul><ul><li>SELECT NTILE( 83 ) </li></ul><ul><li>OVER (ORDER BY LastName) </li></ul><ul><li>AS PageNo, </li></ul><ul><li>FirstName, LastName FROM Person </li></ul><ul><li>) AS TEMP </li></ul><ul><li>WHERE TEMP. PageNo = 78 </li></ul>
  22. 22. The SQLCLR
  23. 23. Overview of SQLCLR <ul><li>Write Procedures, Triggers and Functions in .NET languages to run in a CLR hosted by SQL Server </li></ul><ul><li>Use ADO.NET data access classes to run T-SQL commands inside the server </li></ul><ul><li>Create User-Defined Data Types that can be stored in database tables </li></ul><ul><li>Write Aggregate functions to operate on UDTs </li></ul>
  24. 24. Procedural Database Code before SQLCLR <ul><li>T-SQL </li></ul><ul><ul><li>Clumsy syntax </li></ul></ul><ul><ul><li>Slow when not dealing directly with the database </li></ul></ul><ul><ul><li>Syntax unfamiliar to many programmers </li></ul></ul><ul><li>Extended Stored Procedures </li></ul><ul><ul><li>Write an external DLL in C </li></ul></ul><ul><ul><li>Supported in SQL Server 2005, but likely to be deprecated </li></ul></ul><ul><ul><ul><li>Difficult to develop and test </li></ul></ul></ul><ul><ul><ul><li>Risky, because external DLL runs in SQL Server’s address space </li></ul></ul></ul><ul><ul><ul><ul><li>Memory leaks </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Database corruption </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Security holes </li></ul></ul></ul></ul><ul><li>External Code in Data Access, Business Logic and/or Presentation layers </li></ul>
  25. 25. Benefits of SQLCLR <ul><li>Write in your favorite .NET language </li></ul><ul><ul><li>Initially supports C#, VB.NET and C++ </li></ul></ul><ul><li>Use any .NET development tools </li></ul><ul><li>Use Framework Class Library or other libraries </li></ul><ul><li>Computation-intensive code executes faster than T-SQL </li></ul><ul><li>Stability and security of the CLR </li></ul><ul><li>Use native SQL security, Code Access Security, or both </li></ul>
  26. 26. What is a CLR Host? <ul><li>Host: Any process that loads the CLR </li></ul><ul><li>.NET Framework 1.x has three hosts: </li></ul><ul><ul><li>Command shell </li></ul></ul><ul><ul><li>IIS </li></ul></ul><ul><ul><li>Internet Explorer </li></ul></ul><ul><li>Can write other CLR hosts using the Hosting API </li></ul><ul><li>.NET Framework 2.0 expands the Hosting API to accommodate the needs of SQL Server </li></ul>
  27. 27. Requirements for Hosting in SQL Server <ul><li>To maximize performance, SQL Server manages its own memory and threads without help from the NT Kernel </li></ul><ul><ul><li>SQL Server understands internal memory needs better than NT Kernel; can use memory more efficiently with less paging </li></ul></ul><ul><ul><li>SQL Server uses cooperative multitasking to switch threads without kernel-mode context switching </li></ul></ul><ul><ul><ul><li>Or in “fiber mode”, SQL Server may use fibers instead of threads </li></ul></ul></ul><ul><ul><ul><ul><li>Requires multi-CPU machine </li></ul></ul></ul></ul>
  28. 28. How SQL Server Implements CLR Hosting <ul><li>SQLCLR memory management is handled by SQL Server, not NT Kernel </li></ul><ul><li>SQLCLR threads come from SQL Server thread pool and are cooperatively multitasked </li></ul><ul><ul><li>Or if SQL Server is in “fiber mode”, the CLR threads are actually fibers </li></ul></ul><ul><li>SQLCLR stores assemblies inside the database and loads them from there, not from the file system </li></ul>
  29. 29. Permission Sets Defined for SQLCLR Assemblies <ul><li>SAFE </li></ul><ul><ul><li>The default </li></ul></ul><ul><ul><li>Restrictions to assure the stability and security of SQL Server </li></ul></ul><ul><li>EXTERNAL_ACCESS </li></ul><ul><ul><li>Can access external data sources </li></ul></ul><ul><li>UNSAFE </li></ul><ul><ul><li>No restrictions, except those imposed by .NET Framework on all managed code </li></ul></ul><ul><ul><li>Similar risks as unmanaged External Stored Procedures </li></ul></ul>
  30. 30. SAFE Permission Set <ul><li>Prohibited to </li></ul><ul><ul><li>Create threads </li></ul></ul><ul><ul><li>Access external resources such file system, network, registry or environment variables </li></ul></ul><ul><ul><li>Connect to external databases </li></ul></ul><ul><ul><li>Call unmanaged code via PInvoke or RCWs </li></ul></ul><ul><ul><li>Call portions of the Framework Class Library not marked as safe for SQL Server </li></ul></ul><ul><ul><ul><li>E.g., System.Windows.Forms, System.Security, System.Reflection </li></ul></ul></ul>
  31. 31. EXTERNAL_ACCESS Permission Set <ul><li>Permitted to </li></ul><ul><ul><li>Access external resources such as file system, network, registry or environment variables </li></ul></ul><ul><ul><li>Connect to external databases </li></ul></ul><ul><li>Everything else prohibited same as SAFE </li></ul>
  32. 32. Some Consequences of SQL Server Hosting <ul><li>Static fields must be readonly </li></ul><ul><li>After try{}, a finally{} block is not guaranteed to be called </li></ul>
  33. 33. How to Install an Assembly in SQLCLR <ul><li>Create the Assembly outside SQL Server </li></ul><ul><ul><li>SQL Server itself comes with no tools to write or compile assemblies. Can use Visual Studio, Framework SDK, or other tools </li></ul></ul><ul><ul><li>SQL Server doesn’t need a Strong Name </li></ul></ul><ul><li>Enable SQLCLR on the server </li></ul><ul><li>Install Assembly in SQL Server with CREATE ASSEMBLY </li></ul><ul><li>Declare a procedure, function or trigger with CREATE [PROCEDURE|FUNCTION|TRIGGER] … EXTERNAL NAME … </li></ul>
  34. 34. Enabling SQLCLR on a Server <ul><li>CLR Execution is Disabled by Default </li></ul><ul><ul><li>To enable it, execute: </li></ul></ul><ul><ul><ul><li>Sp_configure ‘clr enabled’, 1 </li></ul></ul></ul><ul><ul><ul><li>RECONFIGURE </li></ul></ul></ul>
  35. 35. Installing An Assembly <ul><li>CREATE ASSEMBLY MyAssembly </li></ul><ul><li>FROM ‘C:ProjectsinMyAssembly.dll’ </li></ul><ul><li>WITH PERMISSION_SET = SAFE </li></ul><ul><li>ALTER ASSEMBLY MyAssembly </li></ul><ul><li>FROM ‘C:ProjectsinMyAssembly.dll’ </li></ul><ul><li>WITH PERMISSION_SET = SAFE </li></ul><ul><li>DROP ASSEMBLY MyAssembly </li></ul>
  36. 36. Making the Assembly Usable from T-SQL <ul><li>CREATE PROCEDURE MyProcedure </li></ul><ul><li>(@arg1 int, @arg2 varchar(20)) </li></ul><ul><li>EXTERNAL NAME MyAssembly.[MyNameSpace.MyClass]. </li></ul><ul><li>MyProcedure </li></ul><ul><li>CREATE FUNCTION MyFunction </li></ul><ul><li>(arg1 int) RETURNS int </li></ul><ul><li>EXTERNAL NAME MyAssembly.[MyNameSpace.MyClass]. </li></ul><ul><li>MyFunction </li></ul>
  37. 37. Viewing Assemblies in SQL Server’s Metadata <ul><li>To view metadata about assemblies installed in SQL Server </li></ul><ul><li>SELECT * FROM Sys.Assemblies </li></ul><ul><li>To view assembly code itself </li></ul><ul><li>SELECT * FROM Sys.Assembly_Files </li></ul><ul><li>To view procedures, functions and triggers defined from an assembly </li></ul><ul><li>SELECT * FROM Sys.Assembly_References </li></ul>
  38. 38. Demonstration Creating a SQLCLR Function with Notepad Viewing assembly metadata
  39. 39. SQL Database Projects in Visual Studio 2005 <ul><li>Allow quick creation of classes for Stored Procedures, Functions, Triggers, UDTs and Aggregates </li></ul><ul><li>One-click deployment of assembly into a database, no need to write T-SQL code </li></ul><ul><li>SQL Script provided to run while debugging </li></ul>
  40. 40. Debugging SQLCLR <ul><li>Visual Studio 2005 Interactive Debugger can step through SQLCLR code </li></ul><ul><ul><li>Must have Visual Studio Remote Debugging Monitor running on remote SQL Server </li></ul></ul><ul><li>Microsoft has announced intention to release a free stand alone debugger sometime after SQL Server 2005 ships </li></ul>
  41. 41. Creating SQLCLR Functions, Procedures and Triggers <ul><li>Must be a static method with one of </li></ul><ul><ul><li>[SqlFunctionAttribute] </li></ul></ul><ul><ul><li>[SqlProcedureAttribute] </li></ul></ul><ul><ul><li>[SqlTriggerAttribute] </li></ul></ul><ul><li>Can belong to a class or struct, whose name isn’t important </li></ul><ul><li>SQL doesn’t support overloading, so avoid overloaded method names </li></ul>
  42. 42. Using SQL Data Types in .NET <ul><li>SQL types don’t map perfectly to CTS types </li></ul><ul><ul><li>All SQL types can be NULL, but CTS value types can never be null </li></ul></ul><ul><ul><li>SQL decimal has a broader range of values than CTS Decimal </li></ul></ul><ul><ul><li>CTS Float and Double can hold the values Infinity and NAN, but SQL float and double cannot </li></ul></ul>
  43. 43. System.Data.SqlTypes <ul><li>System.Data.SqlTypes implements </li></ul><ul><li>SQL types in .NET </li></ul><ul><li>SqlTypes should be used for </li></ul><ul><ul><li>Parameters to functions and stored procedures </li></ul></ul><ul><ul><li>Return values from functions </li></ul></ul><ul><li>You can also use SqlTypes in code outside SQL Server </li></ul>
  44. 44. SqlType Examples <ul><li>CLR SQLType SQL </li></ul><ul><li>String SqlString (n)(var)char, </li></ul><ul><li>(n)text </li></ul><ul><li>Int32 SqlInt32 int </li></ul><ul><li>Double SqlDouble float </li></ul><ul><li>Boolean SqlBoolean bit </li></ul><ul><li>Byte[] SqlBinary (var)binary, </li></ul><ul><li>image, timestamp </li></ul><ul><li>DateTime SqlDateTime datetime </li></ul><ul><li>Guid SqlGuid uniqueidentifier </li></ul>
  45. 45. Operations on SqlTypes <ul><li>Numerical SqlTypes support unary and binary arithmetic operators (+,-,* etc) </li></ul><ul><li>SqlTypes have boolean IsNull property </li></ul><ul><ul><li>Use it instead of comparing a SqlType with CLR null </li></ul></ul><ul><li>SqlTypes support comparison operators (==,!=,<,> etc), but watch out for special rules when value = NULL </li></ul><ul><li>SqlTypes have static Null method to create an instance with value = NULL </li></ul><ul><li>SqlString has concatenation with + </li></ul>
  46. 46. Converting SqlType to CLR Type <ul><li>void foo( SqlInt32 sqlInt ) </li></ul><ul><li>{ </li></ul><ul><li>Int32 clrInt; </li></ul><ul><li>clrInt = sqlInt.Value; </li></ul><ul><li>// or </li></ul><ul><li>clrInt = (Int32)sqlInt; </li></ul><ul><li>// but next is error, no implicit conversion </li></ul><ul><li>clrInt = sqlInt; </li></ul><ul><li>} </li></ul>
  47. 47. Converting CLR Type to SqlType <ul><li>void foo( Int32 clrInt ) </li></ul><ul><li>{ </li></ul><ul><li>SqlInt32 mySqlInt; </li></ul><ul><li>mySqlInt = new SqlInt32(clrInt); </li></ul><ul><li>// or </li></ul><ul><li>mySqlInt.Value = clrInt; </li></ul><ul><li>// or </li></ul><ul><li>mySqlInt = (SqlInt)clrInt; </li></ul><ul><li>// ok, implicit conversion allowed this direction </li></ul><ul><li>mySqlInt = clrInt </li></ul><ul><li>} </li></ul>
  48. 48. Demonstration Creating a SQLCLR Function with Visual Studio 2005 Using SqlTypes
  49. 49. Accessing the Database from SQLCLR Code <ul><li>Database code written in T-SQL can issue SQL statements like SELECT, UPDATE and EXEC at any time </li></ul><ul><li>SQLCLR code must go through an ADO.NET data provider </li></ul>
  50. 50. The System.Data.SQLServer Provider (as of Feb 2005 CTP) <ul><li>System.Data.SqlServer provides data access classes for use (only) within SQLCLR </li></ul><ul><li>Connection objects aren’t needed </li></ul><ul><li>Static SqlContext methods create commands, DataAdapters, etc </li></ul><ul><li>In SAFE assembly, SQL Server won’t allow data access unless class has this attribute property: </li></ul><ul><li>DataAccess=DataAccessKind.Read </li></ul>
  51. 51. Changes Coming <ul><li>Microsoft announced that in next pre-release of SQL Server 2005, System.Data.SqlServer will merge into System.Data.SqlClient </li></ul><ul><li>To connect to the database from within SQLCLR, you will use a SQLConnection with this connection string: </li></ul><ul><li>“context connection=true” </li></ul>
  52. 52. Data Access Example (Feb CTP) <ul><li>SqlCommand comm = SqlContext.CreateCommand(); </li></ul><ul><li>comm.CommandText = “SELECT * </li></ul><ul><li>FROM MyTable”; </li></ul><ul><li>SqlDataReader reader = </li></ul><ul><li>comm.ExecuteReader(); </li></ul><ul><li>// use the reader … </li></ul>
  53. 53. Data Access Example (Coming Soon) <ul><li>SqlConnection conn = new SqlConnection(“context connection=true”) </li></ul><ul><li>SqlCommand comm = new SqlCommand() </li></ul><ul><li>comm.Connection = conn; </li></ul><ul><li>comm.CommandText = “…”; </li></ul><ul><li>conn.Open(); </li></ul><ul><li>// use the command … </li></ul>
  54. 54. Splitting the SqlCommand <ul><li>SQLDefinition – the parts of the command that don’t change in multiple invocations </li></ul><ul><li>SQLExecutionContext – the parts that do, such as the parameters </li></ul><ul><li>These can yield better performance than a single SqlCommand </li></ul>
  55. 55. SqlPipe <ul><li>Returns a TDS (tabular data set) stream to the client </li></ul><ul><li>Use to return the results of stored procedures to clients </li></ul><ul><li>SqlDataReader reader = </li></ul><ul><li>command.ExecuteReader(); </li></ul><ul><li>SqlPipe pipe = SqlContext.GetPipe(); </li></ul><ul><li>pipe.Send( reader ); </li></ul>
  56. 56. Demonstration Executing SELECT statement inside a SQLCLR Function Putting It Together: Selecting a Random Row from a Table
  57. 57. User-Defined Data Types and Aggregates
  58. 58. Is SQL Server 2005 an Object-Oriented Database? <ul><li>No </li></ul><ul><ul><li>Will not store any arbitrary CLR type in the database </li></ul></ul><ul><ul><li>Does not support inheritance or polymorphism </li></ul></ul><ul><li>It will store User-Defined Types, which emulate native SQL scalar types </li></ul><ul><li>Though created in .NET, UDTs behave more like SQL types than OOP types </li></ul>
  59. 59. What is a User-Defined Data Type? <ul><li>A UDT is a .NET Class or Struct that can function as a SQL scaler type </li></ul><ul><li>A scaler can be stored in a column of a table, or be the type of a variable </li></ul><ul><li>Examples of built-in scaler types </li></ul><ul><ul><li>INT </li></ul></ul><ul><ul><li>CHAR </li></ul></ul><ul><ul><li>DATETIME </li></ul></ul>
  60. 60. What Must a Scaler Be Able to Do? <ul><li>Mandatory </li></ul><ul><ul><li>Be serializable to/from a byte array </li></ul></ul><ul><ul><li>Be serializable to/from a string </li></ul></ul><ul><ul><li>Be able to equal NULL </li></ul></ul><ul><li>Optional, But Usually Necessary </li></ul><ul><ul><li>Support comparison operators (=,<,>, etc) </li></ul></ul><ul><ul><li>Support numerical operators (+,-,*,/ etc) </li></ul></ul><ul><ul><li>Support aggregation functions </li></ul></ul><ul><ul><li>Be indexable </li></ul></ul>
  61. 61. Creating a UDT <ul><li>Can be a Class or Struct </li></ul><ul><li>Must have [SqlUserDefinedAttribute] </li></ul><ul><li>Must implement INullable </li></ul><ul><li>Must override ToString() </li></ul><ul><li>Must have a static Parse() that converts a string to an instance of the UDT </li></ul>
  62. 62. Binary Serialization of UDTs <ul><li>Byte stream cannot exceed 8,000 bytes </li></ul><ul><li>If [SqlUserDefinedAttribute] is set to Format.Native, SQL Server will handle serialization </li></ul><ul><ul><li>All UDT fields must be “blittable” </li></ul></ul><ul><ul><ul><li>I.e., fields that are simple value types </li></ul></ul></ul><ul><ul><li>Sort order must be based on order of the binary fields </li></ul></ul><ul><li>Use Format.Native whenever possible </li></ul>
  63. 63. Format.Native Serialization <ul><li>[Serializable] </li></ul><ul><li>[SqlUserDefinedType </li></ul><ul><li>(Format = Format.Native, </li></ul><ul><li>IsByteOrdered = true)] </li></ul><ul><li>[StructLayout(LayoutKind = Sequential)] </li></ul><ul><li>struct MyUDT </li></ul><ul><li>{ … } </li></ul>
  64. 64. User-Defined Binary Serialization <ul><li>[Serializable] </li></ul><ul><li>[SqlUserDefinedType( </li></ul><ul><li>Format = Format.UserDefined, </li></ul><ul><li>IsByteOrdered = true, </li></ul><ul><li>IsFixedLength = true, </li></ul><ul><li>MaxByteSize = 17)] </li></ul><ul><li>struct MyUDT </li></ul><ul><li>{ … } </li></ul>
  65. 65. UDTs Outside the Database <ul><li>Clients outside the database will need UDT type information when they see a table with a UDT column, and they won’t get the info from SQL Server </li></ul><ul><li>You’ll need to deploy the UDT’s assembly in the client’s folder, in the GAC, or elsewhere in the probe path </li></ul><ul><li>This leads to possible version conflicts between assemblies in and out of database </li></ul>
  66. 66. What is an Aggregate? <ul><li>A class or struct whose methods implement a SQL aggregation function </li></ul><ul><li>The aggregation function can be applied in a T-SQL statement to a database column </li></ul><ul><li>Example: </li></ul><ul><li>SELECT MyAgg.Sum(MyTable.UDTCol) </li></ul><ul><li>FROM MyTable </li></ul>
  67. 67. Creating an Aggregate <ul><li>Class or struct must have [SerializableAttribute] </li></ul><ul><li>Class or struct must have [SqlUserDefinedAggregateAttribute] </li></ul><ul><li>Must provide four public methods: </li></ul><ul><ul><li>Init </li></ul></ul><ul><ul><li>Accumulate </li></ul></ul><ul><ul><li>Merge </li></ul></ul><ul><ul><li>Terminate </li></ul></ul>
  68. 68. Aggregate Attribute Properties <ul><li>IsInvariantToNulls </li></ul><ul><ul><li>The aggregate ignores null values. The optimizer can choose not to send nulls. </li></ul></ul><ul><li>IsInvariantToDuplicates </li></ul><ul><ul><li>The aggregate ignores duplicate values. The optimizer can choose not to send dupes. </li></ul></ul><ul><li>IsInvariantToOrder </li></ul><ul><ul><li>The result is unaffected by the order in which rows are processed. Optimizer can send them in any order </li></ul></ul><ul><li>IsNullEmpty </li></ul><ul><ul><li>Result is NULL if no rows are passed. Optimizer can choose not to create an aggregate at all. </li></ul></ul>
  69. 69. Demonstration Creating a 2D Point Data Type And a String Aggregator
  70. 70. Microsoft SQL Server Summit 2005 <ul><li>With Karen Delaney, author of Inside SQL Server 2000 and Inside SQL Server 2005 </li></ul><ul><ul><li>May 17, 2005 Park Center III 6050 Oak Tree Blvd, Suite 300 Independence, Ohio 44131 Event code: 1032271939 </li></ul></ul><ul><ul><li>To register call 1.877.673.8368 </li></ul></ul><ul><li>Free, but seating limited </li></ul>
  71. 71. Resources on the Web <ul><li>SQL Server 2005 Official Site </li></ul><ul><ul><li> </li></ul></ul><ul><li>SQLJunkies </li></ul><ul><ul><li> </li></ul></ul><ul><li>SQL Server 2005 Hands-On Labs Online </li></ul><ul><ul><li> </li></ul></ul>
  72. 72. Conclusion <ul><li>SQL Server 2005 confirms Microsoft’s ongoing commitment to the product </li></ul><ul><ul><li>Gets closer to parity with rival databases </li></ul></ul><ul><li>SQLCLR has compelling advantages in some situations </li></ul><ul><ul><li>Intensive computations in memory </li></ul></ul><ul><ul><li>Use of FCL library features </li></ul></ul><ul><li>In other situations, alternative designs, including T-SQL, may be better </li></ul>
  73. 73. Conclusion <ul><li>SQLCLR solutions require care to build and test </li></ul><ul><li>SQLCLR developers will need mastery of both SQL and CLR </li></ul>
  74. 74. Q & A