0
SQL Server 2008 for Developers<br />UTS Short Course<br />
Peter Gfader<br />Specializes in <br />C# and .NET (Java not anymore)<br />TestingAutomated tests<br />Agile, ScrumCertifi...
Course Website<br />Course Timetable & Materials<br />http://www.ssw.com.au/ssw/Events/2010UTSSQL/<br />Resources<br />htt...
Course Overview<br />
What we did last weekHigh availability<br />?<br />What can go wrong? What can we do?<br />Implementing Database Snapshots...
Homework?<br />
SQL CLR Integration<br />
Agenda - CLR Integration<br />What is .NET?<br />What is CLR Integration?<br />Requirements on SQL box<br />Samples<br />I...
What is .NET?<br />An application development platform from Microsoft<br />Tools, Languages, Runtime (Virtual machine), ID...
.NET Overview<br />IL = Intermediate Language<br />CLR = Runtime<br />
CLR<br />Common<br />Language<br />Runtime<br />= Virtual machine <br />
.NET Framework<br />Evolution<br />The whole .NET FX<br />http://shrinkster.com/1515(PDF Poster)<br />
What is CLR Integration?<br />Lets you write your database queries using .NET<br />Create and debug using VS 2008 IDE<br /...
SQL CLR Project<br />
CLR Integration<br />You can do the same thing as SQL Server using .NET code<br />Stored Procedures<br />Triggers<br />Use...
Server - Enabling CLR Integration<br />Enabled on an instance (not per database)<br />SQL Script<br />Execute sp_configure...
Stored Procedures<br />
public partial class StoredProcedures<br />{<br /> [Microsoft.SqlServer.Server.SqlProcedure]<br /> public static void Hell...
What you do<br />Enable CLR<br />Create a new database project in Visual Studio<br />Create a new stored procedure in Visu...
Internals<br />Assembly collated as set of files<br />Stored within SQL Server system tables <br />Assembly, references, p...
Security Levels<br />Safe (default)<br />Access only to CLR code. No access is allowed to external resources, thread manag...
Custom CLR Functions<br />
public partial class UserDefinedFunctions<br />{<br />    [Microsoft.SqlServer.Server.SqlFunction]<br />public static bool...
What you do<br />Create IsValidPostCode in C# (.NET)<br />Deploy it to SQL Server<br />Run it<br />
Stored procedure vs. Function<br />What is the difference?<br />Function <br />Base functionality<br />Independent of Data...
Triggers<br />
public partial class Triggers<br />{<br />    [Microsoft.SqlServer.Server.SqlTrigger(Name = "EmailTrigger", Target = "Cust...
What you do<br />Create EmailTrigger in C# (.NET)<br />Deploy it to SQL Server<br />Test it<br />
CLR Integration: Pros (Continued)<br />Take advantage of the powerful .NET Framework<br />.NET is a full-featured programm...
CLR Integration: Pros<br />For complex calculations<br />Parsing strings (like the regular expression code)<br />User-defi...
CLR Integration: Cons (Continued)<br />NON MAINSTREAM<br />Lots of programming for simple operations<br />Some overhead in...
CLR Integration: Cons<br />There are some restrictions to observe when calling between T-SQL and SQL-CLR.<br />You must on...
When to use CLR Integration<br />Do I need to manipulate data before it is displayed?<br />.NET code and SQLCLR<br />Do I ...
CLR Integration<br />The Bottom Line<br /><ul><li>Use T-SQL for all data operations
Use CLR assemblies for any complex calculations and transformations</li></li></ul><li>Quick tips<br />SQL Management Studi...
Session 4 Lab <br />CLR Integration<br />Download from Course Materials Site (to copy/paste scripts) or type manually:<br ...
3things…<br />PeterGfader@ssw.com.au<br />http://peitor.blogspot.com<br />twitter.com/peitor<br />
2 Things<br />PeterGfader@ssw.com.au<br />EricPhan@ssw.com.au<br />
Upcoming SlideShare
Loading in...5
×

SQL Server - CLR integration

2,530

Published on

How to write a stored procedure in C#. When to do it and when not to do it

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
2,530
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
70
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "SQL Server - CLR integration"

  1. 1. SQL Server 2008 for Developers<br />UTS Short Course<br />
  2. 2. Peter Gfader<br />Specializes in <br />C# and .NET (Java not anymore)<br />TestingAutomated tests<br />Agile, ScrumCertified Scrum Trainer<br />Technology aficionado <br />Silverlight<br />ASP.NET<br />Windows Forms<br />
  3. 3. Course Website<br />Course Timetable & Materials<br />http://www.ssw.com.au/ssw/Events/2010UTSSQL/<br />Resources<br />http://sharepoint.ssw.com.au/Training/UTSSQL/<br />
  4. 4. Course Overview<br />
  5. 5. What we did last weekHigh availability<br />?<br />What can go wrong? What can we do?<br />Implementing Database Snapshots<br />Configuring a Database Mirror<br />Partitioned Tables<br />SQL Agent Proxies<br />Performing Online Index Operations<br />Mirrored Backups<br />
  6. 6. Homework?<br />
  7. 7. SQL CLR Integration<br />
  8. 8. Agenda - CLR Integration<br />What is .NET?<br />What is CLR Integration?<br />Requirements on SQL box<br />Samples<br />Internals<br />CLR Integration: Pros<br />CLR Integration: Cons<br />Real world - When to use CLR Integration<br />
  9. 9. What is .NET?<br />An application development platform from Microsoft<br />Tools, Languages, Runtime (Virtual machine), IDE, …<br />Rapidly develop secure and robust software<br />Web and Windows<br />Full support for object-oriented programming<br />
  10. 10. .NET Overview<br />IL = Intermediate Language<br />CLR = Runtime<br />
  11. 11. CLR<br />Common<br />Language<br />Runtime<br />= Virtual machine <br />
  12. 12. .NET Framework<br />Evolution<br />The whole .NET FX<br />http://shrinkster.com/1515(PDF Poster)<br />
  13. 13. What is CLR Integration?<br />Lets you write your database queries using .NET<br />Create and debug using VS 2008 IDE<br />Brand new in SQL 2005 (Standard and Express)<br />Support for large UDT (User defined types) in SQL 2008 (up to 2GB)<br />Support for multiple inputs on UDA (User defined aggregators)<br />e.g. string concatenator that takes in a column and separator char<br />Any .NET language (C#, VB, C++)<br />
  14. 14.
  15. 15. SQL CLR Project<br />
  16. 16. CLR Integration<br />You can do the same thing as SQL Server using .NET code<br />Stored Procedures<br />Triggers<br />User-defined functions<br />User-defined types<br />Aggregate functions<br />
  17. 17. Server - Enabling CLR Integration<br />Enabled on an instance (not per database)<br />SQL Script<br />Execute sp_configure ‘clr enabled’, ‘1’<br />reconfigure<br />
  18. 18. Stored Procedures<br />
  19. 19. public partial class StoredProcedures<br />{<br /> [Microsoft.SqlServer.Server.SqlProcedure]<br /> public static void HelloWorld()<br /> {<br /> // Put your code here<br />using (SqlConnectioncn = new SqlConnection("Context Connection=true"))<br /> {<br />cn.Open();<br />SqlCommandcmd = new SqlCommand("SELECT * FROM DEMO", cn);<br />SqlContext.Pipe.Send(cmd.ExecuteReader());<br />}<br />}<br />Sample<br />
  20. 20. What you do<br />Enable CLR<br />Create a new database project in Visual Studio<br />Create a new stored procedure in Visual Studio<br />Connect to current context using “Context Connection=true”<br />Add a simple SELECT statement<br />Deploy and run it<br />
  21. 21. Internals<br />Assembly collated as set of files<br />Stored within SQL Server system tables <br />Assembly, references, program database (pdb), source files<br />Deployed to SQL Server<br />Manually<br />Catalogued with CREATE ASSEMBLY<br />Dropped with DROP ASSEMBLY<br />Automatically<br />Deployed from VS 2008<br />
  22. 22. Security Levels<br />Safe (default)<br />Access only to CLR code. No access is allowed to external resources, thread management, unsafe code or interop.<br />External_Access<br />Access is allowed to external systems, such as the EventLog, File System, and network. Still no access to unsafe code or interop code.<br />Unsafe<br />Access is not limited whatsoever. User-defined types<br />
  23. 23. Custom CLR Functions<br />
  24. 24. public partial class UserDefinedFunctions<br />{<br /> [Microsoft.SqlServer.Server.SqlFunction]<br />public static boolIsValidPostCode(string postcode)<br /> {<br /> return System.Text.RegularExpressions.Regex.IsMatch(<br /> postcode, ^(((2|8|9)d{2})|((02|08|09)d{2})|([1-9]d{3}))$");<br /> }<br />};<br />Sample<br />
  25. 25. What you do<br />Create IsValidPostCode in C# (.NET)<br />Deploy it to SQL Server<br />Run it<br />
  26. 26. Stored procedure vs. Function<br />What is the difference?<br />Function <br />Base functionality<br />Independent of Database itself<br />Stored procedure<br />Many operations at once<br />Normally database specific<br />
  27. 27. Triggers<br />
  28. 28. public partial class Triggers<br />{<br /> [Microsoft.SqlServer.Server.SqlTrigger(Name = "EmailTrigger", Target = "Customers", Event = "FOR UPDATE")]<br /> public static void SalaryFraudTrigger()<br /> { <br />SqlTriggerContext context = SqlContext.TriggerContext;<br /> using (SqlConnectioncnn = new SqlConnection("context connection=true"))<br /> {<br />cnn.Open();<br />SqlCommand command = cnn.CreateCommand();<br />command.CommandText = "SELECT * FROM inserted";<br />SqlDataReader reader = command.ExecuteReader();<br /> while (reader.Read())<br /> {<br /> for (intcolumnNumber = 0; columnNumber<context.ColumnCount; columnNumber++)<br /> {<br />SqlContext.Pipe.Send(string.Format("Col: {0} = {1}", columnNumber, reader[columnNumber].ToString()));<br /> } <br /> };<br />reader.Close();<br /> }<br /> }<br />}<br />Sample<br />
  29. 29. What you do<br />Create EmailTrigger in C# (.NET)<br />Deploy it to SQL Server<br />Test it<br />
  30. 30. CLR Integration: Pros (Continued)<br />Take advantage of the powerful .NET Framework<br />.NET is a full-featured programming language<br />Supports things like “for each” loops, arrays, collections<br />Object Oriented programming model to organise your queries<br />Obtaining data from external resources<br />The File System<br />The Event Log<br />A Web Service<br />The Registry<br />
  31. 31. CLR Integration: Pros<br />For complex calculations<br />Parsing strings (like the regular expression code)<br />User-defined types<br />Date, time, currency, and extended numeric types<br />Geospatial applications<br />Encoded or encrypted data (see books online)<br />User-defined aggregates<br />Powerful Intellisense and debugging<br />Generally faster<br />E.g. CLR aggregate 100x faster than cursor<br />
  32. 32. CLR Integration: Cons (Continued)<br />NON MAINSTREAM<br />Lots of programming for simple operations<br />Some overhead in communicating with assemblies<br />Remember – T-SQL is designed and optimised for data, use it!<br />Not useful if your guys do not know any .NET<br />Potentially costly to rewrite logic<br />Companies (including us) have invested a lot in T-SQL<br />
  33. 33. CLR Integration: Cons<br />There are some restrictions to observe when calling between T-SQL and SQL-CLR.<br />You must only use T-SQL supported data types (No streams)<br />You can't use inheritance or polymorphism<br />.NET cannot easily represent either VARCHAR or TIMESTAMP<br />.NET strings are Unicode, the equivalent of NVARCHAR<br />The CLR decimal type is not the same as SQL_DECIMAL<br />
  34. 34. When to use CLR Integration<br />Do I need to manipulate data before it is displayed?<br />.NET code and SQLCLR<br />Do I need to do set-based operations such as pivoting?<br />T-SQL <br />Do I need to do extensive computation or custom algorithms? <br />.NET code and SQLCLR<br />Are my developers SQL gurus but .NET newbies?<br />T-SQL<br />Do I have loads of stored procs that are becoming hard to manage?<br />.NET code and SQLCLR<br />
  35. 35. CLR Integration<br />The Bottom Line<br /><ul><li>Use T-SQL for all data operations
  36. 36. Use CLR assemblies for any complex calculations and transformations</li></li></ul><li>Quick tips<br />SQL Management Studio Shortcuts<br />Ctrl + L – Display query execution plan<br />F5 – Run/Show result grid<br />Rules for SQL Server<br />http://www.ssw.com.au/SSW/Standards/default.aspx<br />SQL Server Cheat sheet <br />http://www.pinaldave.com/sql-download/SQLServerCheatSheet.pdf<br />http://www.addedbytes.com/cheat-sheets/sql-server-cheat-sheet/<br />
  37. 37. Session 4 Lab <br />CLR Integration<br />Download from Course Materials Site (to copy/paste scripts) or type manually:<br />http://tinyurl.com/utssql2009<br />
  38. 38. 3things…<br />PeterGfader@ssw.com.au<br />http://peitor.blogspot.com<br />twitter.com/peitor<br />
  39. 39. 2 Things<br />PeterGfader@ssw.com.au<br />EricPhan@ssw.com.au<br />
  40. 40. Thank You!<br />Gateway Court Suite 10 81 - 91 Military Road Neutral Bay, Sydney NSW 2089 AUSTRALIA <br />ABN: 21 069 371 900 <br />Phone: + 61 2 9953 3000 Fax: + 61 2 9953 3105 <br />info@ssw.com.auwww.ssw.com.au <br />
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×