SlideShare a Scribd company logo
SQL Server™ .NET
Programmability

José A. Blakeley
Architect
SQL Server

Background
l

Transact SQL (T -SQL)
Ø
Ø

SQL Server’s database programming language
Includes:
§
§

l

SQL DDL, SQL DML
Variables, assignment, iteration, procedures, functions

.NET Platform
Ø

.NET runtime (Common Language Runtime)
§
§
§

Ø
Ø

Verifiable Intermediate Language
Managed memory – garbage collection
Multiple languages (e.g, C#, C++, Cobol)
(e.g ,

Frameworks library (e.g., GUI, Files, XML)
Assemblies – New Dynamic Link Libraries
§
§

Contain code + metadata (class definitions, assembly
dependencies)
Unit of code deployment, security, versioning

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

1
Outline
l
l

Motivation
Basic Infrastructure
Ø
Ø
Ø

l

SQL features
Ø
Ø
Ø

l

Hosting overview
Data access inside process: ADO.NET
SQL types
Server assemblies
Functions, procedures, triggers
Types and aggregates

Summary

Motivation
l

Broaden the set of languages for running
datadata -intensive business logic in server
Ø
Ø
Ø
Ø
Ø

l

Packaged as .NET assemblies
Ø

l

Verifiable, secure

Deployed to SQL Server as
Ø

l

IT Developers and ISVs
Multiple languages: Visual Basic ®, C#, C++, J#, …
Same mid - and server -tier data access model
midserverSame tools: IDE, project model, debugging, …
TransactTransact-SQL still supported

Functions, procedures, triggers, types

Basis for SQL Server Extensibility

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

2
Development Steps
VB, C#, C++

VS
Project

Build

Runtime
hosted inside
SQL Server

SQL Queries:
select
sum(tax(sal,state)
sum(tax(sal,state) )
from Emp where county
= ‘King’

Assembly:
“TaxLib.dll”
TaxLib.dll”

SQL Data Definition:
create assembly …
create function …
create procedure …
create trigger …
create type …

SQL Server

Basic Infrastructure
l

Hosting common language runtime
inside SQL Server
Ø
Ø
Ø

l

Data access in process
Ø
Ø

l

4Ss: Safety, security, scalability, speed
Run verified, type-safe code inside
typeprocess
Multiple languages
Based on ADO.NET
Same data access programming model
as middle -tier
middle-

SQLTypes
Ø

SQL type semantics in managed code

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

3
Hosting .NET Runtime
l

Safety
Ø

Prevent user code from corrupting the server
process
§

Ø

Use runtime code permissions to control user code
when calling
§

l

Verifiable code

Unmanaged APIs, user interface, threads, synchronization

Security
Ø
Ø
Ø

Authorized access to SQL Server data from user
code via SQL Server authorization model
Authorized access to system resources from user
code via runtime code permissions
Administrators control permissions given
to assemblies

Three Code Permission Sets
l

SAFE
Ø

Execute & data access permission

Ø

No access to resources outside SQL Server
No unmanaged calls
Must be verifiable

Ø
Ø

l

EXTERNAL_ACCESS
Ø
Ø
Ø
Ø

l

SAFESQL + access to external resources (Net, File
permissions)
Requires EXTERNAL ACCESS permission to create
SQL Server will impersonate the caller
Must be verifiable

UNRESTRICTED
Ø
Ø

No controls: Can call unmanged code, can be un-verifiable
unOnly Administrators can create

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

4
Hosting .NET Runtime
l

Scalability
As many concurrent users as, as fast as
TransactTransact-SQL

Ø

§

Integrated SQL Server and runtime threads

§

Collaboration between SQL Server and GC
SQL Server becomes OS to the .NET runtime

§

l

Speed
Efficient data access in process
Compiled user code, not interpreted as
TransactTransact-SQL
Fast transitions in/out of runtime

Ø
Ø
Ø

Speed: Functions
.NET function vs. Transact-SQL inline

600

.NET function vs. Transact-SQL function

400
200

1000000

0
1

3

5

7

9

Query time (ms)

Query time (ms)

800

100000

10000
11 1 3 15 17 19 21
1000
Integer ops per func call
100
.NET func

23

25 27

29

10 TSQL inline
1
100

1000

10000

Integer ops per call

.NET functions approximating speed of TransactTransact.NET func
TSQL func
SQL inline expressions
.NET framework functions much faster than
TransactTransact-SQL functions for complex expressions

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

5
Outline
l
l

Motivation
Basic Infrastructure
Ø
Ø
Ø

l

SQL features
Ø
Ø
Ø

l

Hosting overview
Data access inside process: ADO.NET
SQL types
Server assemblies
Functions, procedures, triggers
Types and aggregates

Summary

ADO .NET Data Access
Controls,
Designers,
etc

XSL/T, X -Path,
XValidation, etc

XmlDataXmlDataDocument

XmlReader
XmlText- XmlNodeXmlText- XmlNode Reader
Reader

DataSet
Sync

SQL Server
Managed
Managed
Managed
Provider
Provider

Provider

XmlReader
XmlText- XmlNodeXmlText- XmlNode Reader
Reader

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

6
Data Access Inside SQL
using System.Data.SqlServer;
System.Data.SqlServer;
using System.Data.SqlTypes;
System.Data.SqlTypes;
public class ShippingCosts {
public static SqlMoney FreightByShipper( string ship ) {
FreightByShipper(
SqlCommand cmd = SqlContext.GetCommand( );
SqlContext.GetCommand(
cmd.CommandText = "select sum(o.freight) as freight " +
"from orders o join shippers s on o.shipvia = s.shipperid " +
"where s.companyname = @CompanyName " ;
@CompanyName
SqlParameter param = cmd.Parameters.Add("@CompanyName",
cmd.Parameters.Add("@CompanyName",
SqlDbType.NVarChar,
SqlDbType.NVarChar, COMPANY_NAME_COL_LENGTH);
param.Value = ship;
ship;
SqlMoney amount = cmd.ExecuteScalar( );
cmd.ExecuteScalar(
return amount;
}
}

SQL Types
l
l
l

Reduce impedance mismatch between
programming language and data
Consistent expression evaluation in
midmid- and server-tier programming
serverSQL Types library
Ø
Ø

Managed classes: System.Data.SqlTypes
Provide SQL semantics
§
§

Nullability, threeNullability , three-valued logic
Precision and scale in operations

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

7
SQL Types Example
Tax function using SQL types

l

using System;
using System.Data.SQLTypes
;
public class myFinances
{
public static SQLDouble tax( SQLDouble sal )
{
if ( sal < 50000.0 ) return sal * 0.15;
0.15;
if ( sal >= 50000.0 && sal <= 90000.0 ) return sal * 0.23
else return sal * 0.35;
0.35;
}
}

SQLDouble makes function NULL-aware
NULL-

Outline
l
l

Motivation
Basic Infrastructure
Ø
Ø
Ø

l

SQL features
Ø
Ø
Ø

l

Hosting overview
Data access inside process: ADO.NET
SQL types
Server assemblies
Functions, procedures, triggers
Types and aggregates

Summary

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

8
SQL Features
Assemblies
Functions
Procedures
Triggers
Types

l
l
l
l
l

Creating An Assembly
CREATE ASSEMBLY geom FROM ‘m1typesgeometry.dll’
‘ m1types
WITH PERMISSION_SET = SAFE
WITH AUTOREGISTER
DROP ASSEMBLY lib_geom
l

Assemblies stored in database
Ø

l

Ø

l

Safe (default), external access, unrestricted

Autoregister functions
Ø

l

Backup, restore with data

Code permissions assigned per assembly

Using .NET custom attributes

Assembly benefits
Ø
Ø

SelfSelf-describing metadata: Types, file dependencies
Unit of code deployment: Permissions, versioning

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

9
Altering An Assembly
l
l

Cannot invalidate persistent data or indexes
Implies
Ø
Ø

l
l

No tables with columns of UDT from this assembly
No indexes on functions of this assembly

Force option allows ALTER even if persistent
dependencies exist
Packaging considerations
Ø

Place routines and types in different assemblies

Creating A Function
CREATE FUNCTION distance (
@x1 int, @y1 int, @x2 int, @y2 int ) RETURNS float
int,
int,
int,
EXTERNAL NAME ‘geom:CPoint.Distance’
‘geom:CPoint.Distance’
DETERMINISTIC
RETURNS NULL ON NULL INPUT
DROP FUNCTION distance
l

Functions called from queries
Ø
Ø
Ø

l

Can be scalar or table -valued
Static class functions
Deterministic functions

Using a function in a query
SELECT s.name FROM Supplier s
WHERE dbo.distance ( s.x, s.y, @x, @y ) < 3
dbo.distance(

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

10
Creating A Procedure
CREATE PROCEDURE check_inventory
EXTERNAL NAME ‘events:CInventory.check_level’
‘events:CInventory.check_level’
DROP PROCEDURE check_inventory
l

Procedures not called from queries
Ø
Ø

Can contain SQL queries, updates or DDL
Can return results directly to client

Creating A Trigger
CREATE TRIGGER supplier_event ON supplier
AFTER INSERT, UPDATE
EXTERNAL NAME ‘events:CNotif.Supp_Event’
‘events:CNotif.Supp_Event’
DROP TRIGGER supplier_event
l
l

Similar to procedures, plus
Access to inserted, deleted tables

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

11
Creating A Type
l

Create or drop a type
CREATE TYPE Point
EXTERNAL NAME ‘geom:Point’
‘geom:Point’
DROP TYPE Point

l

Using a type
CREATE TABLE Supplier (
id
INTEGER PRIMARY KEY,
name
VARCHAR(20),
location
Point )

l

Using a type method in a query
SELECT s.name FROM Supplier s
WHERE s.location::distance( @point ) < 3

Query Optimization
l

Automatically gather function statistics
Ø

l

Reorder of predicate evaluation
Ø

l

Based on execution cost and statistics

Function indexes
Ø
Ø

l

Value histograms, execution cost

Speed up expensive functions
Extends computed column indexes
and index views

Implied and residual predicates

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

12
Summary
Richer server programming model

l

Ø
Ø
Ø

Any .NET framework language
Same mid - and server -tier data access:
midserverADO. NET
Same IDE, project model, debugging, tools

SQL Server hosting of .NET runtime

l

Ø

Safety, security, scalability, speed

SQL Server .NET features

l

Ø

Functions, stored procedures, triggers,
types, aggregates

Demos
l
l

Sample code for function, stored procedure, and type
Assemblies
Ø

l

Functions and stored procedures
Ø
Ø

l

Safe versus external access
Creation and execution
Data access in-process via ADO .NET
in-

Types
Ø
Ø
Ø
Ø
Ø

Type contract
Create type
Create table with column of user-defined type
userCreate index on column of user-defined type
userInsert and query the table

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

13
© 2001 Microsoft Corporation. All rights reserved.

PDC 2001
October 22-26, 2001
© 2001 Microsoft Corporation. All rights reserved.

14

More Related Content

PDF
Ice mini guide
PPTX
Shrug2017 arcpy data_and_you
PDF
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
PPTX
Jafka guide
PPTX
Unit test candidate solutions
PDF
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?
PPTX
Apache Cassandra, part 3 – machinery, work with Cassandra
Ice mini guide
Shrug2017 arcpy data_and_you
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
Jafka guide
Unit test candidate solutions
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?
Apache Cassandra, part 3 – machinery, work with Cassandra

What's hot (20)

PPT
Scaling web applications with cassandra presentation
PPT
Cassandra NoSQL
DOC
Ad java prac sol set
PPTX
Apache cassandra - future without boundaries (part3)
PDF
In-depth caching in Varnish - GOG Varnish Meetup, march 2019
PDF
Devtools cheatsheet
PDF
Scala4sling
 
PDF
Dependency Injection
PDF
Kamaelia Protocol Walkthrough
ZIP
Above the clouds: introducing Akka
PPT
Sqlapi0.1
PDF
Lambda Jam 2015: Event Processing in Clojure
PDF
Store and Process Big Data with Hadoop and Cassandra
ODP
Introduction to Apache Kafka- Part 2
PDF
Paris Cassandra Meetup - Cassandra for Developers
PDF
Rstudio ide-cheatsheet
PDF
Dynamic websites lec3
PDF
PDF
NYC* Tech Day - New Cassandra Drivers in Depth
PDF
03 2017Emea_RoadshowMilan-WhatsNew-Mariadbserver10_2andmaxscale 2_1
Scaling web applications with cassandra presentation
Cassandra NoSQL
Ad java prac sol set
Apache cassandra - future without boundaries (part3)
In-depth caching in Varnish - GOG Varnish Meetup, march 2019
Devtools cheatsheet
Scala4sling
 
Dependency Injection
Kamaelia Protocol Walkthrough
Above the clouds: introducing Akka
Sqlapi0.1
Lambda Jam 2015: Event Processing in Clojure
Store and Process Big Data with Hadoop and Cassandra
Introduction to Apache Kafka- Part 2
Paris Cassandra Meetup - Cassandra for Developers
Rstudio ide-cheatsheet
Dynamic websites lec3
NYC* Tech Day - New Cassandra Drivers in Depth
03 2017Emea_RoadshowMilan-WhatsNew-Mariadbserver10_2andmaxscale 2_1
Ad

Viewers also liked (12)

PPTX
Task 2 analysis of nme music magazine
DOC
Teste 1º. 10ºe. 29 outubro 2010
PDF
Trt civil 02 (1)
PDF
Trt português 02
PDF
Trt previdenciário (1)
PDF
الشهادات٣
PPTX
YO, MI CULTURA, MI REGIÓN
DOCX
Leccion 5 tablas numericas con ceros fep rene
DOCX
Trabajo sobre edificios en word
DOCX
Rúbrica
DOCX
El derecho de autor
PPT
Comparatives nice two
Task 2 analysis of nme music magazine
Teste 1º. 10ºe. 29 outubro 2010
Trt civil 02 (1)
Trt português 02
Trt previdenciário (1)
الشهادات٣
YO, MI CULTURA, MI REGIÓN
Leccion 5 tablas numericas con ceros fep rene
Trabajo sobre edificios en word
Rúbrica
El derecho de autor
Comparatives nice two
Ad

Similar to Sql Server - Apresentação (20)

PDF
SQL Server SQL Server
PDF
SQL Server SQL Server
PPT
SQL Server 2005 CLR Integration
PPT
Sql Summit Clr, Service Broker And Xml
PDF
SQL-Server Database.pdf
PPT
SQL Server 2008 for Developers
PPTX
SQL Server Workshop for Developers - Visual Studio Live! NY 2012
PPS
11 qmds2005 session16
PPT
Introduction to Threading in .Net
PPT
SQL Server 2008 Overview
PPT
What's New for Developers in SQL Server 2008?
PPTX
6232 b 01
PPT
ordbms.ppt
PPT
Sql Server 2000
PPTX
SQL Server - CLR integration
PPTX
PDF
23 ijaprr vol1-3-25-31iqra
PPT
SQL Server 2008 for .NET Developers
SQL Server SQL Server
SQL Server SQL Server
SQL Server 2005 CLR Integration
Sql Summit Clr, Service Broker And Xml
SQL-Server Database.pdf
SQL Server 2008 for Developers
SQL Server Workshop for Developers - Visual Studio Live! NY 2012
11 qmds2005 session16
Introduction to Threading in .Net
SQL Server 2008 Overview
What's New for Developers in SQL Server 2008?
6232 b 01
ordbms.ppt
Sql Server 2000
SQL Server - CLR integration
23 ijaprr vol1-3-25-31iqra
SQL Server 2008 for .NET Developers

Recently uploaded (20)

PPTX
A Presentation on Artificial Intelligence
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Big Data Technologies - Introduction.pptx
PDF
cuic standard and advanced reporting.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Approach and Philosophy of On baking technology
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
A Presentation on Artificial Intelligence
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Per capita expenditure prediction using model stacking based on satellite ima...
Big Data Technologies - Introduction.pptx
cuic standard and advanced reporting.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Approach and Philosophy of On baking technology
Digital-Transformation-Roadmap-for-Companies.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Chapter 3 Spatial Domain Image Processing.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
NewMind AI Monthly Chronicles - July 2025
Advanced methodologies resolving dimensionality complications for autism neur...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Sql Server - Apresentação

  • 1. SQL Server™ .NET Programmability José A. Blakeley Architect SQL Server Background l Transact SQL (T -SQL) Ø Ø SQL Server’s database programming language Includes: § § l SQL DDL, SQL DML Variables, assignment, iteration, procedures, functions .NET Platform Ø .NET runtime (Common Language Runtime) § § § Ø Ø Verifiable Intermediate Language Managed memory – garbage collection Multiple languages (e.g, C#, C++, Cobol) (e.g , Frameworks library (e.g., GUI, Files, XML) Assemblies – New Dynamic Link Libraries § § Contain code + metadata (class definitions, assembly dependencies) Unit of code deployment, security, versioning PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 1
  • 2. Outline l l Motivation Basic Infrastructure Ø Ø Ø l SQL features Ø Ø Ø l Hosting overview Data access inside process: ADO.NET SQL types Server assemblies Functions, procedures, triggers Types and aggregates Summary Motivation l Broaden the set of languages for running datadata -intensive business logic in server Ø Ø Ø Ø Ø l Packaged as .NET assemblies Ø l Verifiable, secure Deployed to SQL Server as Ø l IT Developers and ISVs Multiple languages: Visual Basic ®, C#, C++, J#, … Same mid - and server -tier data access model midserverSame tools: IDE, project model, debugging, … TransactTransact-SQL still supported Functions, procedures, triggers, types Basis for SQL Server Extensibility PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 2
  • 3. Development Steps VB, C#, C++ VS Project Build Runtime hosted inside SQL Server SQL Queries: select sum(tax(sal,state) sum(tax(sal,state) ) from Emp where county = ‘King’ Assembly: “TaxLib.dll” TaxLib.dll” SQL Data Definition: create assembly … create function … create procedure … create trigger … create type … SQL Server Basic Infrastructure l Hosting common language runtime inside SQL Server Ø Ø Ø l Data access in process Ø Ø l 4Ss: Safety, security, scalability, speed Run verified, type-safe code inside typeprocess Multiple languages Based on ADO.NET Same data access programming model as middle -tier middle- SQLTypes Ø SQL type semantics in managed code PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 3
  • 4. Hosting .NET Runtime l Safety Ø Prevent user code from corrupting the server process § Ø Use runtime code permissions to control user code when calling § l Verifiable code Unmanaged APIs, user interface, threads, synchronization Security Ø Ø Ø Authorized access to SQL Server data from user code via SQL Server authorization model Authorized access to system resources from user code via runtime code permissions Administrators control permissions given to assemblies Three Code Permission Sets l SAFE Ø Execute & data access permission Ø No access to resources outside SQL Server No unmanaged calls Must be verifiable Ø Ø l EXTERNAL_ACCESS Ø Ø Ø Ø l SAFESQL + access to external resources (Net, File permissions) Requires EXTERNAL ACCESS permission to create SQL Server will impersonate the caller Must be verifiable UNRESTRICTED Ø Ø No controls: Can call unmanged code, can be un-verifiable unOnly Administrators can create PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 4
  • 5. Hosting .NET Runtime l Scalability As many concurrent users as, as fast as TransactTransact-SQL Ø § Integrated SQL Server and runtime threads § Collaboration between SQL Server and GC SQL Server becomes OS to the .NET runtime § l Speed Efficient data access in process Compiled user code, not interpreted as TransactTransact-SQL Fast transitions in/out of runtime Ø Ø Ø Speed: Functions .NET function vs. Transact-SQL inline 600 .NET function vs. Transact-SQL function 400 200 1000000 0 1 3 5 7 9 Query time (ms) Query time (ms) 800 100000 10000 11 1 3 15 17 19 21 1000 Integer ops per func call 100 .NET func 23 25 27 29 10 TSQL inline 1 100 1000 10000 Integer ops per call .NET functions approximating speed of TransactTransact.NET func TSQL func SQL inline expressions .NET framework functions much faster than TransactTransact-SQL functions for complex expressions PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 5
  • 6. Outline l l Motivation Basic Infrastructure Ø Ø Ø l SQL features Ø Ø Ø l Hosting overview Data access inside process: ADO.NET SQL types Server assemblies Functions, procedures, triggers Types and aggregates Summary ADO .NET Data Access Controls, Designers, etc XSL/T, X -Path, XValidation, etc XmlDataXmlDataDocument XmlReader XmlText- XmlNodeXmlText- XmlNode Reader Reader DataSet Sync SQL Server Managed Managed Managed Provider Provider Provider XmlReader XmlText- XmlNodeXmlText- XmlNode Reader Reader PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 6
  • 7. Data Access Inside SQL using System.Data.SqlServer; System.Data.SqlServer; using System.Data.SqlTypes; System.Data.SqlTypes; public class ShippingCosts { public static SqlMoney FreightByShipper( string ship ) { FreightByShipper( SqlCommand cmd = SqlContext.GetCommand( ); SqlContext.GetCommand( cmd.CommandText = "select sum(o.freight) as freight " + "from orders o join shippers s on o.shipvia = s.shipperid " + "where s.companyname = @CompanyName " ; @CompanyName SqlParameter param = cmd.Parameters.Add("@CompanyName", cmd.Parameters.Add("@CompanyName", SqlDbType.NVarChar, SqlDbType.NVarChar, COMPANY_NAME_COL_LENGTH); param.Value = ship; ship; SqlMoney amount = cmd.ExecuteScalar( ); cmd.ExecuteScalar( return amount; } } SQL Types l l l Reduce impedance mismatch between programming language and data Consistent expression evaluation in midmid- and server-tier programming serverSQL Types library Ø Ø Managed classes: System.Data.SqlTypes Provide SQL semantics § § Nullability, threeNullability , three-valued logic Precision and scale in operations PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 7
  • 8. SQL Types Example Tax function using SQL types l using System; using System.Data.SQLTypes ; public class myFinances { public static SQLDouble tax( SQLDouble sal ) { if ( sal < 50000.0 ) return sal * 0.15; 0.15; if ( sal >= 50000.0 && sal <= 90000.0 ) return sal * 0.23 else return sal * 0.35; 0.35; } } SQLDouble makes function NULL-aware NULL- Outline l l Motivation Basic Infrastructure Ø Ø Ø l SQL features Ø Ø Ø l Hosting overview Data access inside process: ADO.NET SQL types Server assemblies Functions, procedures, triggers Types and aggregates Summary PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 8
  • 9. SQL Features Assemblies Functions Procedures Triggers Types l l l l l Creating An Assembly CREATE ASSEMBLY geom FROM ‘m1typesgeometry.dll’ ‘ m1types WITH PERMISSION_SET = SAFE WITH AUTOREGISTER DROP ASSEMBLY lib_geom l Assemblies stored in database Ø l Ø l Safe (default), external access, unrestricted Autoregister functions Ø l Backup, restore with data Code permissions assigned per assembly Using .NET custom attributes Assembly benefits Ø Ø SelfSelf-describing metadata: Types, file dependencies Unit of code deployment: Permissions, versioning PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 9
  • 10. Altering An Assembly l l Cannot invalidate persistent data or indexes Implies Ø Ø l l No tables with columns of UDT from this assembly No indexes on functions of this assembly Force option allows ALTER even if persistent dependencies exist Packaging considerations Ø Place routines and types in different assemblies Creating A Function CREATE FUNCTION distance ( @x1 int, @y1 int, @x2 int, @y2 int ) RETURNS float int, int, int, EXTERNAL NAME ‘geom:CPoint.Distance’ ‘geom:CPoint.Distance’ DETERMINISTIC RETURNS NULL ON NULL INPUT DROP FUNCTION distance l Functions called from queries Ø Ø Ø l Can be scalar or table -valued Static class functions Deterministic functions Using a function in a query SELECT s.name FROM Supplier s WHERE dbo.distance ( s.x, s.y, @x, @y ) < 3 dbo.distance( PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 10
  • 11. Creating A Procedure CREATE PROCEDURE check_inventory EXTERNAL NAME ‘events:CInventory.check_level’ ‘events:CInventory.check_level’ DROP PROCEDURE check_inventory l Procedures not called from queries Ø Ø Can contain SQL queries, updates or DDL Can return results directly to client Creating A Trigger CREATE TRIGGER supplier_event ON supplier AFTER INSERT, UPDATE EXTERNAL NAME ‘events:CNotif.Supp_Event’ ‘events:CNotif.Supp_Event’ DROP TRIGGER supplier_event l l Similar to procedures, plus Access to inserted, deleted tables PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 11
  • 12. Creating A Type l Create or drop a type CREATE TYPE Point EXTERNAL NAME ‘geom:Point’ ‘geom:Point’ DROP TYPE Point l Using a type CREATE TABLE Supplier ( id INTEGER PRIMARY KEY, name VARCHAR(20), location Point ) l Using a type method in a query SELECT s.name FROM Supplier s WHERE s.location::distance( @point ) < 3 Query Optimization l Automatically gather function statistics Ø l Reorder of predicate evaluation Ø l Based on execution cost and statistics Function indexes Ø Ø l Value histograms, execution cost Speed up expensive functions Extends computed column indexes and index views Implied and residual predicates PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 12
  • 13. Summary Richer server programming model l Ø Ø Ø Any .NET framework language Same mid - and server -tier data access: midserverADO. NET Same IDE, project model, debugging, tools SQL Server hosting of .NET runtime l Ø Safety, security, scalability, speed SQL Server .NET features l Ø Functions, stored procedures, triggers, types, aggregates Demos l l Sample code for function, stored procedure, and type Assemblies Ø l Functions and stored procedures Ø Ø l Safe versus external access Creation and execution Data access in-process via ADO .NET in- Types Ø Ø Ø Ø Ø Type contract Create type Create table with column of user-defined type userCreate index on column of user-defined type userInsert and query the table PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 13
  • 14. © 2001 Microsoft Corporation. All rights reserved. PDC 2001 October 22-26, 2001 © 2001 Microsoft Corporation. All rights reserved. 14