Download SQL Server Yukon - Microsoft Center

Document related concepts

Serializability wikipedia , lookup

Concurrency control wikipedia , lookup

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

SQL wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Clusterpoint wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Relational model wikipedia , lookup

PL/SQL wikipedia , lookup

Database model wikipedia , lookup

Transcript
Vývoj pro SQL Server 2005
T-SQL
.NET integrace
XML
Novinky v T-SQL
Schemas
SQL Server 2005 allows multiple schemas in a single
database
schemas exist independent of users
each user has a default schema
2-part name must be used to create in non-default
Schema name can be substituted for user name in
object
eases database management when personnel changes
accounts is a schema,
no user 'accounts' exists
CREATE TABLE accounts.invoice (…)
GO
Dan now owns
accounts schema
ALTER SCHEMA accounts
AUTHORIZATION Dan
SQL Server 2005 Code execution
context
SQL Server 2005 code need not execute as caller
EXECUTE AS can be specified on
stored procedures
functions
EXECUTE AS can be specified for batches
can be nested
revert to previous principal using revert all
Code can execute as:
CALLER
OWNER
SELF
a specific user
Transaction isolation and
versioning
SQL Server 2005 can use versioning
isolation accomplished by combination of locking
and versioning
write locks block other writers
write locks do not block readers
readers do not lock by default
readers do not block writers by default
known as snapshot isolation
eases conversion from versioning databases
Snapshot
Snapshot always reads coherent data
no read lock needed even though data being
changed
version of each value maintained as long as needed
transaction reads version of value corresponding to
its start time
Snapshot Transactions are ACID
Failures may be deferred
write fails if version later than that when transaction
started
serialization isolation holds off transaction until safe
to proceed
Snapshot isolation types
SQL Server 2005 provides two styles of
snapshot isolation
both provide conflict detection
transaction-level snapshot
consistent as of beginning of transaction
won't see changes others commit during transaction
most like serializable
statement-level snapshot
consistent as of last statement
will see changes others commit during transaction
most like read committed
Extended triggers
SQL Server SQL Server 2005 extended trigger
types
previously only triggers for tables and views
SQL Server 2005 adds
DDL triggers
triggers on system events
CREATE TABLE ddl_log (data VARCHAR(MAX))
GO
-- Create Trigger
CREATE TRIGGER trig_create_tab
ON DATABASE
FOR CREATE_TABLE
AS
INSERT ddl_log VALUES (EVENTDATA())
GO
DDL Trigger
Handling exceptions
SQL Server Yukon adds exception handling
Error handling in previous SQL Server versions
tedious
@@ERROR set on each statement
set variable with @@ERROR, then check value
Yukon adds BEGIN-END TRY BEGIN-END CATCH
blocks
semantic equivalent of BEGIN-END blocks
additional functions return error info
can query transaction status
can save @@ERROR
Exception handling example
-- catch errors in a procedure
CREATE PROCEDURE someproc
AS
BEGIN
BEGIN TRY
SELECT * FROM authors
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER()
END CATCH
END
GO
-- catch errors in a batch
BEGIN TRY
SELECT * FROM authors
END TRY
BEGIN CATCH
-- Test tx state
IF (XACT_STATE()) = -1
ROLLBACK TRANSACTION
IF (XACT_STATE()) = 1
COMMIT TRANSACTION
END CATCH
GO
Try/Catch
Common table expressions
CTE is a temporary named resultset
specified by starting query with a WITH keyword
can be replacement for subquery and used in view
can be used with SELECT/INSERT/UPDATE/DELETE
Common table expression can do recursive calculation
Recursive common table expression has three parts
anchor, followed by UNION ALL; does initialization
recursive member after UNION ALL; recurses until no results
outer select; selects results to be returned
Recursive common table
expression
anchor; executed once
recursive member; repeated
joined with previous recursion
outer select; id's returned
WITH descendant(parent, id, amount) AS
(SELECT parent, id, amount
FROM partsTree WHERE id = @start
UNION ALL
SELECT P.parent, P.id, P.amount
FROM partsTree AS P INNER JOIN
descendant AS A ON A.id = P.parent
)
SELECT id FROM descendant
Rekurzivní CTE
Pivot and Unpivot
The PIVOT keyword makes
rows into columns and aggregates values
generates crosstab reports
UNPIVOT does the opposite
rotates columns to rows (not always symmetric w/PIVOT)
-- quantity by quarter
CREATE TABLE quarterlysales(
product varchar(50),
quarter int,
quantity int)
GO
SELECT product, [1] AS 'Q1', [2] AS 'Q2',
[3] AS 'Q3', [4] AS 'Q4'
FROM quarterlysales
PIVOT(SUM(quantity)
FOR quarter IN ([1], [2], [3], [4])) AS P
Apply operators
APPLY is join
no ON clause allowed
Right part can be any table, but meant for table udf
params for udf can come from columns of left part
Cross and outer apply available
amount comes from invoice row
each invoice row joined
to table returned by greater
SELECT * FROM invoice
CROSS APPLY greater(amount, 1500)
function must return table
equivalent join
SELECT I1.*, I2.amount FROM invoice I1
JOIN invoice I2 ON I2.amount > 1500
AND I2.id = I1.id
OUTPUT clause on action
statements
SQL action statements return "number of rows affected"
sometimes you want to know more
which rows were changed
you could change from a static cursor
what identity columns were generated
you could get @@ identity
both cases require extra work to return info to caller
OUTPUT clause on actions generate output
returned through TABLE variables
no addition program logic needed
can use logical tables to return before/after images
you can insert output clause results into tables
Returning automatic output
-- output rows of "before" values
DECLARE @tab TABLE (c1 ...)
UPDATE orders
SET shipregion = 'RJ'
OUTPUT c.*, INSERTED.* into @tab
FROM orders o JOIN customers c
ON o.customerid=c.customerid
GO
-- return default value and GUID
CREATE TABLE T (
id int, name varchar(20),
a TIMESTAMP, b UNIQUEIDENTIFIER)
GO
INSERT T
OUTPUT INSERTED.* into @tab -- table variable
VALUES (1, 'bob', DEFAULT, NEWID())
GO
XML
XML as a data type
The XML data type is native database type
used as type of column in table
used as type of parameter in stored procedure
used as type of return value of a user-defined
function
used as type of a variable
XML data type of character types
CREATE TABLE xml_tab (
the_id INTEGER,
xml_col XML)
GO
-- auto conversion
INSERT INTO xml_tab VALUES(1, '<doc/>')
INSERT INTO xml_tab VALUES(2, N'<doc/>')
SELECT CAST(xml_col AS VARCHAR(MAX))
FROM xml_tab WHERE the_id < 10
-- fails, not wellformed
INSERT INTO xml_tab
VALUES(3, '<doc><x1><x2></x1></x2></doc>')
XML column
XML column can store well-formed XML
XML 1.0 recommendation
documents or fragments
XML column usage
XML column is not just a TEXT column
XML technologies supported
the contents can validated using XML Schema
XML-aware indexes are supported
XQuery and XPath 2.0 supported
in-database XML-related functionality works on the
type
FOR XML
OpenXML
XML schema collections
XML schemas can be associated with an XML type
insures that data inserted into column complies with schemas
set of schemas known as a schema collection
schema valid XML can disallow fragments
XML schemas used by XML types must be in database
Create XML SCHEMA COLLECTION
collection name associated with XML instance
Create XML SCHEMA COLLECTION requires literal
schemas
CREATE XML SCHEMA COLLECTION geo
'<xs:schema ...
targetNamespace=
"http://www.develop/geo">
...
</xs:schema>'
CREATE TABLE Locations
(
location xml(geo)
...
)
Using strongly typed XML
CREATE TABLE point_tab(
id int IDENTITY primary key,
-- geocoll include schema for 'urn:geo' namespace
thepoint xml(CONTENT, geocoll)
GO
-- this works, schema-valid Point
INSERT INTO point_tab VALUES(
'<Point xmlns="urn:geo"><X>10</X><Y>20</Y></Point>')
-- this insert fails, value foo is not a dim (integer)
INSERT INTO point_tab VALUES(
'<Point xmlns="urn:geo"><X>10</X><Y>foo</Y></Point>')
Práce s XML a XSD
XML indexes
You can create XML INDEXes on an XML column
optimizes XML Queries on the column
table or view must have clustered primary key
composite XML index not allowed
primary XML index must be created first
three specialized index types also available
VALUE, PATH, PROPERTY
CREATE TABLE xml_tab (
id integer primary key,
doc xml)
GO
CREATE PRIMARY XML INDEX xml_idx on xml_tab (doc)
GO
Using XML type in a table
XML has some special features when used as a
column
can define DEFAULT values
must be well-formed or schema valid
can define CHECK constraints
use XML type methods to compare to implement
create table documents(
id INT,
doc XML DEFAULT '<invoice/>',
CONSTRAINT ck_inv
CHECK(doc.exist('/invoice')=1)
)
this will succeed
this will fail
INSERT documents VALUES (1, DEFAULT)
INSERT documents VALUES (2,'<book/>')
SQL Server 2005 Support of
XQuery
XQuery is supported through methods on the XML type
xml.exist
xml.value
xml.query
xml.modify
xml.nodes
These methods can return
columns in rowsets - when used with SQL SELECT
variables
Enhancements to SELECT...FOR
XML
SELECT FOR XML is an extension to TransactSQL
usually produces a stream
in Yukon, it can also produce an XML data type
use TYPE keyword after FOR XML
can@x
be used
DECLARE
xml with RAW, AUTO formats
SET @xcan
= be
SELECT
FROMa "collection"
authors of documents
used to*query
FOR XML AUTO, TYPE
FOR XML PATH
SELECT FOR XML PATH allows shaping of
output
FOR XML AUTO, RAW allow little shaping
FOR XML EXPLICIT is complex to write
FOR XML PATH uses path-syntax in column aliases
allows "creation" of elements
simpler than XML EXPLICIT
XML PATH example
SELECT
au_id as [@authorid],
au_fname as [name/firstname],
au_lname as [name/lastname]
FROM authors FOR XML PATH
<row @authorid="111-11-1111">
<name>
<firstname>Bob</firstname>
<lastname>Smith</lastname>
</name>
</row>
...
.NET
Hosted CLR
.Net CLR hosted inside SQL Server to improve
performance
applications run in same address space as SQL
Server
stored procedures in any language supported by
CLR
web services can run inside of SQL Server
.NET assembly permission sets
.NET assemblies don't use traditional CAS evidence
all .NET assembly code lives in the database
no notion of evidence based on load location
unsafe .NET assembly must be code signed
public code key stored in master DB
.NET assembly permission sets via CREATE
ASSEMBLY
SAFE
EXTERNAL_ACCESS
UNSAFE
Cataloging assemblies
CREATE ASSEMBLY is used to catalog an
assembly
bits can be loaded from disk or stream
assembly is assigned a symbolic name
bits are stored in system table
SQL Server principal running create must have
assembly catalog permissions
file system access to the code
symbolic name
assembly name
CREATE ASSEMBLY math FROM 'c:\types\math.dll'
Replacing code
ALTER ASSEMBLY used to replace code
used for in-place fixes
cannot alter signatures in assembly
permissions retained
stored procedure, UDF, trigger definitions retained
UDTs and UDAggs subject to limitations
can skip validation of existing data
-- replace assembly
-- do not check existing data
ALTER ASSEMBLY asm
FROM 'c:\mydir\asm.dll'
WITH UNCHECKED DATA
CLR functions
Any CLR language function can be used as a TSQL function
class must be public
function must be public static
assembly containing class must be cataloged
function must be cataloged
public class
public static function
math.dll
namespace Math
{
public class Inverter
{
public static int
Invert(int x)
{
return -x;
}
}
}
Cataloging functions
CREATE FUNCTION used to catalog function
only cataloged functions can by used by T-SQL
symbolic T-SQL name bound to CLR function name
CLR function parameters bound by position
T-SQL parameters use ‘@’ syntax
namespace must be escaped by [ ]
bound to first
CLR function
parameter
T-SQL name
Create Function DoInvert(@A int) returns int
As EXTERNAL NAME math.[Math.Inverter].Invert
CLR name
.NET funkce
SQL Server programming models
SQL Server 2005 works with two data providers
System.Data.SqlServer
System.Data.SqlClient
Programming Models have some differences
SqlClient uses a SqlConnection
SqlServer uses a SqlContext
System.Data.SqlClient
SqlConnection
Select * from ...
System.Data.SqlServer
SqlContext
Select * from ...
Database
Code inside the database
SqlServer needs no connection
explicit connection would unneeded and wasteful
Command are part of same batch
running code may already be in a transaction
Context provides direct access to database
code runs as though part of database
Code outside the database
Code outside the database needs to establish a
connection
establish buffers
start a batch of commands
start a transaction or “participate in” one
System.Data.SqlClient
Input Buffer
Socket
Connection
Output Buffer
Socket
Transaction
Database
SqlContext
SqlContext represents current execution context
GetConnection() gets the current connection
GetCommand() gets a new command in current
batch
GetTransaction() gets the current transaction (if
exists)
GetPipe() gets pipe to the output TDS stream
pipe permits sending messages, results
SqlTriggerContext
SqlTriggerContext is the environment inside a
trigger
can get it from SqlContext
contains Trigger.Action enumeration
INSERT, UPDATE, or DELETE
contains ColumnsUpdated
array of boolean flags == TSQL's COLUMNS_UPDATED
can get EventData
for extended triggers, more control (more on this later)
Why user-defined types?
Add scalars that extend the type system
used in sorts, aggregates
customized sort orders and arithmetic calculations
Allows scalars to be implemented efficiently
compact representation
operations written in compiled language
Cataloging a UDT
SQL Server 2005 UDTs live in .NET assemblies
first, catalog assembly (CREATE ASSEMBLY)
then, catalog type (CREATE TYPE)
external name = name of .NET class
symbolic name can be whatever you like
CREATE ASSEMBLY Point
FROM 'c:\types\Point.dll'
GO
CREATE TYPE PointCls
EXTERNAL NAME Point.PointCls
GO
Working with UDTs
Types can be used
as columns in tables
variables and parameters
UDF return value
UDT supports implicit conversion from varchar
explicit convert can be used
or you can write factory function (no "new" in T-SQL)
CREATE TABLE point_tab(
id int primary key,
thepoint PointCls)
INSERT INTO point_tab
values(1, '100:200')
DECLARE @p PointCls
SET @p = convert(PointCls, '300:400')
Accessors and mutators
All public fields are available as "members" of
the type
useable with dot syntax
instance.member, instance.method
instance members are case-sensitive
Methods marked as "mutators" can only be used
in statements that update the database
SELECT thepoint.m_x, thepoint.m_y
FROM point_tab
go
-- use mutator
-- the name of mutator is case-sensitive!
UPDATE point_tab SET thepoint.SetXY(20, 30)
WHERE thepoint.m_x = 0
User-defined aggregates
UDA’s can be written inside .NET classes
accumulators, with computations
used for specialized mathematics
useful as .NET components because compiled
Aggregate use
GROUPBY
inside stored procedures, functions
OVER clause
TSQL vs C#
Konverze Binary na Hex
if @bin is null return null
declare @len int, @b tinyint, @lowbyte tinyint, @hibyte tinyint, @index int, @str nchar(2), @result nvarchar(4000)
set @len = datalength(@bin)
set @index = 1
set @result = '0x'
while @index <= @len
begin
set @b = substring(@bin, @index, 1)
set @index = @index + 1
set @lowbyte = @b & 0xF
set @hibyte = @b & 0xF0
if @hibyte > 0
set @hibyte = @hibyte / 0xF
set @result = @result +
((case
when @hibyte < 10 then convert(varchar(1), @hibyte)
when @hibyte = 10 then 'A'
when @hibyte = 11 then 'B'
when @hibyte = 12 then 'C'
when @hibyte = 13 then 'D'
when @hibyte = 14 then 'E'
when @hibyte = 15 then 'F'
else 'Z'
end)
+
(case
when @lowbyte < 10 then convert(varchar(1), @lowbyte)
when @lowbyte = 10 then 'A'
when @lowbyte = 11 then 'B'
when @lowbyte = 12 then 'C'
when @lowbyte = 13 then 'D'
when @lowbyte = 14 then 'E'
when @lowbyte = 15 then 'F'
else 'Z'
end))
end
if (value == null) return null;
StringBuilder sb = new StringBuilder();
foreach (byte b in value)
sb.Append(b.ToString("X2"));
return sb.ToString();
TSQL vs C#
Přístup k datům
SELECT * FROM T_CUSTOMERS WHERE C_CITY = @name
private static readonly SqlDefinition x_definition;
string query = “SELECT * FROM T_CUSTOMERS WHERE C_CITY = @name”;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Parameters.Add(new SqlParameter("@name", SqlDbType.NVarChar, 128));
x_definition = new SqlDefinition(cmd);
SqlExecutionContext sec = SqlContext.GetConnection().CreateExecutionContext(x_definition);
sec.SetSqlString(0, "ExecutePredefinedQuery");
SqlContext.GetPipe().ExecuteReader(sec);
Závěr
T-SQL rozšíření
Rekurzivní CTE
XML
Nativní datový typ
Podpora XSD
Podpora XQUery
.NET
Možnost psaní v .NETu procedury, funkce, triggery
Možnost napsat vlastní uživatelské typy či agregace
© 2005 Microsoft Corporation. All rights reserved.
This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS
OR IMPLIED, IN THIS SUMMARY.