Lập trình SQL Server: Hanoi University of Technology
Lập trình SQL Server: Hanoi University of Technology
Lập trình SQL Server: Hanoi University of Technology
với .Net
Vu Tuyet Trinh
[email protected]
Hanoi University of Technology
1
What is .NET?
Microsoft
Advantages of .Net Framework
Microsoft
Outline
.Net Framework
ADO.net
CLR Integration
Enabling CLR Integration
CLT Integration: Pros & Cons
Microsoft
.Net Framework
Microsoft
ADO.NET Architecture
Disconnected Connected Data
Layer Layer Layer
Command
DataSet DataAdapter
Builder
DataReader Command
Transaction Connection
Microsoft
ADO.NET Managed Provider
System.data.dll System.data.dll
+{System.data} +{System.data.SqlClient}
…. ….
IDbConnection SqlConnection
IDbCommand SqlCommand
IDataReader SqlDataReader
IDbTransaction SqlTransaction
IDbDataAdapter SqlDataAdapter
…. SqlCommandBuilder
Microsoft
DataSet
DataSet
Table
In-memory cache of data
Relational view of data
Column
Data source agnostic
Keeps track of changes
Constraint
Contains an XSD schema
MarshalByValue object
Row
Relation
Microsoft Schema
TypedDataSet
Without TypedDataSet
dataset.Tables[0].Rows[0][1] = 1023;
dataset.Tables[“Orders”].Rows[0][“CustomerID"] = 1023;
With TypedDataSet
dataset.Orders[0].CustomerID = 1023;
Code is more readable
Introduces compile-time checking
Intellisense under Visual Studio
Microsoft
Generated TypedDataSet
Class OrdersDataSet: DataSet {
InitClass() {
DataSet
// create relations, constraints
} Orders
class OrdersDataTable: DataTable { Tables[0]
void AddOrdersRow(OrderRow row)
void AddOrderRow(int OrderID, int CustomerID, ..) OrdersDetails
OrderRow FindOrderByID(int OrderID)
Tables[1]
OrderRow NewOrderRow()
}
class OrdersRow: DataRow {
int OrderID {get; set}
int CustomerID {get; set}
.....
}
……
Microsoft
}
DataAdapter
CommandBuilder
DataAdapter
SelectCommand
Fill Fill
InsertCommand
DataSet
UpdateCommand
DeleteCommand
Update Update
TableMapping
Microsoft
DataSet Interaction
DataView XmlTextReader
XML
Filter/Sort XmlTextWriter File
DataControl
SqlDataAdapter DB
DataGrid
ComboBox…
ComboBox
Microsoft
Outline
.Net Framework
ADO.net
CLR Integration
Enabling CLR Integration
CLT Integration: Pros & Cons
Microsoft
CLR Integration
Microsoft
What can we do with CLR code?
Microsoft
Where do we use CLR code?
Microsoft
Enabling CLR Integration
Enabled on an instance
SQL Script
Execute sp_configure ‘clr enabled’, ‘1’
Sp_reconfigure
Microsoft
Assembly Management
Microsoft
Code Access Security for Assemblies
Microsoft
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
Microsoft
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
Microsoft
Managed Stored Procedures
Microsoft
Managed Stored Procedure DML
Example
Microsoft
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;
Microsoft }
DML must match the parameters
Microsoft
Managed Functions (2)
[SqlFunction] Parameters
Helps SQL Server know what the function does
IsDeterministic
IsPrecise
DataAccess
SystemDataAccess
Microsoft
Managed Triggers
DML Triggers
DDL Triggers
CREATE TRIGGER <TriggerName>
ON <ALL_SERVER or DATABASE> <FOR or AFTER> <EventName>
AS EXTERNAL NAME <Assembly Identifier>.<Type Name>.<Method Name>
CREATE TRIGGER AddUser
ON DATABASE FOR CreateUser
AS EXTERNAL NAME AssemlyExample.SqlClr.AddUser
Microsoft
TriggerContext
ColumnsUpdates to see what columns changed
public static void AddAuthor() {
SqlTriggerContext ctx = SqlContext.TriggerContext;
if (ctx.TriggerAction == TriggerAction.Insert) {
string msg = "";
// Get the data associated with Event
for (int x = 0; x < ctx.ColumnCount; ++x) {
msg += string.Format("Column {0} {1} been updated{2}",
x,
(ctx.IsColumnsUpdated(x) ? "has" : "has not"),
Environment.NewLine)
}
Microsoft
Custom Aggregates
Microsoft
Custom Aggregates - CLR Class
called during the aggregation
Not just passed a set of values, but one at a time
Must be serializable (for intermediate results)
Must implement known methods
Init
Called at the start of the aggregation of fields
Accumulate
Called once for each row being aggregated. It is passed the value from
the column being aggregated.
Merge
Called to merge a temporary result into the aggregate
Terminate
Called at the end of the aggregation process to retrieve the result of the
aggregation.
Microsoft
Custom Average Example
[Serializable]
[SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize = 8000)]
public class CustomAverage : IBinarySerialize {
SqlDouble _total = 0;
ulong _totalCount = 0;
Microsoft
InProc Managed Provider (2)
Dude, where’s my Connection?
In Out-of-proc ADO.NET:
while (rdr.Read()) {
Console.WriteLine(rdr.GetString(0));
}
} // Reader is disposed
} finally {
conn.Close()
}
} // using statements ensure Disposed is called
Microsoft
InProc Managed Provider (3)
SqlContext.Pipe.ExecuteAndSend(cmd);
}
Microsoft
InProc Managed Provider (4)
If you need a connection
Can create additional connections
Use “context connection=true” for current
try {
conn.Open();
} finally {
conn.Close();
}
Microsoft
}
InProc Managed Provider (5)
SqlContext
Used to get active server objects
Pipe
WindowsIdentity
Etc.
Microsoft
InProc Managed Provider (6)
Returning Data
Use a Pipe to send data back to the client
Use the SqlContext’s Pipe
Use Execute() to Fire a Command into the pipe
Use Send() to send results back from a Reader
record.SetInt32(0, 1);
record.SetString(1, "Bob Higgins");
record.SetDateTime(2, DateTime.Now);
SqlContext.Pipe.Send(record);
Microsoft
InProc Managed Provider (8)
Return Custom Results (Multiple Rows)
Use SendResultsStart to begin
Must send all rows with SendResultsRow
Must end with SendResultsEnd
// Start it
SqlContext.Pipe.SendResultsStart(record); // Only primes pump
SqlContext.Pipe.SendResultsRow(record);
// Finish ResultSet
SqlContext.Pipe.SendResultsEnd();
Microsoft
InProc Managed Provider (9)
SQL Server Datatypes
Use System.Data.SqlTypes namespace
Each SqlXXXXX type is INullable
Allows Stored Procs that allow DB Nulls
public static void GetContact(SqlString email) {
SqlCommand cmd = new SqlCommand();
cmd.CommandText =
@"SELECT FirstName, LastName
FROM Person.COntact
WHERE EmailAddress = @email";
SqlContext.Pipe.ExecuteAndSend(cmd);
}
Microsoft
Managed User-Defined Datatypes
Before SQL Server 2005
User Datatypes were aliases or restrictions
Microsoft
CLR Data Type - Requirements
Microsoft
Creating a User-Defined Data Type
Microsoft
UDT Example
[Serializable]
[SqlUserDefinedType(Format.UserDefined, MaxByteSize=8)]
public class Point : INullable, IBinarySerialize {
bool isNull = false;
int x;
int y;
// Required constructor
public Point() : this(0, 0) {
}
DECLARE @p as dbo.Point
SET @p = Convert(dbo.Point, '3,8')
SELECT @p
Microsoft
UDT Methods
.Net Framework
ADO.net
CLR Integration
Enabling CLR Integration
CLR Integration: Pros & Cons
Microsoft
Benefits from CLR Integration
Microsoft
Benefits … (2)
Microsoft
Week points …
Microsoft
Calling between T-SQL & SQL-CLR
Having some restrictions
Must only use T-SQL supported data types.
Can't use inheritance or polymorphism.
Microsoft
Summary
Need to manipulate data before it is displayed
Use .NET code and SQLCLR
Microsoft
Microsoft
Demo
Microsoft