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

Weitere ähnliche Inhalte

Was ist angesagt?

The 5 most common reasons for a slow WordPress site and how to fix them – ext...
The 5 most common reasons for a slow WordPress site and how to fix them – ext...The 5 most common reasons for a slow WordPress site and how to fix them – ext...
The 5 most common reasons for a slow WordPress site and how to fix them – ext...Otto Kekäläinen
 
High Performance Snippets
High Performance SnippetsHigh Performance Snippets
High Performance SnippetsSteve Souders
 
Intro to JavaScript Tooling in Visual Studio Code
Intro to JavaScript Tooling in Visual Studio CodeIntro to JavaScript Tooling in Visual Studio Code
Intro to JavaScript Tooling in Visual Studio CodeColdFusionConference
 
Web Cache Deception Attack
Web Cache Deception AttackWeb Cache Deception Attack
Web Cache Deception AttackOmer Gil
 
Testing Code.org's Interactive CS Curriculum
Testing Code.org's Interactive CS CurriculumTesting Code.org's Interactive CS Curriculum
Testing Code.org's Interactive CS CurriculumBrian Jordan
 
Behavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberBehavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberKMS Technology
 
How to make your Webpack builds 10x faster
How to make your Webpack builds 10x fasterHow to make your Webpack builds 10x faster
How to make your Webpack builds 10x fastertrueter
 
How I Learned to Stop Worrying and Backup WordPress
How I Learned to Stop Worrying and Backup WordPressHow I Learned to Stop Worrying and Backup WordPress
How I Learned to Stop Worrying and Backup WordPressChris Jean
 
Ci of js and apex using jasmine, phantom js and drone io df14
Ci of js and apex using jasmine, phantom js and drone io   df14Ci of js and apex using jasmine, phantom js and drone io   df14
Ci of js and apex using jasmine, phantom js and drone io df14Kevin Poorman
 
What’s New in ASP.NET 4
What’s New in ASP.NET 4What’s New in ASP.NET 4
What’s New in ASP.NET 4Todd Anglin
 
Modern Web Application Development Workflow - EclipseCon US 2014
Modern Web Application Development Workflow - EclipseCon US 2014Modern Web Application Development Workflow - EclipseCon US 2014
Modern Web Application Development Workflow - EclipseCon US 2014Stéphane Bégaudeau
 
An Introduction to GitHub for DBAs - Brent Ozar
An Introduction to GitHub for DBAs - Brent OzarAn Introduction to GitHub for DBAs - Brent Ozar
An Introduction to GitHub for DBAs - Brent OzarBrent Ozar
 
Nightwatch JS for End to End Tests
Nightwatch JS for End to End TestsNightwatch JS for End to End Tests
Nightwatch JS for End to End TestsSriram Angajala
 
Capybara testing
Capybara testingCapybara testing
Capybara testingFutureworkz
 
"Spring Boot. Boot up your development" Сергей Моренец
"Spring Boot. Boot up your development" Сергей Моренец"Spring Boot. Boot up your development" Сергей Моренец
"Spring Boot. Boot up your development" Сергей МоренецFwdays
 
Why you should switch to Cypress for modern web testing?
Why you should switch to Cypress for modern web testing?Why you should switch to Cypress for modern web testing?
Why you should switch to Cypress for modern web testing?Shivam Bharadwaj
 
10 practices that every developer needs to start right now
10 practices that every developer needs to start right now10 practices that every developer needs to start right now
10 practices that every developer needs to start right nowCaleb Jenkins
 
Web Performance Part 4 "Client-side performance"
Web Performance Part 4  "Client-side performance"Web Performance Part 4  "Client-side performance"
Web Performance Part 4 "Client-side performance"Binary Studio
 

Was ist angesagt? (20)

The 5 most common reasons for a slow WordPress site and how to fix them – ext...
The 5 most common reasons for a slow WordPress site and how to fix them – ext...The 5 most common reasons for a slow WordPress site and how to fix them – ext...
The 5 most common reasons for a slow WordPress site and how to fix them – ext...
 
High Performance Snippets
High Performance SnippetsHigh Performance Snippets
High Performance Snippets
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Intro to JavaScript Tooling in Visual Studio Code
Intro to JavaScript Tooling in Visual Studio CodeIntro to JavaScript Tooling in Visual Studio Code
Intro to JavaScript Tooling in Visual Studio Code
 
Web Cache Deception Attack
Web Cache Deception AttackWeb Cache Deception Attack
Web Cache Deception Attack
 
Testing Code.org's Interactive CS Curriculum
Testing Code.org's Interactive CS CurriculumTesting Code.org's Interactive CS Curriculum
Testing Code.org's Interactive CS Curriculum
 
Behavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberBehavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using Cucumber
 
How to make your Webpack builds 10x faster
How to make your Webpack builds 10x fasterHow to make your Webpack builds 10x faster
How to make your Webpack builds 10x faster
 
How I Learned to Stop Worrying and Backup WordPress
How I Learned to Stop Worrying and Backup WordPressHow I Learned to Stop Worrying and Backup WordPress
How I Learned to Stop Worrying and Backup WordPress
 
Ci of js and apex using jasmine, phantom js and drone io df14
Ci of js and apex using jasmine, phantom js and drone io   df14Ci of js and apex using jasmine, phantom js and drone io   df14
Ci of js and apex using jasmine, phantom js and drone io df14
 
What’s New in ASP.NET 4
What’s New in ASP.NET 4What’s New in ASP.NET 4
What’s New in ASP.NET 4
 
Modern Web Application Development Workflow - EclipseCon US 2014
Modern Web Application Development Workflow - EclipseCon US 2014Modern Web Application Development Workflow - EclipseCon US 2014
Modern Web Application Development Workflow - EclipseCon US 2014
 
An Introduction to GitHub for DBAs - Brent Ozar
An Introduction to GitHub for DBAs - Brent OzarAn Introduction to GitHub for DBAs - Brent Ozar
An Introduction to GitHub for DBAs - Brent Ozar
 
Nightwatch JS for End to End Tests
Nightwatch JS for End to End TestsNightwatch JS for End to End Tests
Nightwatch JS for End to End Tests
 
Capybara testing
Capybara testingCapybara testing
Capybara testing
 
"Spring Boot. Boot up your development" Сергей Моренец
"Spring Boot. Boot up your development" Сергей Моренец"Spring Boot. Boot up your development" Сергей Моренец
"Spring Boot. Boot up your development" Сергей Моренец
 
Protractor overview
Protractor overviewProtractor overview
Protractor overview
 
Why you should switch to Cypress for modern web testing?
Why you should switch to Cypress for modern web testing?Why you should switch to Cypress for modern web testing?
Why you should switch to Cypress for modern web testing?
 
10 practices that every developer needs to start right now
10 practices that every developer needs to start right now10 practices that every developer needs to start right now
10 practices that every developer needs to start right now
 
Web Performance Part 4 "Client-side performance"
Web Performance Part 4  "Client-side performance"Web Performance Part 4  "Client-side performance"
Web Performance Part 4 "Client-side performance"
 

Ähnlich wie SQL Server - CLR integration

SQLCLR For DBAs and Developers
SQLCLR For DBAs and DevelopersSQLCLR For DBAs and Developers
SQLCLR For DBAs and Developerswebhostingguy
 
Dr. Jekyll and Mr. Hyde
Dr. Jekyll and Mr. HydeDr. Jekyll and Mr. Hyde
Dr. Jekyll and Mr. Hydewebhostingguy
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integrationwebhostingguy
 
SDC - Programming the CLR in SQL Server 2005.ppt (1.51 MB)
SDC - Programming the CLR in SQL Server 2005.ppt (1.51 MB)SDC - Programming the CLR in SQL Server 2005.ppt (1.51 MB)
SDC - Programming the CLR in SQL Server 2005.ppt (1.51 MB)webhostingguy
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Netwebhostingguy
 
23 ijaprr vol1-3-25-31iqra
23 ijaprr vol1-3-25-31iqra23 ijaprr vol1-3-25-31iqra
23 ijaprr vol1-3-25-31iqraijaprr_editor
 
Ordina SOFTC Presentation - SQL CLR
Ordina SOFTC Presentation - SQL CLROrdina SOFTC Presentation - SQL CLR
Ordina SOFTC Presentation - SQL CLROrdina Belgium
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notesWE-IT TUTORIALS
 
Azure presentation nnug dec 2010
Azure presentation nnug  dec 2010Azure presentation nnug  dec 2010
Azure presentation nnug dec 2010Ethos Technologies
 
DotNet Introduction
DotNet IntroductionDotNet Introduction
DotNet IntroductionWei Sun
 
Runtime Environment Of .Net Divya Rathore
Runtime Environment Of .Net Divya RathoreRuntime Environment Of .Net Divya Rathore
Runtime Environment Of .Net Divya RathoreEsha Yadav
 
SQL Server 2008 Integration Services
SQL Server 2008 Integration ServicesSQL Server 2008 Integration Services
SQL Server 2008 Integration ServicesEduardo Castro
 
SQL Server Security - Attack
SQL Server Security - Attack SQL Server Security - Attack
SQL Server Security - Attack webhostingguy
 
Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02Wei Sun
 
New Features Of Microsoft Visual Studio 2008 And .Net Framework 3.5 To Comsof...
New Features Of Microsoft Visual Studio 2008 And .Net Framework 3.5 To Comsof...New Features Of Microsoft Visual Studio 2008 And .Net Framework 3.5 To Comsof...
New Features Of Microsoft Visual Studio 2008 And .Net Framework 3.5 To Comsof...Shahzad
 
System verilog important
System verilog importantSystem verilog important
System verilog importantelumalai7
 

Ähnlich wie SQL Server - CLR integration (20)

CLR Stored Procedures
CLR Stored ProceduresCLR Stored Procedures
CLR Stored Procedures
 
SQLCLR For DBAs and Developers
SQLCLR For DBAs and DevelopersSQLCLR For DBAs and Developers
SQLCLR For DBAs and Developers
 
Dr. Jekyll and Mr. Hyde
Dr. Jekyll and Mr. HydeDr. Jekyll and Mr. Hyde
Dr. Jekyll and Mr. Hyde
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integration
 
SDC - Programming the CLR in SQL Server 2005.ppt (1.51 MB)
SDC - Programming the CLR in SQL Server 2005.ppt (1.51 MB)SDC - Programming the CLR in SQL Server 2005.ppt (1.51 MB)
SDC - Programming the CLR in SQL Server 2005.ppt (1.51 MB)
 
SQLCLR Tips & Trics
SQLCLR Tips & TricsSQLCLR Tips & Trics
SQLCLR Tips & Trics
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
 
23 ijaprr vol1-3-25-31iqra
23 ijaprr vol1-3-25-31iqra23 ijaprr vol1-3-25-31iqra
23 ijaprr vol1-3-25-31iqra
 
Ordina SOFTC Presentation - SQL CLR
Ordina SOFTC Presentation - SQL CLROrdina SOFTC Presentation - SQL CLR
Ordina SOFTC Presentation - SQL CLR
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notes
 
Azure presentation nnug dec 2010
Azure presentation nnug  dec 2010Azure presentation nnug  dec 2010
Azure presentation nnug dec 2010
 
DotNet Introduction
DotNet IntroductionDotNet Introduction
DotNet Introduction
 
Runtime Environment Of .Net Divya Rathore
Runtime Environment Of .Net Divya RathoreRuntime Environment Of .Net Divya Rathore
Runtime Environment Of .Net Divya Rathore
 
SQL Server 2008 Integration Services
SQL Server 2008 Integration ServicesSQL Server 2008 Integration Services
SQL Server 2008 Integration Services
 
SQL Server Security - Attack
SQL Server Security - Attack SQL Server Security - Attack
SQL Server Security - Attack
 
.net Framework
.net Framework.net Framework
.net Framework
 
Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
New Features Of Microsoft Visual Studio 2008 And .Net Framework 3.5 To Comsof...
New Features Of Microsoft Visual Studio 2008 And .Net Framework 3.5 To Comsof...New Features Of Microsoft Visual Studio 2008 And .Net Framework 3.5 To Comsof...
New Features Of Microsoft Visual Studio 2008 And .Net Framework 3.5 To Comsof...
 
System verilog important
System verilog importantSystem verilog important
System verilog important
 

Mehr von Peter Gfader

Achieving Technical Excellence in Your Software Teams - from Devternity
Achieving Technical Excellence in Your Software Teams - from Devternity Achieving Technical Excellence in Your Software Teams - from Devternity
Achieving Technical Excellence in Your Software Teams - from Devternity Peter Gfader
 
You Can't Be Agile If Your Testing Practices Suck - Vilnius October 2019
You Can't Be Agile If Your Testing Practices Suck - Vilnius October 2019You Can't Be Agile If Your Testing Practices Suck - Vilnius October 2019
You Can't Be Agile If Your Testing Practices Suck - Vilnius October 2019Peter Gfader
 
You Cant Be Agile If Your Code Sucks (with 9 Tips For Dev Teams)
You Cant Be Agile If Your Code Sucks (with 9 Tips For Dev Teams)You Cant Be Agile If Your Code Sucks (with 9 Tips For Dev Teams)
You Cant Be Agile If Your Code Sucks (with 9 Tips For Dev Teams)Peter Gfader
 
How to make more impact as an engineer
How to make more impact as an engineerHow to make more impact as an engineer
How to make more impact as an engineerPeter Gfader
 
13 explosive things you should try as an agilist
13 explosive things you should try as an agilist13 explosive things you should try as an agilist
13 explosive things you should try as an agilistPeter Gfader
 
You cant be agile if your code sucks
You cant be agile if your code sucksYou cant be agile if your code sucks
You cant be agile if your code sucksPeter Gfader
 
Use Scrum and Continuous Delivery to innovate like crazy!
Use Scrum and Continuous Delivery to innovate like crazy!Use Scrum and Continuous Delivery to innovate like crazy!
Use Scrum and Continuous Delivery to innovate like crazy!Peter Gfader
 
Innovation durch Scrum und Continuous Delivery
Innovation durch Scrum und Continuous DeliveryInnovation durch Scrum und Continuous Delivery
Innovation durch Scrum und Continuous DeliveryPeter Gfader
 
Qcon london2012 recap
Qcon london2012 recapQcon london2012 recap
Qcon london2012 recapPeter Gfader
 
Continuous Delivery with TFS msbuild msdeploy
Continuous Delivery with TFS msbuild msdeployContinuous Delivery with TFS msbuild msdeploy
Continuous Delivery with TFS msbuild msdeployPeter Gfader
 
Silverlight vs HTML5 - Lessons learned from the real world...
Silverlight vs HTML5 - Lessons learned from the real world...Silverlight vs HTML5 - Lessons learned from the real world...
Silverlight vs HTML5 - Lessons learned from the real world...Peter Gfader
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code DevelopmentPeter Gfader
 
Data Mining with SQL Server 2008
Data Mining with SQL Server 2008Data Mining with SQL Server 2008
Data Mining with SQL Server 2008Peter Gfader
 
SSAS - Other Cube Browsers
SSAS - Other Cube BrowsersSSAS - Other Cube Browsers
SSAS - Other Cube BrowsersPeter Gfader
 
Reports with SQL Server Reporting Services
Reports with SQL Server Reporting ServicesReports with SQL Server Reporting Services
Reports with SQL Server Reporting ServicesPeter Gfader
 
OLAP – Creating Cubes with SQL Server Analysis Services
OLAP – Creating Cubes with SQL Server Analysis ServicesOLAP – Creating Cubes with SQL Server Analysis Services
OLAP – Creating Cubes with SQL Server Analysis ServicesPeter Gfader
 
Business Intelligence with SQL Server
Business Intelligence with SQL ServerBusiness Intelligence with SQL Server
Business Intelligence with SQL ServerPeter Gfader
 
SQL Server - Full text search
SQL Server - Full text searchSQL Server - Full text search
SQL Server - Full text searchPeter Gfader
 
Usability AJAX and other ASP.NET Features
Usability AJAX and other ASP.NET FeaturesUsability AJAX and other ASP.NET Features
Usability AJAX and other ASP.NET FeaturesPeter Gfader
 
Work with data in ASP.NET
Work with data in ASP.NETWork with data in ASP.NET
Work with data in ASP.NETPeter Gfader
 

Mehr von Peter Gfader (20)

Achieving Technical Excellence in Your Software Teams - from Devternity
Achieving Technical Excellence in Your Software Teams - from Devternity Achieving Technical Excellence in Your Software Teams - from Devternity
Achieving Technical Excellence in Your Software Teams - from Devternity
 
You Can't Be Agile If Your Testing Practices Suck - Vilnius October 2019
You Can't Be Agile If Your Testing Practices Suck - Vilnius October 2019You Can't Be Agile If Your Testing Practices Suck - Vilnius October 2019
You Can't Be Agile If Your Testing Practices Suck - Vilnius October 2019
 
You Cant Be Agile If Your Code Sucks (with 9 Tips For Dev Teams)
You Cant Be Agile If Your Code Sucks (with 9 Tips For Dev Teams)You Cant Be Agile If Your Code Sucks (with 9 Tips For Dev Teams)
You Cant Be Agile If Your Code Sucks (with 9 Tips For Dev Teams)
 
How to make more impact as an engineer
How to make more impact as an engineerHow to make more impact as an engineer
How to make more impact as an engineer
 
13 explosive things you should try as an agilist
13 explosive things you should try as an agilist13 explosive things you should try as an agilist
13 explosive things you should try as an agilist
 
You cant be agile if your code sucks
You cant be agile if your code sucksYou cant be agile if your code sucks
You cant be agile if your code sucks
 
Use Scrum and Continuous Delivery to innovate like crazy!
Use Scrum and Continuous Delivery to innovate like crazy!Use Scrum and Continuous Delivery to innovate like crazy!
Use Scrum and Continuous Delivery to innovate like crazy!
 
Innovation durch Scrum und Continuous Delivery
Innovation durch Scrum und Continuous DeliveryInnovation durch Scrum und Continuous Delivery
Innovation durch Scrum und Continuous Delivery
 
Qcon london2012 recap
Qcon london2012 recapQcon london2012 recap
Qcon london2012 recap
 
Continuous Delivery with TFS msbuild msdeploy
Continuous Delivery with TFS msbuild msdeployContinuous Delivery with TFS msbuild msdeploy
Continuous Delivery with TFS msbuild msdeploy
 
Silverlight vs HTML5 - Lessons learned from the real world...
Silverlight vs HTML5 - Lessons learned from the real world...Silverlight vs HTML5 - Lessons learned from the real world...
Silverlight vs HTML5 - Lessons learned from the real world...
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 
Data Mining with SQL Server 2008
Data Mining with SQL Server 2008Data Mining with SQL Server 2008
Data Mining with SQL Server 2008
 
SSAS - Other Cube Browsers
SSAS - Other Cube BrowsersSSAS - Other Cube Browsers
SSAS - Other Cube Browsers
 
Reports with SQL Server Reporting Services
Reports with SQL Server Reporting ServicesReports with SQL Server Reporting Services
Reports with SQL Server Reporting Services
 
OLAP – Creating Cubes with SQL Server Analysis Services
OLAP – Creating Cubes with SQL Server Analysis ServicesOLAP – Creating Cubes with SQL Server Analysis Services
OLAP – Creating Cubes with SQL Server Analysis Services
 
Business Intelligence with SQL Server
Business Intelligence with SQL ServerBusiness Intelligence with SQL Server
Business Intelligence with SQL Server
 
SQL Server - Full text search
SQL Server - Full text searchSQL Server - Full text search
SQL Server - Full text search
 
Usability AJAX and other ASP.NET Features
Usability AJAX and other ASP.NET FeaturesUsability AJAX and other ASP.NET Features
Usability AJAX and other ASP.NET Features
 
Work with data in ASP.NET
Work with data in ASP.NETWork with data in ASP.NET
Work with data in ASP.NET
 

SQL Server - CLR integration

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