Lập trình SQL Server
với .Net
Vu Tuyet Trinh
Hanoi University of Technology
1
MicrosoftMicrosoft
What is .NET?
An application development platform from Microsoft
Rapidly develop secure and robust software
Web and Windows
Full support for object-oriented programming
MicrosoftMicrosoft
Advantages of .Net Framework
CLR – Common Language Runtime
Garbage collector, type safety, JIT, …
Language integration
C#, VB.net, …
Built-in support for open standards
SOAP, …
Simple development, simple deployment
Supporting entity data model (ADO.net & entity framework)
MicrosoftMicrosoft
Outline
√
.Net Framework
ADO.net
CLR Integration
Enabling CLR Integration
CLT Integration: Pros & Cons
MicrosoftMicrosoft
.Net Framework
Web
Forms
Web
Services
ADO.NET and XML
Base Framework Classes
Common Language Runtime
Win
Forms
…
MicrosoftMicrosoft
DataReader
DataSet
DataAdapter
ADO.NET Architecture
Command
Transaction
Connection
Command
Builder
Disconnected
Layer
Connected
Layer
Data
Layer
MicrosoftMicrosoft
ADO.NET Managed Provider
System.data.dll
+{System.data}
….
IDbConnection
IDbCommand
IDataReader
IDbTransaction
IDbDataAdapter
….
System.data.dll
+{System.data.SqlClient}
….
SqlConnection
SqlCommand
SqlDataReader
SqlTransaction
SqlDataAdapter
SqlCommandBuilder
Warning: There is no IDbCommandBuilder
MicrosoftMicrosoft
DataReader
Fast Forward-Only/Read-Only streams of data
Returned by IDbCommand.ExecuteReader(...)
Data is not cached on the client-side
Must be closed explicitly
Not serializable
Cannot be inherited (sealed class)
MicrosoftMicrosoft
DataSet
In-memory cache of data
Relational view of data
Data source agnostic
Keeps track of changes
Contains an XSD schema
MarshalByValue object
DataSet
Schema
Relation
Table
Column
Constraint
Row
MicrosoftMicrosoft
TypedDataSet
Without TypedDataSet
Without TypedDataSet
With TypedDataSet
With TypedDataSet
Code is more readable
Introduces compile-time checking
Intellisense under Visual Studio
dataset.Tables[0].Rows[0][1] = 1023;
dataset.Tables[“Orders”].Rows[0][“CustomerID"] = 1023;
dataset.Orders[0].CustomerID = 1023;
MicrosoftMicrosoft
Generated TypedDataSet
Class OrdersDataSet: DataSet {
InitClass() {
// create relations, constraints
}
class OrdersDataTable: DataTable {
void AddOrdersRow(OrderRow row)
void AddOrderRow(int OrderID, int CustomerID, ..)
OrderRow FindOrderByID(int OrderID)
OrderRow NewOrderRow()
}
class OrdersRow: DataRow {
int OrderID {get; set}
int CustomerID {get; set}
.....
}
……
}
Orders
OrdersDetails
Tables[0]
Tables[1]
DataSet
DataSet
MicrosoftMicrosoft
DataAdapter
SelectCommand
InsertCommand
UpdateCommand
DeleteCommand
TableMapping
DataAdapter
DataAdapter
CommandBuilder
DataSet
Fill
Update
Fill
Update
MicrosoftMicrosoft
DataSet Interaction
SqlDataAdapter
DB
XmlTextReader
XmlTextWriter
XML
File
DataControl
DataControl
DataGrid
DataGrid
ComboBox
ComboBox…
DataView
DataView
Filter/Sort
MicrosoftMicrosoft
Outline
√
.Net Framework
√
ADO.net
CLR Integration
Enabling CLR Integration
CLT Integration: Pros & Cons
MicrosoftMicrosoft
CLR Integration
Brand new since SQL Server 2005
(Standard and Express)
Write database queries using .NET
Supporting Any .NET language (C#, VB, C++)
Creating and debugging using VS 2005 IDE
MicrosoftMicrosoft
What can we do with CLR code?
Common T-SQL objects can be implemented in CLR code
User defined functions (and table valued functions)
Stored procedures
Triggers
Additional objects can be implemented in CLR code
User Defined Types
User Defined Aggregates (MAX, MIN, SUM … )
MicrosoftMicrosoft
Where do we use CLR code?
Round trip Round trip
“Distance” between the code and the data
Scale up/out possibilities of different tiers
Abstraction of the database technology
Security requirements
Set-based versus procedural code
Possibilities for using shared code libraries in multiple tiers
MicrosoftMicrosoft
Enabling CLR Integration
Enabled on an instance
SQL Script
Execute sp_configure ‘clr enabled’, ‘1’
Sp_reconfigure
Surface Area Configuration (features)
MicrosoftMicrosoft
Assembly Management
Adding an assembly from file
Note: must have permissions (NT Security)
Adding an assembly from bitstream
CREATE ASSEMBLY AssemlyExample
FROM 'd:\AssemlyExample.dll'
CREATE ASSEMBLY AssemlyExample
FROM
0x4D5A90000300000004000000FFFF0000B8000000000000...
MicrosoftMicrosoft
Code Access Security for Assemblies
3 Code Access Security (CAS) Buckets
SAFE
Access to the CLR only
No access to external resources, thread management, unsafe code or
interoper
EXTERNAL_ACCESS
Access to external systems through the .NET Framework
E.g. EventLog, FileSystem and Network
No access unsafe or interop
UNSAFE
No restrictions; similar to extended stored procedures
MicrosoftMicrosoft
DML Assembly Commands for CAS
SAFE
CREATE ASSEMBLY AssemlyExample
FROM 'd:\AssemlyExample.dll'
WITH PERMISSION_SET=SAFE
EXTERNAL_ACCESS
CREATE ASSEMBLY AssemlyExample
FROM 'd:\AssemlyExample.dll'
WITH PERMISSION_SET=EXTERNAL_ACCESS
UNSAFE
CREATE ASSEMBLY AssemlyExample
FROM 'd:\AssemlyExample.dll'
WITH PERMISSION_SET=UNSAFE
MicrosoftMicrosoft
Managed Code
Code isn’t available by default
Must register functions, stored procedures, etc.
Code is not available by default
Registration takes certain permissions to allow
Attributes
Hints to VS about how to deploy
[SqlProcedure]
[SqlFunction]
[SqlUserDefinedType]
[SqlUserDefinedAggregate]
….
Also used at runtime for behaviors of objects
MicrosoftMicrosoft
Managed Stored Procedures
To expose a Stored Procedure:
The containing class must be public
The exposed method must be public
The exposed method must be static
public class SqlClr {
public static void MyProc() {
// Put your code here
}
}
MicrosoftMicrosoft
Managed Stored Procedure DML
Uses the CREATE PROCEDURE call
Adds AS EXTERNAL NAME to specify CLR SP
Example
CREATE PROCEDURE <Procedure Name>
AS EXTERNAL NAME <Assembly Identifier>.<Type Name>.<Method Name>
CREATE PROCEDURE MyProc
AS EXTERNAL NAME AssemlyExample.SqlClr.MyProc
MicrosoftMicrosoft
Stored Procedure Parameters
// Input Parameter
public static void InputProcedure(int number) {
}
// Output Parameter
public static void OutputProcedure(out int number) {
number = 42;
}
// In/Out Parameter
public static void InOutProcedure(ref int number) {
number = 42;
}
// Return Parameter
public static int ReturnProcedure() {
return 42;
}