1. Trang chủ
  2. » Công Nghệ Thông Tin

SQL Server - Bài 8

56 473 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Lập trình sql server với .net
Tác giả Vu Tuyet Trinh
Trường học Hanoi University of Technology
Thể loại bài
Thành phố Hanoi
Định dạng
Số trang 56
Dung lượng 899 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

SQL Server - Bài

Trang 2

What is NET?

 An application development platform from Microsoft

 Rapidly develop secure and robust software

 Full support for object-oriented programming

Trang 3

Advantages of Net Framework

 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)

Trang 5

.Net Framework

Web Forms

Web Services

ADO.NET and XML Base Framework Classes Common Language Runtime

Win

Trang 6

Layer

Connected Layer

Data Layer

Trang 7

ADO.NET Managed Provider

System.data.dll

+{System.data}

….

IDbConnection IDbCommand IDataReader IDbTransaction IDbDataAdapter

Trang 8

 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)

Trang 9

 In-memory cache of data

 Relational view of data

 Data source agnostic

 Keeps track of changes

Trang 11

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}

Trang 12

SelectCommand InsertCommand UpdateCommand DeleteCommand

Update

Trang 13

DataSet Interaction

SqlDataAdapter DB

XmlTextReader XmlTextWriter

XML File

Trang 15

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

Trang 16

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 … )

Trang 17

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

Trang 19

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

Trang 20

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

Trang 21

DML Assembly Commands for CAS

Trang 22

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

Trang 23

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

} }

Trang 24

Managed Stored Procedure DML

CREATE PROCEDURE <Procedure Name>

AS EXTERNAL NAME <Assembly Identifier>.<Type Name>.<Method Name>

Trang 25

Stored Procedure Parameters

// Input Parameterpublic static void InputProcedure(int number) {}

// Output Parameterpublic static void OutputProcedure(out int number) { number = 42;

}

// In/Out Parameterpublic static void InOutProcedure(ref int number) { number = 42;

}// Return Parameter

Trang 26

DML must match the parameters

CREATE PROCEDURE InputProcedure @number int

AS EXTERNAL NAME AssemlyExample.SqlClr.InputProcedure

CREATE PROCEDURE OutputProcedure

@number int OUTPUT

AS EXTERNAL NAME AssemlyExample.SqlClr.OutputProcedureCREATE PROCEDURE InOutProcedure

@number int OUTPUT

Trang 27

Managed Functions

Using similar DML Syntax:

CREATE FUNCTION <Function Name>

(

<Parameter List>

)

RETURNS <Return Type>

AS EXTERNAL NAME <Assembly Identifier>.<Type Name>.<Method Name>

CREATE FUNCTION Addition(

@x int, @y int)

Trang 29

Managed Triggers

 DDL Triggers

CREATE TRIGGER <TriggerName>

ON <Table or View> <FOR|INSTEAD OF> <INSERT|UPDATE|DELETE>

AS EXTERNAL NAME <Assembly Identifier>.<Type Name>.<Method Name>

CREATE TRIGGER AddContact

ON author FOR INSERT

AS EXTERNAL NAME AssemlyExample.SqlClr.AddContact

CREATE TRIGGER <TriggerName>

ON <ALL_SERVER or DATABASE> <FOR or AFTER> <EventName>

AS EXTERNAL NAME <Assembly Identifier>.<Type Name>.<Method Name>

CREATE TRIGGER AddUser

Trang 30

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)

}

Trang 31

Custom Aggregates

 Define a CLR Type that does the aggregation

 Use DML command to register

CREATE AGGREGATE <Aggregate Name>

( @param <SQL Type> )RETURNS <SQL Type>

EXTERNAL NAME <assembly>.<CLR Type>

CREATE AGGREGATE CustomAverage( @value float )

RETURNS floatEXTERNAL NAME AssemlyExample.CustomAverage

Trang 32

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

Trang 33

Custom Average Example

public void Init() { }

public void Accumulate(SqlDouble Value) {

++_totalCount;

if (_total.IsNull) _total = 0;

_total += Value;

}

public void Merge(StdDev grp) {/* */ }

public SqlDouble Terminate() { return _total/_totalCount; }

Trang 34

InProc Managed Provider

 Inside the Server, a new Provider

 Very similar to SqlClient Provider

 Follows Managed Provider Model

Trang 35

InProc Managed Provider (2)

 Dude, where’s my Connection?

Trang 36

InProc Managed Provider (3)

 InProc you can assume the connection

using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = " ";

SqlContext.Pipe.ExecuteAndSend(cmd);

}

Trang 37

InProc Managed Provider (4)

 If you need a connection

 Can create additional connections

 Use “context connection=true” for current

using (SqlConnection conn =

new SqlConnection("context connection=true"))

using (SqlCommand cmd = conn.CreateCommand()) {

cmd.CommandText = @"SELECT * FROM Sales.SalesOrderHeader";

Trang 38

InProc Managed Provider (5)

Trang 39

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

SqlCommand cmd = new SqlCommand();

cmd.CommandText = "SELECT * FROM Customer";

// Send the results to the client

SqlPipe pip = SqlContext.Pipe.Execute(cmd);

SqlCommand cmd = new SqlCommand();

cmd.CommandText = "SELECT * FROM Customer";SqlDataReader rdr = cmd.ExecuteReader();

Trang 40

InProc Managed Provider (7)

 Returning Custom Results

 Use SqlDataRecord

 Must create SqlMetaData to describe the resultSqlMetaData[] columns = new SqlMetaData[3];

columns[0] = new SqlMetaData("ID", SqlDbType.Int);

columns[1] = new SqlMetaData("Name", SqlDbType.NVarChar, 50);

columns[2] = new SqlMetaData("theDate", SqlDbType.DateTime);

SqlDataRecord record = new SqlDataRecord(columns);

Trang 41

InProc Managed Provider (8)

 Return Custom Results (Multiple Rows)

 Use SendResultsStart to begin

 Must send all rows with SendResultsRow

 Must end with SendResultsEnd

Trang 42

InProc Managed Provider (9)

 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();

Trang 43

Managed User-Defined Datatypes

 Before SQL Server 2005

 User Datatypes were aliases or restrictions

 Since SQL Server 2005

 Can store CLR Type as a Datatype

 Rules are embedded in the CLR Type

EXEC sp_addtype N'age', N'tinyint', N'not null'GO

CREATE RULE age_rangeAS

@age >= 0 AND @age <=140GO

EXEC sp_bindrule N'age_range', N'age'GO

Trang 44

CLR Data Type - Requirements

 Supports the concept of NULL

 Supports conversion to and from string

 Supports serialization

 Supports a default constructor

 Type and member conform to naming rules

 (128 character maximum)

Trang 45

Creating a User-Defined Data Type

DML Statement: CREATE TYPE

CREATE TYPE <database type name>

EXTERNAL NAME <assembly name>.<CLR type name>

CREATE TYPE Point EXTERNAL NAME AssemlyExample.Point

Trang 46

UDT Example

[Serializable]

[SqlUserDefinedType(Format.UserDefined, MaxByteSize=8)] public class Point : INullable, IBinarySerialize {

bool isNull = false;

Trang 48

UDT Methods

Marking it with SqlMethod can expose it

 IsMutator shows SQL Server that it changes itself:

 Can use with the point syntax:

Trang 50

Benefits from CLR Integration

 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

Trang 51

Benefits … (2)

 For complex calculations

 Parsing strings (like the regular expression code)

Trang 52

Week points …

 Lots of programming for simple operations

 Some overhead in communicating with assemblies

 Remember – T-SQL is designed and optimised for data, use it!

 Potentially costly to rewrite logic

 Companies (including us) have invested a lot in T-SQL

Trang 53

Calling between T-SQL & SQL-CLR

Having some restrictions

 Must only use T-SQL supported data types

 Can't use inheritance or polymorphism.

 No equivalent of DB_NULL in NET

 can use null for reference types, but not for types like int

 .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.

Trang 54

 Need to manipulate data before it is displayed

Use NET code and SQLCLR

 Need to do set-based operations such as pivoting

Use T-SQL

 Need to do extensive computation or custom algorithms

Use NET code and SQLCLR

 Have many complex store procedure

Trang 56

Demo

Ngày đăng: 15/11/2012, 10:59

TỪ KHÓA LIÊN QUAN