Académique Documents
Professionnel Documents
Culture Documents
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=v^=^=!^=f
=
=
..
100
C#
U
.
SQL Server 2008
Express
U
Server
SQL
Server
Stored Procedures C#
2.0 4.0
XML Transactions
ADO.NET .
ADO.NET .
.
.
.
hosam@live.co.uk
=^==g
Egypt Network
C#,ASP.NET,SQL Server,SharePoint ,InfoPath,XML
:
http://sharepointhero.wordpress.com/
_____________________________________________________
^l
..............................................................................................................................
.................................................................................................................... MS SQL Server 2008
.............................................................................................................................
.......................................................................................................................................
3T
3T
3T
3T
3T
3T
3T
3T
3T
...............................................................................................................:
...........................................................................................................................
) Data Base Management System ( DBMS ...................................................
Relational DBMS .................................................................................................................
...................................................................................................................
RDBMS ............................................................................
RDBMS ........................................................................... Servers
.............................................................................................. DB Life Cycle
......................................................................................................................
................................................................................................................................. Keys
........................................................................................................... Data Integrity
....................................................................................................................Normalization
....................................................................................................................... Normalization
.......................................................................................................................................
.......................................................................................................................................
...................................................................................... Database Queries
.............................................................................................................................
....................................................................................................................QBE and SQL
.......................................................................................................... Queries
: ..................................................................................................................
..........................................................................................................
............................................................................................................................... GROUP BY
................................................................................................................................... PIVOT
.........................................................................................................................ROW_NUMBER
.........................................................................................................................PARTITION BY
.............................................................................................................. Pattern Matching
......................................................................................................... Aggregate Functions
............................................................................................. DATETIME Functions
......................................................................................................................................... JOINS
........................................................................................................................................ Inner Joins
........................................................................................................................................ Outer Joins
........................................................................................................................................ Other Joins
.......................................................................................................................................
.......................................................................................................................................
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
.................................................................................................................... :
..................................................................................................................................
....................................................................................................................... WHERE
Comparison Operators .............................................................. WHERE
........................................................................................................ Combining Predicates
......................................................................................................................Sorting Data
.............................................................................................................. SELECT INTO
SELECT INTO ......................................................................................... Table Structure
................................................................................................................. Inserting Data
................................................................................................................Updating Data
.................................................................................................................. Deleting Data
.......................................................................................................................................
.......................................................................................................................................
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
.......................................................................................................................Stored Procedures
........................................................................................................................... :
................................................................................................................Stored Procedures
Stored Procedure ..................................................................................... SQL Server
Stored Procedure ....................................................................................................
.................................................................................................................. Stored Procedure
..................................................................................................................... SP Definitions
.................................................................................................................................... SP
SP .............................................................................................................. C#
.................................................................................................Deleting Stored Procedure
.......................................................................................................................................
.....................................................................................................................................
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
.................................................................................................................... :
...................................................................................................................................... XML
XML .......................................................................................................................................
..................................................................................................... XML
......................................................................................................................... XML
.......................................................................................................................... XML Declaration
............................................................................................................ XML
........................................................................................................................ :FOR XML RAW
........................................................................................................................ FOR XML AUTO
XML documents ............................................................. XML
.......................................................................................................................................
.....................................................................................................................................
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
Transactions ........................................................................................................................
Transactions ...............................................................................................................
3T
3T
3T
3T
........................................................................................................................... ACID
......................................................................................................................... Transactions
...........................................................................................................................Transaction
) (Boundaries ................................................................................................. Transactions
T-SQL Transaction ...................................................................................
) (Local Transactions ......................................................................................... SQL
) (Distributed Transactions .............................................................................. SQL
...............................................................................................................
...........................................................................................................................
........................................................................................................... T-SQL
................................................................................................. ADO.NET
.....................................................................................................................................
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
3T
MS SQL Server 2008
MS SQL Server 2008
:
Express
.
Express
) (:
3TU
http://www.youtube.com/watch?v=CXJP4D503Tk
U3T
...
:
:
Windows Server 2003 Service Pack 2, Windows Server 2008, Windows Vista, Windows Vista Service Pack 1,
Windows XP Service Pack 2, Windows XP Service Pack 3 ,Windows 7.
:
x Express IA64.
Express ) (:
http://www.microsoft.com/en-us/download/details.aspx?id=1695
SQLEXPR_x64_ENU.exe
SQLEXPR_x86_ENU.exe
3.5 sp1
) ( .Windows Installer 4.5
U3T
3TU
..
:
Install :
Next ..
Express :
Install :
Next :
Next :
close Finish :
Express
Visual Studio 2010
.
Northwind AdventureWorks AdventureWorks
:
3TU
http://msftdbprodsamples.codeplex.com/releases/view/37109
U3T
SQL Server
http://northwinddatabase.codeplex.com/
U3T
Download
)
(.
.
Relational Databases
!
RDBMS
RDBMS Servers
DB Life Cycle
Keys
Data Integrity
Normalization
Normalization
structured
.
Relational DBMS
DBMS ) (
Excel
RDBMS
.
Spreadsheets
.. Spreadsheets !! ....
)
( .
:
) (
.
.
.
.
RDBMS
RDBMS :
: Redundancy
.
U
: Inconsistency
.
:Data Integrity
) ( .
:
.RDBMS
:
....... .
:
RDBMS .
: RDBMS
Internal Schema .
RDBMS Servers
:
. PCs
.Servers
:
PCs
PCs
) (MS Access Lotus-FoxPro-SQL Server Express
:
:
.
: GUI
SQL .
Servers
Servers
MS SQL
Server IBM DB2. Sybase
:
:
.
: Servers
..
Mirroring . Log Shipping
:
.
:
...
.
DB Life Cycle
.... .
). (Block by Block
Model
.
.
.
.
:
:One-to-One )( :
.. ).(:
: One-to-Many
...
..
.
: Many-to-Many ...
.
.
Keys
Keys
.
RDBMS : Primary Key (P.K) , Foreign Key (F.K) :
. :P.K
Unique .
: P.K
. NULL
.
.
.
U
P.K
. RDBMS
Entity Uniqueness
) (
. Candidate Key
. : Foreign Key
F.K .. ) (Unique
.. ..
.
Dept_Code .. .F.K
Data Integrity
. Entity Integrity Integrity
.Referential
Entity Integrity :
Null
Entity Integrity DBMS
) (Insert-Update .
Referential Integrity :
F.K
R.I F.K
. P.K
Normalization
Normalization
. 3NF Third Normal form
.http://en.wikipedia.org/wiki/Database_normalization
U3T
3TU
Normalization
Normalization ) (Joins
Normalization
.
...
.. ...
.
Database Queries
SQL Server 2008 T-SQL
Northwind .Adventure Works
...
:
. SQL
U
Queries
: .
.
SQL Server Management Studio
Express ) SSMSE (.
:
- SSMSE Databases .Adventure Works database
- New Query
Select * from Sales.SalesReason
* SELECT
.
CTE Common Table Expressions SQL Server 2008
SELECT , INSERT,DELET UPDATE
.
CTE
- CTE WITH.
- )(
- ) ( AS
: SSMSE
WITH TopSales (SalesPersonID,TerritoryID,NumberOfSales)
AS
(
SELECT SalesPersonID,TerritoryID, Count(*)
FROM Sales.SalesOrderHeader
GROUP BY SalesPersonID, TerritoryID
)
SELECT * FROM TopSales
WHERE SalesPersonID IS NOT NULL
ORDER BY NumberOfSales DESC
1T
1T
1T
F5
( SalesPersonID,TerritoryID,NumberOfSales) CTE
SELECT SalesPersonID,TerritoryID, Count(*)
SELECT list
. CTE
GROUP BY
Rows SELECT
GROUP BY .
SSMSE
Execute :
Use AdventureWorks
Go
'Select CardType, ExpYear,count(CardType) AS 'Total Cards
from Sales.CreditCard
)Where ExpYear in (2006,2007
group by ExpYear,CardType
order by CardType,ExpYear
group by ExpYear,CardType
ORDER BY
CardType ExpYear .
PIVOT
PIVOT
Sales.CreditCard
AdventureWorks .
GROUP BY
PIVOT .
Sales.CreditCard AdventureWorks
New Query
.Execute
Use AdventureWorks
Go
select CardType ,[2006] as Year2006,[2007] as Year2007
from
(
select CardType,ExpYear
from Sales.CreditCard
)piv Pivot
(
)]count(ExpYear) for ExpYear in ([2006],[2007
)as carddetail
order by CardType
SELECT
year2006 ,year2007
PIVOT COUNT -
ORDER BY . CardType
ROW_NUMBER
.
SSMSE Execute F5 :
select SalesPersonID, Bonus,
]ROW_NUMBER() over (order by SalesPersonID) as [RowCount
from Sales.SalesPerson
SELECT
]ROW_NUMBER() over (order by SalesPersonID) as [RowCount
) SalesPersonID
(RowCount RowCount ] [
SQL Server Key Word .
PARTITION BY
) ( ROW_NUMBER
Partitions .
F5
select CustomerID, TerritoryID ,
Row_Number() over (Partition by TerritoryID
]order by CustomerID) as [RowCount
from Sales.Customer
Where TerritoryID in (1,2) AND
CustomerID Between 1 and 75
RowCount ...
TerritoryID
RowCount .TerritoryID
:
Row_Number() over (Partition by TerritoryID
]order by CustomerID) as [RowCount
SELECT Row_Number() , over and Partition by
).Where TerritoryID in (1, 2
Pattern Matching
pattern . pattern
) % _ ( .
pattern . LIKE , NOT LIKE
.Case Sensitive Sql Server
.
) % (
C# 2010 :
'WHERE title LIKE '%C# 2010%
:
"C# 2010: An Introduction, - Accelerated C# 2010 "Beginning C# 2010 Databases
) _ (underscore
: ean
'SELECT * FROM books_db WHERE au_fname LIKE '_ean
: %
SSMSE :
select Title + ' ' + FirstName + ' ' + LastName
"as "Person Name
from Person.Contact
where FirstName like 'A%' and Title is not null
A
_ :
:
) _ ( .
] [ ):(Square Bracket
:
select Title + ' ' + FirstName + ' ' + LastName
"as "Person Name
from Person.Contact
where FirstName like '[A-I]__' and Title is not null
A I .
]^[ ):(Square Bracket and Caret
:
select Title + ' ' + FirstName + ' ' + LastName
"as "Person Name
from Person.Contact
where FirstName like '_[^i][a]__' and Title is not null
i a .
Aggregate Functions
SQL .
. .
. .AVG,MAX,MIN,SUM,COUNT
) (UnintPrice ) (SalesOrderID
.SalesOrderDetail
Execute F5 :
-:
GROUP BY .SalesOrderID
Order 1
.
: COUNT
.Person.Contact
:F5
Select count(*) as "Total Records" from Person.Contact
Select count(Title)as "Not Null Titles" from Person.Contact
DATETIME Functions
DATETIME SQL
YEAR,MONTH,DAY,HOUR,MINUTE,SECOND )(DBMS
DBMS .
T-SQL
: Execute
select
current_timestamp'standard datetime',
getdate()'Transact-SQL datetime',
datepart(year, getdate())'datepart year',
year(getdate())'year function',
'datepart(hour, getdate())'hour
SELECT FROM
select
current_timestamp'standard datetime',
getdate()'Transact-SQL datetime',
DATEPART YEAR
YEAR )(.GETDATE
) T-SQL (YEAR
)( GETDATE HOUR
'datepart(hour, getdate())'hour
DBMS !
T-SQL .
U
JOINS
.JOIN
JOIN ) (
.
joins ) (.
joins .
joins Northwind .
Inner Joins
joins
Relational Operator join ) < >(
)=( joins .natural joins
join -:
select
><select list
from
left-table INNER JOIN right-table
ON
><join specification
) ( Northwind F5
select
orders.orderid,
orders.customerid,
employees.lastname
from
orders inner join employees
on
orders.employeeid = employees.employeeid
SELECT ! ...
) (.
disambiguation
..
.
on
orders.employeeid = employees.employeeid
OredrID , CustomerID , LastName
EmployeeID
Correlation name
) (Northwind Execute
select
o.orderid,
o.customerid,
e.lastname
from
orders o inner join employees e
on
o.employeeid = e.employeeid
4T
4T
4T
4T
4T
4T
4T
4T
4T
!
Correlation name reference
) aliases
( aliases Oreders o
Employees e .
) (Northwind Execute
select
o.orderid OrderID,
c.companyname CustomerName,
e.lastname Employee
from
orders o inner join employees e
on o.employeeid = e.employeeid
inner join customers c
on o.customerid = c.customerid
4T
4T
4T
4T
4T
4T
4T
4T
4T
4T
inner join
join join .Customers
.
) inner join correlation name
.(
from
orders o inner join employees e
on o.employeeid = e.employeeid
inner join customers c
on o.customerid = c.customerid
Orders matching
.
joins
optimize
joins
. ! ..
Outer Joins
outer joins ) (
.doesn't match outer joins left outer join : right outer join :
. full outer join : left, right operand . join
left outer join join
.join right outer join join
.join full outer join .join
! !
Parent Child Referential
Integrity Parents Childs null
F.K . matching
Orders Employees .
employee Employees
.Orders .null
Execute
INSERT EmployeeID
IDENTITY NULL .
Hossam Kamal order.
orders employees
.
LEFT OUTER JOIN EMPLOYEES
F5
select
e.firstname,
e.lastname,
o.orderid
from
employees e left outer join orders o
on e.employeeid = o.employeeid
order by 2, 1
Other Joins
:Cross Join
) (
Cross Join )
.(
SSMSE SQL
Aggregate Functions GROUP BY
Joins
.
:
Insert , Update ,Delete
SELECT INTO
Inserting data
Updating data
Deleting data
SELECT .
rows tables columns
:
SELECT .
FROM / .
SELECT , FROM :
)*( asterisk .
SSMSE Northwind Execute
Select * from employees
Employees !
.
..
Resources :
New Query ..F5
4T
4T
4T
4T
EmployeeID,FirstName,LastName .Employees
..
WHERE
WHERE
Patterns .
WHERE ..
>WHERE <column1> <operator> <column2 / Value
4T
) :( SSMSE
4T
4T
4T
4T
Execute ..
=
<
>
=<
=>
><
=!
<!
>!
EmployeeID = 1
EmployeeID < 1
EmployeeID > 1
EmployeeID <= 1
EmployeeID >= 1
EmployeeID < > 1
EmployeeID != 1
EmployeeID !< 1
EmployeeID !> 1
4T
4T
4T
4T
4T
4T
4T
4T
4T
SQL
T-SQL Syntax .
LIKE ) (
:
LIKE
Pattern
Wildcards :
where firstname :
' like 'Ho% ... Hossam,Hosney
] [
] ^[
] [^a-g ][^abcde
.
null ) = (NULL
IS [NOT] NULL :
IS NULL
IS NOT NULL
)(
4T
4T
= =!..
SELECT * FROM employees WHERE Region = NULL
4T
F5 ... = IS
region ..
4T
range BETWEEN IN ..
BETWEEN
range
True
IN
True
4T
4T
Combining Predicates
Logical Operators :
True
True
NOT
OR
True
AND
4T
4T
4T
4T
.. .
Sorting Data
.
ORDER BY :
}ORDER BY <column> [ASC | DESC] {, n
> <column . } {, n
} {2,5,7,15
.ASC|DESC
. ASC
:
>SELECT <column
>FROM <table
>WHERE <predicate
ORDER BY <column> ASC | DESC
:
orders . ( employee 5)
France .Brazil
. OrederID , EmployeeID ,CustomerID, OrderDate, ShipCountry
.
.
. SQL Server Management Studio
: F5
select orderid,employeeid,customerid,orderdate,shipcountry
from orders
)'where employeeid = 5 and shipcountry in ('Brazil', 'France
order by shipcountry asc,orderdate asc
. SELECT
select orderid,employeeid,customerid,orderdate,shipcountry
FROM
WHERE :
EmployeeID
ShipCountry Brazil France
from orders
AND .
ORDER BY
ShipCountry OrderDate
U
SELECT INTO
SELECT Structure
.INTO
. BackUp
null data types constraints indexes
.triggers
-:
NorthWind : F5
select orderid,employeeid,customerid,orderdate,shipcountry
into #myorder
from orders
:
SELECT
tempdb INTO #myorder from orders
Northwind ) (# tempdb
.tempdb
SSMSE .SSMSE
:
where 0=1!
) ( table structure
tempdb Temporary
Tables refresh . refresh
SELECT
:
Inserting Data
. INSERT
WHERE ORDER
BY INSERT :
>INSERT INTO <table
)>(<column1>, <column2>, ..., <columnN
)>VALUES (<value1>, <value2>, ..., <valueN
Shipper . Northwind
SSMSE Northwind
) (+ Shippers Open Table
:
Insert
:F5
:
:
U
* SELECT :
select * from Shippers
Data Type
Character data type Integer
.
Updating Data
. UPDATE
WHERE .
:
>UPDATE <table
>SET <column1> = <value1>, <column2> = <value2>, ..., <columnN> = <valueN
>WHERE <predicate
EgyptNetwork EgyptSoftware
key ShipperId .
:
Northwind :
Update shippers
'Set companyname='EgyptSoftware
Where shipperid=4
shipperId
F5 )(1 row(s) affected
Object Explorer shippers Open Table
:
SET
:
Update shippers
Set copmanyname = 'EgyptSoftware',
'Phone='19350
Where shipperid = 4
Deleting Data
. .DELETE
UPDATE WHERE
DELETE .
DELETE :
>DELETE FROM <table
>WHERE <predicate
where .
shippers
: f5
.
) F.K (Orders
database error SSE )
(.
TRUNCATE TABLE
DELETE logging
log file DELETE .
. Operators
Stored Procedures
Stored Procedures ) (SP SQL
.
procedure .
..
.
SP C#
SP
SP
SP definitions
SP
SP C#
SP
Stored Procedures
SP Parameters
) .
(
SP C# SP . SP
Multitier Applications Web Service
Servers Requests
.
: F5 .
execute sp_Select_All_Employees
:
SP Create Procedure )
( AS Signature ) .(SQL
AS
Select
employeeid,
firstname,
lastname
from
employees
SSMS :
execute sp_Select_All_Employees
SP SQL SP .
:
_ sp T-SQL sp
T-SQL _ xp extended procedure
sp .T-SQL
U
_ sp
T-SQL sp
:
SQL Server Master
_ sp .calling
master
). (database_name.stored_procedure_name
!
master
.master
Stored Procedure
SP ID SP .
- F5 " "Command(s) completed successfully .
create procedure sp_Orders_By_EmployeeId
@employeeid int
as
select orderid, customerid
from orders
;where employeeid = @employeeid
- " " :
execute sp_Orders_By_EmployeeId 2
SQL Server .
SP CREATE PROCEDURE
@employeeid int AS int
data type where employeeid
@employeeid
where
;employeeid = @employeeid
Output Parameters SPs
C#
"".
- F5 " " Command(s) completed successfully .
Create procedure sp_Orders_By_EmployeeId2
@employeeid int,
@ordercount int = 0 output
as
select orderid,customerid
from orders
;where employeeid = @employeeid
)*(select @ordercount = count
from orders
where employeeid = @employeeid
return @ordercount
-
:
: F5
."96"
" 0" @ ordercount
Create procedure sp_Orders_By_EmployeeId2
@employeeid int,
@ordercount int = 0 output
as
select orderid,customerid
from orders
;where employeeid = @employeeid
output
);( - :
)*(select @ordercount = count
from orders
where employeeid = @employeeid
)*( count
@ordercount return
return @ordercount
COUNT INTEGER RETURN ""96
.
C#
.
Stored Procedure
sp_select_All_employees SP
:
: F5
Alter procedure sp_Select_All_Employees
as
select employeeid,firstname,lastname
from employees
order by lastname,firstname
execute :
execute sp_Select_All_Employees
ALTER PROCEDURE
Alter procedure sp_Select_All_Employees
SP Definitions
SQL SERVER .Definition of Objects
. metadata retrieval
.
:
sp_Select_All_Employees :
'Execute sp_helptext 'sp_Select_All_Employees
query Result to -> Result to text
) ( sp_helptext
Predefined SQL Server SP )( definition .
sp_helptext .
SP
sp_rename :
:
'Execute sp_rename 'sp_Select_All_Employees', 'sp_Select_Employees_Details
Execute :
!
Northwind Programmability Stored Procedures referesh
sp_Select_All_Employees sp_Select_Employees_Details
:
sp_rename
...
SP C#
C# execute
. sp_Select_Employees_Details
Consol Application CallSp1
Program.cs CallSp1.cs
CallSp1.cs
using System;
using System.Data;
using System.Data.SqlClient;
namespace CallSp1
{
class CallSp1
{
static void Main()
{
// create connection
SqlConnection conn = new SqlConnection("server=.;integrated security = true;database =
northwind.mdf");
try
{
// open connection
conn.Open();
// create command
SqlCommand cmd = conn.CreateCommand();
// specify stored procedure to execute
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_select_employees_details";
// execute command
SqlDataReader rdr = cmd.ExecuteReader();
// process the result set
while (rdr.Read())
{
Console.WriteLine(
"{0} {1} {2}"
, rdr[0].ToString().PadRight(5)
, rdr[1].ToString()
, rdr[2].ToString());
}
rdr.Close();
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
conn.Close();
}
}
}
}
: Ctrl+F5
// create command
command.type sp_select_employees_details
cmd.CommandText = CommandType.StoredProcedure
. SqlDataReader rdr =cmd.ExecuteReader();
using
using
using
using
System;
System.Data;
System.Data.SqlClient;
System.Text;
: parameters
CallSp2 Consol Application
CallSp2.cs Program.cs
CallSp2.cs
namespace Callsp2
{
class Program
{
static void Main(string[] args)
{
// create connection
SqlConnection conn = new SqlConnection(@"
server = .;
integrated security = true;
database = northwind.mdf
");
try
{
// open connection
conn.Open();
// create command
SqlCommand cmd = conn.CreateCommand();
// specify stored procedure to execute
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_orders_by_employeeid2";
// create input parameter
SqlParameter inparm = cmd.Parameters.Add(
"@employeeid", SqlDbType.Int);
inparm.Direction = ParameterDirection.Input;
inparm.Value = 2;
// create output parameter
SqlParameter ouparm = cmd.Parameters.Add(
"@ordercount", SqlDbType.Int);
ouparm.Direction = ParameterDirection.Output;
// create return value parameter
SqlParameter retval = cmd.Parameters.Add(
"return_value", SqlDbType.Int);
retval.Direction = ParameterDirection.ReturnValue;
// execute command
SqlDataReader rdr = cmd.ExecuteReader();
// process the result set
while (rdr.Read())
{
Console.WriteLine(
"{0} {1}"
, rdr[0].ToString().PadRight(5)
, rdr[1].ToString());
}
rdr.Close();
// display output parameter value
Console.WriteLine(
"The output parameter value is {0}"
, cmd.Parameters["@ordercount"].Value);
// display return value
Console.WriteLine(
"The return value is {0}"
, cmd.Parameters["return_value"].Value);
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
conn.Close();
}
: ctrl+ F5
// create input parameter
(2) ParameterDirection.ReturnValue ParameterDirection.Input /Output
: inparm.value = 2 ;
// display output parameter value
Console.WriteLine(
"The output parameter value is {0}"
, cmd.Parameters["@ordercount"].Value);
command
parameters .default values
) capital
small T-SQL (Case Sensitive
.
ADO.NET return value
. .
sp_Select_All_employees sp_Select_Employees_Details :
SQL Server
Drop procedure sp_Select_Employees_Details
DROP
DROP .
C# ADO.NET Procedure Calling
Parameters
.XML
XML
XML
XML
XML
XML documents
XML Declaration
XML
XML documents XML
XML
XML eXtensible Markup Language SGML (Standard Generalized
(Markup Language metalanguag
markup language
0T
XML XML
) (elements XML Vocabulary
Syntax Semantics ) XML Schema Definition Language (XSD
.
1996 ) (W3C XML
XHTML XML
) eXtensible Sylesheet Language (XSL
) Cascading Style Sheets (CSS HTML (XSLT) XSL Transformation
XML.
XML
XML
structured XML
semi structured unstructured SQL Server
2008 .
XML
XML platform-independent
:
self-describing XML
Root Parent
node .XML
XML .
XML .XML Schema
XML
XML Xquery .XPath
extensible .
XML
W3C .
XML
XML ) data stream
(Binary
Schema
) (childes ) (tag ) (parent :
><states
><state
><name>Dakahli</name
><city>Mansoura</city
><city>Belqas</city
></state
></states
) (root states > <states > </states
parent state parent name city XML
root attributes
name :state
><states
>"<state name="Dakahli
><city>Mansoura</city
><city>Belqas</city
></state
></states
name state .
city
) ( )> (<./
:
><states
><controlinfo count="1"/
>"<state name="Dakahli
><city>Mansoura</city
><city>Belqas</city
></state
></states
controlinfo count
> <controlinfo count="1"/ :
U
XML .
XML attributes )
(
XML XML
.
XML Declaration
XML
W3C XML Declaration XML root element
.XML
declaration
; version 1.0 , 1.1 :
>? "<? Xml version="1.0
XML
schemas namespaces
.
XML
SELECT SQL
XML FOR XML SELECT MS SQL SERVER 2008
.
FOR XML XML :
XML
Alias
Names
XML XML root
:
attributes element
ELEMENTS
FOR XML RAW :
:F5
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID between 98 and 101
FOR XML RAW,ELEMENTS
>ProductModelID="98" Name="Chain" /
>ProductModelID="99" Name="LL Crankset" /
>ProductModelID="100" Name="ML Crankset" /
>ProductModelID="101" Name="HL Crankset" /
<ProductModelDetail
<ProductModelDetail
<ProductModelDetail
<ProductModelDetail
XML element
centric attribute centric XML
PARENTS .CHILDES
SELECT Cust.CustomerID,
OrderHeader.CustomerID,
OrderHeader.SalesOrderID,
OrderHeader.Status,
Cust.CustomerType
FROM Sales.Customer Cust, Sales.SalesOrderHeader
OrderHeader
WHERE Cust.CustomerID = OrderHeader.CustomerID
ORDER BY Cust.CustomerID
FOR XML AUTO
Cust.CustomerID Cust
CustomerType Cust .
ORDER BY
Children .Parent
FOR XML AUTO
FOR XML AUTO XML .root elements
element centric attribute centric
FOR XML RAW
aliases .
xmltest XML
:execute
insert into xmltest
values(
1,
'
<states>
<state>
<abbr>CA</abbr>
<name>California</name>
<city>Berkeley</city>
<city>Los Angeles</city>
<city>Wilmington</city>
</state>
<state>
<abbr>DE</abbr>
<name>Delaware</name>
<city>Newark</city>
<city>Wilmington</city>
</state>
</states>
'
)
insert into xmltest
values(
2,
'
<states>
<state abbr="CA" name="California">
<city name="Berkeley"/>
<city name="Los Angeles"/>
<city name="Wilmington"/>
</state>
<state abbr="DE" name="Delaware">
<city name="Newark"/>
<city name="Wilmington"/>
</state>
</states>
'
)
( 1(row(s) affected))
:F5
XML xdoc :
INSERT
P.K XML .
XML C#
XML SQL Server
.
Transactions
Data Integrity
.
Transactions SQL Server 2008 C# :
Transactions
Transactions
ACID
Transactions
Transaction
Transactions
T-SQL Transaction
) (Local Transactions SQL
) (Distributed Transactions SQL
ADO.NET
Transactions
.
:
Transactions
.
Transactions
:Transactions
batch processing .
.
.
.Distributed Transactions
lock
.
concurrency .
.
:
U
transactions .
ACID
transactions ACID :
Atomicity
Consistency
Isolation
Durability
:Durability transaction
) (logging
transaction transaction log
backup transaction
.transaction log
Transactions
transactions ...
) (design transaction
:
transaction
transaction
transaction
:transactions
Retrieval transaction -
Update transaction -
Mixed transaction -
Transaction
transaction transaction
transaction aborted
committed :
) (Boundaries Transactions
:T-SQL transaction :
BEGIN TRANSACTION, COMMIT TRANSACTION, COMMIT WORK, ROLLBACK TRANSACTION,
ROLLBACK WORK, SET IMPLICIT_TRANSACTIONS
T-SQL scripts osql command
. prompt utitlity
T-SQL Transaction
T-SQL transactions :
ALTER DATABASE, RECONFIGURE, BACKUP, RESTORE, CREATE DATABASE, UPDATE
STATISTICS DROP DATABASE
sp_dboption
master tranasctions .
ALTER TABLE, CREATE, DELETE, DROP, FETCH, GRANT, INSERT, OPEN, REVOKE, SELECT,
TRUNCATE TABLE, UPDATE.
transaction COMMIT ROLLBACK
UPDATE SQL Server
.
Batch-Scoped Transactions transaction
Multiple Active Result Sets MARS transaction
ADO.NET
batch
MARS MARS
.transaction
:
roll back
.
.
.
.
transactions :SQL Server
:BEGIN TRANSACTION .
:COMMIT TRANSACTION .
:ROLLBACK TRANSACTION
.
END TRANSACTION .
T-SQL
transaction .C#
ROLLBACK , COMMIT
.
Customers Northwind transaction
null CompanyName CustomerID
CustomerID
.ID
. SQL Server Management studio
Northwind
.New Query
: F5 stored procedure
create procedure sp_Trans_Test
@newcustid nchar(5),
@newcompname nvarchar(40),
@oldcustid nchar(5)
as
declare @inserr int
declare @delerr int
declare @maxerr int
set @maxerr = 0
begin transaction
-- Add a customer
insert into customers (101ustomerID, companyname)
values(@newcustid, @newcompname)
-- Save error number returned from Insert statement
set @inserr = @@error
if @inserr > @maxerr
set @maxerr = @inserr
-- Delete a customer
delete from customers
where 101ustomerID = @oldcustid
-- Save error number returned from Delete statement
set @delerr = @@error
if @delerr > @maxerr
set @maxerr = @delerr
-- If an error occurred, roll back
if @maxerr <> 0
begin
rollback
print 'Transaction rolled back'
end
else
begin
commit
print 'Transaction committed'
end
print 'INSERT error number:' + cast(@inserr as nvarchar(8))
print 'DELETE error number:' + cast(@delerr as nvarchar(8))
return @maxerr
Execute :
:
:
Select * from Customers
.
select " "aa select
.
:
begin transaction
-- Add a customer
)insert into customers (customerid, companyname
)values(@newcustid, @newconame
-- Save error number returned from Insert statement
set @inserr = @@error
if @inserr > @maxerr
set @maxerr = @inserr
-- Delete a customer
delete from customers
where customerid = @oldcustid
-- Save error number returned from Delete statement
set @delerr = @@error
if @delerr > @maxerr
set @maxerr = @delerr
SQL Server
@@ERROR
"".
T-SQL @@ERROR
.
@@ERROR
PRINT :
-- If an error occurred, roll back
if @maxerr <> 0
begin
rollback
'print 'Transaction rolled back
end
else
begin
commit
'print 'Transaction committed
end
T-SQL ROLLBACK
.COMMIT
.
))print 'INSERT error number:' + cast(@inserr as nvarchar(8
))print 'DELETE error number:' + cast(@delerr as nvarchar(8
return @maxerr
:
" "a " "aa
delete
INSERT DELETE
error result = 0
delete
T-SQL customers
child orders .
-:
" "a " "aa
:
'exec sp_Trans_Test 'a', 'a', 'aa
2627
0
" "aa .
SQL Server
SQL Server " "aa
@maxerr .
-:
child record Orders
" "aaa " "ALFKI :
:
DELETE 547
0
" "ALFKI Orders
Select * from Customers
" "aaa .
-:
:
INSERT DELETE
2627 547 :
The statement has been terminated.
ADO.NET
sp_Trans_Test .C#
Windows Application TransTest
Form1.cs .Transaction.cs
.ADO.NET Transaction In C#
text boxes 3 3 labels :
using System.Data.SqlClient;
: button1 button1_click
SqlConnection conn = new SqlConnection(@"data source = .;integrated security = true;
database = Northwind.mdf
");
// INSERT statement
string sqlins = @"
insert into customers(customerid,companyname)
values(@newcustid, @newconame) ";
// DELETE statement
string sqldel = @"
delete from customers
where customerid = @oldcustid";
// open connection
conn.Open();
SqlTransaction sqltrans = conn.BeginTransaction();
try
{
// create insert command
SqlCommand cmdins = conn.CreateCommand();
cmdins.CommandText = sqlins;
cmdins.Transaction = sqltrans;
cmdins.Parameters.Add("@newcustid",System.Data.SqlDbType.NVarChar, 5);
cmdins.Parameters.Add("@newconame",
System.Data.SqlDbType.NVarChar, 30);
// create delete command
SqlCommand cmddel = conn.CreateCommand();
cmddel.CommandText = sqldel;
cmddel.Transaction = sqltrans;
cmddel.Parameters.Add("@oldcustid",System.Data.SqlDbType.NVarChar, 5);
// add customer
cmdins.Parameters["@newcustid"].Value = textBox1.Text;
cmdins.Parameters["@newconame"].Value = textBox2.Text;
cmdins.ExecuteNonQuery();
// delete customer
cmddel.Parameters["@oldcustid"].Value = textBox3.Text;
cmddel.ExecuteNonQuery();
// commit transaction
sqltrans.Commit();
// no exception, transaction committed, give message
MessageBox.Show("Transaction committed");
}
catch (System.Data.SqlClient.SqlException ex)
{
// roll back transaction
sqltrans.Rollback();
MessageBox.Show(
"Transaction rolled back\n" + ex.Message,"Rollback Transaction");
}
catch (System.Exception ex)
{
MessageBox.Show("System Error\n" + ex.Message, "Error");
}
finally
{
// close connection
conn.Close();
}
F5 :
" "b","bb", "bbb SQL Server "a" ,"aa", ""aaa Execute
.
transaction
transaction transaction ;)( conn.Open
: transaction
// create insert command
;)(SqlCommand cmdins = conn.CreateCommand
;cmdins.CommandText = sqlins
;cmdins.Transaction = sqltrans
;)cmdins.Parameters.Add("@newcustid", SqlDbType.NVarChar, 5
;)cmdins.Parameters.Add("@newconame", SqlDbType.NVarChar, 30
// create delete command
;)(SqlCommand cmddel = conn.CreateCommand
;cmddel.CommandText = sqldel
;cmddel.Transaction = sqltrans
;)cmddel.Parameters.Add("@oldcustid", SqlDbType.NVarChar, 5
// add customer
;cmdins.Parameters["@newcustid"].Value = textBox1.Text
;cmdins.Parameters["@newconame"].Value = textBox2.Text
;)(cmdins.ExecuteNonQuery
// delete customer
;cmddel.Parameters["@oldcustid"].Value = textBox3.Text
;)(cmddel.ExecuteNonQuery
;)( sqltrans.Commit :
)catch (System.Data.SqlClient.SqlException ex
{
//Roll back transaction
;)(sqltrans.Rollback
}
Transactions ACID
T-SQL
ADO.NET C# 2010
.