Vous êtes sur la page 1sur 108

C# 2010 and MSSQL Server 2008

C# 2010 and MSSQL Server 2008

=
=
=
=
=
=
=
=
=
=
=
=
=
=

=v^=^=!^=f
=
=

C# 2010 and MSSQL Server 2008


..



100


C#
U

.
SQL Server 2008
Express
U

SQL Server 2005 2008 SQL Server


2008 R2 SQL
U

Server
SQL
Server
Stored Procedures C#
2.0 4.0
XML Transactions
ADO.NET .

ADO.NET .
.

.
.

hosam@live.co.uk

C# 2010 and MSSQL Server 2008

=^==g


Egypt Network
C#,ASP.NET,SQL Server,SharePoint ,InfoPath,XML

:
http://sharepointhero.wordpress.com/

_____________________________________________________

C# 2010 and MSSQL Server 2008

^l


..............................................................................................................................
.................................................................................................................... MS SQL Server 2008
.............................................................................................................................
.......................................................................................................................................
3T

3T

3T

3T

3T

3T

3T

3T

... ................................ ................................ ................................ Relational Databases


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

C# 2010 and MSSQL Server 2008

3T

.......................... ................................ ................................ Manipulating Database Data


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

.... ................................ ................................ ................................ Using Stored Procedures


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

....................... ................................ ................................ ................................ ................................ XML


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


3T

Transactions ........................................................................................................................
Transactions ...............................................................................................................
3T

3T

3T

3T

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008


MS SQL Server 2008

C# 2010 and MSSQL 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

..

:

C# 2010 and MSSQL Server 2008

Install :

:SQl Sevre Express

C# 2010 and MSSQL Server 2008

Next ..
Express :

I Accept the license Terms


Next :

C# 2010 and MSSQL Server 2008

Install :

C# 2010 and MSSQL Server 2008

Next :

Next Instance . Instance


:

C# 2010 and MSSQL Server 2008

Next Service Accounts )


( :

C# 2010 and MSSQL Server 2008

Next Error and Using Reporting


Next
:

C# 2010 and MSSQL Server 2008

Next :

C# 2010 and MSSQL Server 2008

close Finish :

C# 2010 and MSSQL Server 2008

Express
Visual Studio 2010

.

Northwind AdventureWorks AdventureWorks
:
3TU

http://msftdbprodsamples.codeplex.com/releases/view/37109
U3T

SQL Server

2008 Express : Northwind


3TU

http://northwinddatabase.codeplex.com/
U3T

Download
)
(.

.

C# 2010 and MSSQL Server 2008

Relational Databases

C# 2010 and MSSQL Server 2008



!
RDBMS
RDBMS Servers
DB Life Cycle

Keys
Data Integrity
Normalization
Normalization

C# 2010 and MSSQL Server 2008


structured

.

) Data Base Management System ( DBMS



)
( .... .

Relational DBMS
DBMS ) (
Excel
RDBMS
.

Spreadsheets

.. Spreadsheets !! ....

)
( .


:
) (
.

.

.


.

RDBMS
RDBMS :
: Redundancy
.
U

C# 2010 and MSSQL Server 2008

: 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
:
:

.

C# 2010 and MSSQL Server 2008

: Servers
..
Mirroring . Log Shipping
:

.
:

...
.

DB Life Cycle

.... .

). (Block by Block
Model

.

global schema : maintenance


:Requirement analysis

)
(.
:Logical design
ER diagrams .
:Physical design
Indexers .
:
) RDBMS DDL
Data Definition Language (
: Data modification Data Modification
Language DML
. Referential Integrity
:Database Monitoring

.
.

C# 2010 and MSSQL Server 2008



.
.
.

:
:One-to-One )( :

.. ).(:
: One-to-Many
...

..
.
: Many-to-Many ...


.
.

Keys

Keys
.
RDBMS : Primary Key (P.K) , Foreign Key (F.K) :

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008

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

.



...
.. ...
.

C# 2010 and MSSQL Server 2008

Database Queries

C# 2010 and MSSQL Server 2008


SQL Server 2008 T-SQL
Northwind .Adventure Works
...

QBE and SQL


SQL Server Management Studio Express
Queries

GROUP BY
PIVOT
)(ROW_NUMBER
PARTITION BY
Pattern Matching
Aggregate functions
DATETIME functions
JOINS

C# 2010 and MSSQL Server 2008

QBE and SQL


(QBE-
.(SQL

: QBE Query By Example


).(Point and Click QBE IBM
SQL SQL

.
IBM
. Forms
:SQL Structured Query Language IBM
- -
System R Codd Codd
.
SQL ANSI ISO
. SQL1
SQL3
.Object Relational DB
SQL SQL
SQL
T-SQL SQL
.Server

:
. SQL
U

C# 2010 and MSSQL Server 2008

Queries
: .
.
SQL Server Management Studio
Express ) SSMSE (.

:
- SSMSE Databases .Adventure Works database
- New Query
Select * from Sales.SalesReason

- Execute F5 Query -> Execute

C# 2010 and MSSQL Server 2008

* SELECT
.


CTE Common Table Expressions SQL Server 2008
SELECT , INSERT,DELET UPDATE

.
CTE
- CTE WITH.
- )(
- ) ( AS

C# 2010 and MSSQL Server 2008

: 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

C# 2010 and MSSQL Server 2008

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

CreditCard Sales Count

'Select CardType, ExpYear,count(CardType) AS 'Total Cards


from Sales.CreditCard
2006 2007 WHERE GROUP
BY CardType ExpYear :

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008

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 .

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008

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

) ( Sean Kean-Dean .etc _


' WHERE au_fname LIKE 'a___n ) (a ) (n
:
Allan Amman
) ] [ (square brackets ] [a-f
a f ][abcdef

'WHERE au_fname like '[C-K] arsen

arsen C K .Carsen, Darsen, Larsen, Karsen


:
^ ] [ ^a-f

U


: %
SSMSE :
select Title + ' ' + FirstName + ' ' + LastName
"as "Person Name
from Person.Contact
where FirstName like 'A%' and Title is not null

C# 2010 and MSSQL Server 2008

Title FirstName LastName Person Name


:
select Title + ' ' + FirstName + ' ' + LastName
"as "Person Name
from Person.Contact

WHERE FirstName like 'A%' and Title is not null

A
_ :
:

select Title + ' ' + FirstName + ' ' + LastName


"as "Person Name
from Person.Contact
where FirstName like 'B____a' and Title is not null

C# 2010 and MSSQL Server 2008

) _ ( .
] [ ):(Square Bracket
:
select Title + ' ' + FirstName + ' ' + LastName
"as "Person Name
from Person.Contact
where FirstName like '[A-I]__' and Title is not null

C# 2010 and MSSQL Server 2008


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

C# 2010 and MSSQL Server 2008

) (UnintPrice ) (SalesOrderID
.SalesOrderDetail

Execute F5 :

select SalesOrderID,min(UnitPrice)as "Min",


max(UnitPrice) as "Max",Sum(UnitPrice) as "Sum",
"Avg(UnitPrice)as "Avg
from Sales.SalesOrderDetail
where SalesOrderID between 43659 and 43663
group by SalesOrderID

-:

MIN MAX SUM


AVG
min(UnitPrice) as "Min",
max(UnitPrice) as "Max",
Sum(UnitPrice) as "Sum",
"Avg(UnitPrice)as "Avg

GROUP BY .SalesOrderID
Order 1
.
: COUNT

C# 2010 and MSSQL Server 2008

.Person.Contact
:F5
Select count(*) as "Total Records" from Person.Contact
Select count(Title)as "Not Null Titles" from Person.Contact

COUNT Parameter )*(COUNT


.Person.Contact
NULL Title
COUNT
! .NULL

DATETIME Functions

DATETIME SQL
YEAR,MONTH,DAY,HOUR,MINUTE,SECOND )(DBMS
DBMS .
T-SQL
: Execute
select
current_timestamp'standard datetime',

C# 2010 and MSSQL Server 2008

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',

CURRENT_TIMESTAMP SQL )( GETDATE


T-SQL .

datepart(year, getdate()) 'datepart year',
year(getdate()) 'year function',

DATEPART YEAR
YEAR )(.GETDATE
) T-SQL (YEAR
)( GETDATE HOUR
'datepart(hour, getdate())'hour

C# 2010 and MSSQL Server 2008


DBMS !
T-SQL .
U

DATETIME 3/21/2003 DBMS


DATETIME SQL .

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

join Binary Operation


left-table INNER JOIN right-table
join.
ON join .WHERE

ID .. last name employees .

C# 2010 and MSSQL Server 2008

) ( Northwind F5

select
orders.orderid,
orders.customerid,
employees.lastname
from
orders inner join employees
on
orders.employeeid = employees.employeeid

SELECT ! ...
) (.
disambiguation
..
.

FROM join inner join


from
orders inner join employees
(EmployeeId ) P.K Employees Foreign Key
) (EmployeeId . Orders

C# 2010 and MSSQL Server 2008

on
orders.employeeid = employees.employeeid
OredrID , CustomerID , LastName
EmployeeID

: EmployeeID SELECT join !!


U

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 .

C# 2010 and MSSQL Server 2008


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

CustomerID Orders CompanyName Customers


.SELECT
select
o.orderid OrderID,
c.companyname CustomerName,
e.lastname Employee

inner join
join join .Customers

C# 2010 and MSSQL Server 2008

.
) 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 into employees


(
firstname,
lastname
)
)'values ('Hossam', 'Kamal

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008

Inner Join Hossam Kamal ) (.


ORDER BY First Name , Last Name
) (1 ,2
.SUM OrderID .
left outer join right!
.. Correlation names ) (.

Other Joins

full outer join Union Join Cross Join


) (
.
:
:Full Outer Join .
:Union Join
String Memo . :
Select * from table1 union all
Select * from table2

C# 2010 and MSSQL Server 2008

:Cross Join
) (
Cross Join )
.(


SSMSE SQL
Aggregate Functions GROUP BY
Joins
.

C# 2010 and MSSQL Server 2008

Manipulating Database Data

C# 2010 and MSSQL Server 2008

:
Insert , Update ,Delete

SELECT INTO
Inserting data
Updating data
Deleting data

C# 2010 and MSSQL Server 2008


SELECT .
rows tables columns
:
SELECT .
FROM / .

: SELECT FROM .. Capital


.. SQL Case sensitive keywords
. lowercase T-SQL MS SQL SERVER
SELECT ISO/ANSI
queries and statements statements/
query SELECT
.
U

SELECT , FROM :
)*( asterisk .

>Select * from <table name


SSMSE Northwind Execute
Select * from employees

C# 2010 and MSSQL Server 2008

Employees !
.
..
Resources :
New Query ..F5
4T

Select employeeid, firstname, lastname


from employees
4T

4T

4T

4T

EmployeeID,FirstName,LastName .Employees
..

WHERE

WHERE
Patterns .
WHERE ..
>WHERE <column1> <operator> <column2 / Value
4T

C# 2010 and MSSQL Server 2008

> <operator )= > < < > (


.value
WHERE

) :( SSMSE
4T

4T

4T

'Where country = 'USA


4T

4T

Execute ..

: SQL string literals


' quotes Capital small USA
.
'

where ' 'USA


ID .

Comparison Operators WHERE


:


=
<
>
=<
=>
><
=!
<!
>!

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

C# 2010 and MSSQL Server 2008

SQL
T-SQL Syntax .

LIKE ) (
:


LIKE

Pattern

Where Title LIKE


' 'Sales%
Title
Sales
4T

Wildcards :

where firstname :
' like 'Ho% ... Hossam,Hosney

where title like '_ales' :


......Aales,bales

] [

range ] [a-f ] .[abcd:


' where title like '[b-g]ales bales , fales
.

] ^[

] [^a-g ][^abcde

.
null ) = (NULL
IS [NOT] NULL :

IS NULL

Where region IS NULL

IS NOT NULL


)(

Where region IS NOT NULL

4T

4T

= =!..

SELECT * FROM employees WHERE Region = NULL
4T

C# 2010 and MSSQL Server 2008

F5 ... = IS
region ..
4T

range BETWEEN IN ..

BETWEEN

range
True

Where extension BETWEEN 400 AND


500

IN


True

)' Where city IN ('Seattle','London


4T

4T

Combining Predicates

Logical Operators :

C# 2010 and MSSQL Server 2008

True
True

Where (title LIKE 'Sales%' AND


)'lastname = 'Peacock

NOT

Where NOT (title LIKE 'Sales%' AND


)'lastname = 'Peacock

OR

True

)'Where (title = 'peacock' OR title ='King

AND

4T

4T

4T

4T

.. .

Sorting Data


.
ORDER BY :
}ORDER BY <column> [ASC | DESC] {, n

> <column . } {, n
} {2,5,7,15
.ASC|DESC

ASC: Ascending (1, 2, 3, 4, and so on


DESC: Descending (10, 9, 8, 7, and so on

. 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

C# 2010 and MSSQL Server 2008


. SELECT
select orderid,employeeid,customerid,orderdate,shipcountry

FROM

WHERE :
EmployeeID
ShipCountry Brazil France

from orders

)'where employeeid = 5 and shipcountry in ('Brazil', 'France

AND .
ORDER BY
ShipCountry OrderDate
U

order by shipcountry asc,orderdate asc

SELECT INTO

SELECT Structure
.INTO
. BackUp

C# 2010 and MSSQL Server 2008

) hash (# (tempdb) System


. ! ...
.tempdb


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
:

C# 2010 and MSSQL Server 2008

C# 2010 and MSSQL Server 2008

SELECT INTO Table Structure



. true
.
:Northwind
select orderid,employeeid,customerid,orderdate,shipcountry
into #myemptyorder
from orders
where 0=1

where 0=1!
) ( table structure
tempdb Temporary
Tables refresh . refresh
SELECT
:

C# 2010 and MSSQL Server 2008

Inserting Data
. INSERT
WHERE ORDER
BY INSERT :
>INSERT INTO <table
)>(<column1>, <column2>, ..., <columnN
)>VALUES (<value1>, <value2>, ..., <valueN

Shipper . Northwind
SSMSE Northwind
) (+ Shippers Open Table
:

C# 2010 and MSSQL Server 2008

Insert

:F5
:

) insert into shippers ( companyname, phone


)'values ('EgyptNetwork', '+0220801756

). (1 row (s) affected


) (
ShipperID Identity
SQL Server (Companyname
( ,phone SQL Server
)'.values ('EgyptNetwork', '+0220801756

:
U

INSERT foreign key table


Related Parent Record
Shoppers P.K table Orders F.K
ShipVia ShipperID ) Shippers (
Orders .Shippers


* SELECT :
select * from Shippers

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008

shipperId
F5 )(1 row(s) affected
Object Explorer shippers Open Table
:


SET
:

Update shippers
Set copmanyname = 'EgyptSoftware',
'Phone='19350
Where shipperid = 4

C# 2010 and MSSQL Server 2008

Deleting Data
. .DELETE
UPDATE WHERE
DELETE .
DELETE :
>DELETE FROM <table
>WHERE <predicate

where .
shippers
: f5

Delete from shippers


Where shipperid = 4
) (1 row(s) affected shippers

.
) F.K (Orders
database error SSE )
(.
TRUNCATE TABLE
DELETE logging
log file DELETE .

C# 2010 and MSSQL Server 2008



. Operators

C# 2010 and MSSQL Server 2008

Using Stored Procedures

C# 2010 and MSSQL Server 2008

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
.

Stored Procedure SQL Server


SP Northwind
.SP
. SSMS ) SQL SERVER Management Studio
(Express .
. Northwind New
Query : F5

C# 2010 and MSSQL Server 2008

create procedure sp_Select_All_Employees


as
select
employeeid,
firstname,
lastname
from
employees

: F5 .
execute sp_Select_All_Employees

C# 2010 and MSSQL Server 2008

:
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

C# 2010 and MSSQL Server 2008


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

C# 2010 and MSSQL Server 2008

from orders
where employeeid = @employeeid
return @ordercount

-
:

Declare @return_value int,


@ordercount int
Execute @return_value=sp_Orders_By_EmployeeId2
@employeeId=2,
@ordercount=@ordercount output
Select @ordercount as '@ordercount'
Select 'Return value' =@return_value

: F5

."96"
" 0" @ ordercount
Create procedure sp_Orders_By_EmployeeId2
@employeeid int,
@ordercount int = 0 output

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008

execute :
execute sp_Select_All_Employees

ALTER PROCEDURE
Alter procedure sp_Select_All_Employees

OREDER BY last name . first name


order by lastname,firstname

C# 2010 and MSSQL Server 2008

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 .

C# 2010 and MSSQL Server 2008

SP

sp_rename :
:
'Execute sp_rename 'sp_Select_All_Employees', 'sp_Select_Employees_Details

Execute :

Caution: Changing any part of


an object name could break scripts and stored procedures.

!
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

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008

}
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);

C# 2010 and MSSQL Server 2008

// display return value


(Console.WriteLine
"}"The return value is {0
, cmd.Parameters["return_value"].Value
;)

command
parameters .default values


) capital
small T-SQL (Case Sensitive
.
ADO.NET return value
. .

Deleting Stored Procedure


sp_Select_All_employees sp_Select_Employees_Details :
SQL Server
Drop procedure sp_Select_Employees_Details

).(Command(s) completed successfully


Northwind
) :( Refresh

DROP
DROP .

C# 2010 and MSSQL Server 2008



C# ADO.NET Procedure Calling

Parameters
.XML

XML

C# 2010 and MSSQL Server 2008

1996 .NET XML



XML .
MS SQL Server 2008

XML
XML

XML
XML documents
XML Declaration
XML
XML documents XML

C# 2010 and MSSQL Server 2008

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 :

C# 2010 and MSSQL Server 2008

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

><controlinfo count="1"> </controlinfo

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

C# 2010 and MSSQL Server 2008

XML
schemas namespaces
.

XML
SELECT SQL
XML FOR XML SELECT MS SQL SERVER 2008

.
FOR XML XML :

FOR XML RAW


FOR XML AUTO
FOR XML PATH
FOR XML EXPLICIT

:FOR XML RAW


XML
SELECT ATTRIBUTE
.NULL
:
MS SQL Server .
AdventureWorks
.New Query
:

SELECT ProductModelID, Name


FROM Production.ProductModel
WHERE ProductModelID between 98 and 101
FOR XML RAW

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008

ELEMENTS FOR XML RAW


)element-
(centric XML .root


:FOR XML RAW
:EXECUTE
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID between 98 and 101
FOR XML RAW ('ProductModelDetail'),ELEMENTS

C# 2010 and MSSQL Server 2008

)' FOR XML RAW ('alias raw


ELEMENTS attribute centric
raw:

FOR XML RAW

>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

FOR XML AUTO


XML nested
hierarchies.
FROM SELECT XML
subelements . attribute
FOR XML AUTO

:FOR XML AUTO


AdventureWorks :execute

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

C# 2010 and MSSQL Server 2008

CustomerID Cust Cust attribute


CustomerID OrderHeader.CustomerID , OrderHeader.SaleOrderID, OrderHeader.Status
OrderHeader OrderHeader subelement Cust
.OrderHeader

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 .

XML documents XML


SQL Server 2008 Data Type ) (xml ) XML
character strings (
XML.
Parsing XML
) XML .. (DOM tree
DOM

Document Object Model XML


HTML structured documents
.
XML
.hierarchy
xml data type

.XML
U

XML ADO.NET ) SQLXML


SQL Server 2000 (XML SQL Server 2005 / 2008
XML T-SQL
.
XML
XML :
create table xmltest
(
xid int not null primary key,
xdoc xml not null

C# 2010 and MSSQL Server 2008

(Command(s) completed successfully.)


xml
xml data type SQL SQL Server
.Primary Key

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

C# 2010 and MSSQL Server 2008

Select * from xmltest

XML xdoc :

INSERT
P.K XML .


XML C#
XML SQL Server

.

C# 2010 and MSSQL Server 2008

Transactions

C# 2010 and MSSQL Server 2008


Data Integrity
.
Transactions SQL Server 2008 C# :
Transactions
Transactions
ACID
Transactions
Transaction
Transactions
T-SQL Transaction
) (Local Transactions SQL
) (Distributed Transactions SQL


ADO.NET

C# 2010 and MSSQL Server 2008

Transactions

.
:


Transactions
.

Transactions

:Transactions
batch processing .
.
.
.Distributed Transactions
lock
.
concurrency .

.

:
U


transactions .

ACID

transactions ACID :
Atomicity
Consistency
Isolation
Durability

transaction Atomicity single action


transaction
roll back order-entery Northwind
order orders order details .
Consistency transaction
data integrity transaction
Northwind Order Details
Orders .inconsistent
Isolation transaction

.

C# 2010 and MSSQL Server 2008

: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

transaction SQL Server transactions API


T-SQL :

:T-SQL transaction :
BEGIN TRANSACTION, COMMIT TRANSACTION, COMMIT WORK, ROLLBACK TRANSACTION,
ROLLBACK WORK, SET IMPLICIT_TRANSACTIONS
T-SQL scripts osql command
. prompt utitlity

C# 2010 and MSSQL Server 2008

: API DB APIs ODBC , OLE DB, ADO .NET


SQLClient namespace .transaction
transaction
ODBC API transaction T-SQL COMMIT
SQL Server ODBC transaction ODBC SQLEndTran
.transaction

T-SQL Transaction
T-SQL transactions :
ALTER DATABASE, RECONFIGURE, BACKUP, RESTORE, CREATE DATABASE, UPDATE
STATISTICS DROP DATABASE
sp_dboption
master tranasctions .

) (Local Transactions SQL


transactions transactions
transactions :
Autocommit Transactions transaction SQL Server
T-SQL
.transactions
Explicit Transactions transaction
SQL Server user-defined transaction T-SQL
BEGIN TRANSACTION, COMMIT TRANSACTION, ROLLBACK TRANSACTION:
transaction transaction
.
Implicit Transactions DML
MS SQL Server Management Studio AutoCommit
Implicit
Transaction :
SET
IMPLICIT _TRANSACTIONS ON|OFF

SQL Server transaction :

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

C# 2010 and MSSQL Server 2008

) (Distributed Transactions SQL


local transaction
Distributed Transactions resource managers
transaction manager transaction coordinator SQL Server
transaction managers ).Microsoft Distributed Transaction Coordenator (MS DTC
transaction distributed transaction
.SQL Server
transaction

two phase commit:
:Prepare Phase
durable

.
: Commit Phase


.


:

roll back

.
.

.

.


transactions :SQL Server
:BEGIN TRANSACTION .
:COMMIT TRANSACTION .
:ROLLBACK TRANSACTION
.

END TRANSACTION .

T-SQL

transaction .C#

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008


Execute :
:

' exec sp_Trans_Test 'a ', 'a ', 'z

:
Select * from Customers

Execute " "a :

C# 2010 and MSSQL Server 2008

@newcustid @newcompname " "z


customer " "aa
@oldcsutid :
' exec sp_Trans_Test 'aa ', 'aa ', 'z

.
select " "aa select
.
:

create procedure sp_Trans_Test


@newcustid nchar(5),
@newcompname nvarchar(40),
)@oldcustid nchar(5
as

declare @inserr int


declare @delerr int
declare @maxerr int
INSERT .DELETE
BEGIN TRANSACTION INSERT DELETE

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

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008

0
" "aa .
SQL Server
SQL Server " "aa
@maxerr .
-:
child record Orders
" "aaa " "ALFKI :
:

'exec sp_Trans_Test 'aaa', 'aaa' , 'ALFKI

DELETE 547
0
" "ALFKI Orders

Select * from Customers

" "aaa .
-:
:

'exec sp_Trans_Test 'a', 'a', 'ALFKI

C# 2010 and MSSQL Server 2008

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 directive :Transaction.cs

C# 2010 and MSSQL Server 2008

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

C# 2010 and MSSQL Server 2008

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
.

Vous aimerez peut-être aussi