Sunteți pe pagina 1din 26

b--To read log file dbcc log(adventureworks)

-----------------------------

create database USAID on primary (name='USAID_Data', filename='c:\usaid_data.mdf',

size=10mb,

filegrowth=10%,

maxsize=20mb)

log on (name='USAID_log', filename='c:\usaid_log.ldf',

size=10mb,

filegrowth=10%,

maxsize=20mb)

go

---------------------------------------------------------------

use USAID

go

---------------------------------------------------------------

--Create table create table Test (id int, phone nvarchar(10)) go

--------------------------------------------------------------

--Alter table to add columns alter table Test add fax nvarchar(12) go

--------------------------------------------------------------

--Alter table to modify columns alter table Test alter column fax nvarchar(20)

go

--------------------------------------------------------------

--Alter table to remove columns alter table Test drop column fax

go

---------------------------------------------------------------

--Drop Table drop table Test

---------------------------------------------------------------

--Primary Key --1- One Primary Key Object is allowed per table --2- Gurantee Uniqueness of the columns --3- Create Unique Clustered index automatically --4- The column doesn't accept null values

--add Primary Key constraint during the creation of Table

--First Way create table table1 (tab1id int not null identity(1,1) primary key, firstname nvarchar(20), lastname nvarchar(20), nationalid int not null, birthdate datetime not null) go

--Second Way create table table2 (tab2id int not null identity(1,1), gender char(6), tab1id int, constraint con1 primary key(tab2id)) go

------------------------------------------------------------------

create table table3 (tab3id int not null identity(1,1), gender char(6)) go

--add primary key to an existing table alter table table3 add constraint pk_table3 primary key(tab3id) go

----------------------------------------------------------------

--add primary key with ignoe duplicates keys create table table4 (id int not null, lastname char(1)) go

alter table table4 add constraint pk_tab4 primary key(id asc) with (ignore_dup_key=on)

go

-------------------------------------------------------------------

--Default Constraint --1- Defines a default column value when no value is provided --2- Only One Default Constraint Per Column --3- Only Applicable to Insert Statement --4- Some System Supplied Functions Allowed

--add Default constraint during the creation of Table create table table5 (col1 int default(2)) go

--add Default constraint to existing column alter table table3 add constraint df_gender default 'male' for gender go

------------------------------------------------------------------------

--Check Constraint --1- Restrict the values that can be entered into the column on insert --or update --2- Can Define Multiple Check Constraints per column --3- Can Reference Columns in the same table --4- Can Not Placed On Columns with the rowversion,text,ntext,or image --data types

--add check constraint during creation of the table create table table6 (tab6id int not null, degreeper float check(degreeper between 0 and 100)) go

--add check constraint to existing column alter table table1 with check add constraint ck_birth check(birthdate > getdate()) go

--------------------------------------------------------------------------

--Unique Constraint --1- Ensure that every value in a column is unique --2- Only One Null Value Allowed in a Unique Column --3- Can Include One Or More Columns --4- Create Unique Nonclustered index automatically

create table Employee (Empid int identity(1,1) not null,

nationalidnumber nvarchar(15) not null unique, country nvarchar(30)) go

alter table Employee add constraint un_con unique(country) go

--------------------------------------------------------------

--Foreign Key --1- Ensure Referential Integrity between columns in same -- or different tables --2- The Number of Columns and data types specified in the --Foreign Key statement must match the number and data --types in the parent table --3- Must Reference a Primary Key Or Unique Constraint

--add Foreign Key during the creation of the table create table parent (parid int not null identity(1,1) primary key, parentname char(20)) go

create table child (childid int not null identity(1,1) primary key, childname char(20), parentid int foreign key(parentid) references parent(parid)) go

-------------------------------------------------------------------

--add Foreign Key during the creation of the table --With determine Cascade Options create table parent1 (parid int not null identity(1,1) primary key, parentname char(20)) go

create table child1 (childid int not null identity(1,1) primary key, childname char(20), parentid int) go

alter table child1 add constraint fk_child1 foreign key(parentid) references parent1(parid) on delete cascade on update cascade go

--------------------------------------------------------------------------------------------

--Drop Constraints alter table child1 drop constraint fk_child1 go

--------------------------------------------------------------------------------------------

--Disable Check and Foreign Key Constraints --To Improve Performance when you run large batch jobs --To avoid checking existing data when add new constraints to table

--1- Use with nocheck option to disable checking of existing data

-- When add new constraints to existing table

alter table child1 with nocheck add constraint fk_child1 foreign key(parentid) references parent1(parid) on delete cascade on update cascade

go

--2- Disable and enable Existing constraints alter table child1 nocheck constraint fk_child1 go

---------------------

alter table child1 check constraint fk_child1 go

--------------------------------------------------------------------------------

--Triggers

-----------

--1- Special stored procedures that execute when you run insert,update,or delete statements on a table --2- The trigger and the statement that fires it are treated as a single transaction, --which can be rolled back within the trigger --3- Triggers can evaluate the state of a table before and after a data modification --and take actions based on that difference --4- Multiple triggers of the same type(insert,update,delete) on a table

--5- There are 2 types of triggers --First Type---> After trigger --Second Type--> Instead Trigger

use adventureworks go

create table employees (empid int not null identity(1,1), firstname nvarchar(20), lastname nvarchar(20)) go

create table employeesHistory (empid int not null identity(1,1), firstname nvarchar(20), lastname nvarchar(20)) go

-----------------------------------------------------------------------

insert into employees(firstname,lastname) values('Mohamed','ahmed') insert into employees(firstname,lastname) values('Jacklin','Omar') insert into employees(firstname,lastname) values('Ziad','Medhat') insert into employees(firstname,lastname) values('Alaa','Medhat') insert into employees(firstname,lastname) values('Sameh','ahmed') insert into employees(firstname,lastname) values('Kareem','Mohamed')

------------------------------------------------------------------------

select * from employees select * from employeeshistory

------------------------------------------------------------------------

--Delete Trigger create trigger deldel on dbo.employees after delete as begin

insert into employeeshistory(firstname,lastname) select firstname,lastname from deleted end go

--------------------------------------------------------------------------

delete from employees where empid=5

select * from employees select * from employeeshistory

----------------------------------------------------------------------------

--Insert Trigger create trigger insertworkorder on production.workorder after insert as begin

set nocount on insert into production.TransactionHistory(productid,referenceorderid,transactiontype, transactiondate,quantity,actualcost) select inserted

.productid,inserted.workorderid,'w',getdate(),inserted.orderqty,0

from inserted

end

go

-------------------------------------------------------------------------------

--Update Trigger create trigger up on production.productreview after update as begin

SET NOCOUNT ON update production.productreview set production.productreview.ModifiedDate=getdate() from inserted where inserted.ProductReviewID=production.productreview.ProductReviewID end go

-----------------------------------------------------------------------------------

select * from production.productreview

-----------------------------------------------------------------------------------

update production.productreview set reviewername='jacklin' where

productreviewid=1

---------------------------------------------------------------------------------------

--Instead of trigger create trigger delEmployee on employees instead of delete as begin

set nocount on declare @deletecount int select @deletecount=count(*) from deleted

if(@deletecount>0)

begin

raiserror('You cannot delete from any table',16,1) rollback tran

end

end

go

---------------------------------------------------

delete from employees where empid=4

----------------------------------------------------------------------------------

----------------------------------------------------------------------------------

----------------------------------------------------------------------------------

--Module 6

--Views

-----------

--1- Is a virtual table --2- Improving Security by Grant Permissions on views instead of underlying table --3- Sensitive data can be left out of the view --4- Types of Views --Standard Views --Indexed Views --Partioned Views

--create new table create table tabview (id int not null identity(1,1), name char(10), salary money not null, birthdate datetime) go

------------------------------------------------------------------------------

--Insert data into table insert into tabview(name,salary,birthdate)

values('Mohamed',1000,'10/10/2004')

insert into tabview(name,salary,birthdate)

values('Jacklin',1000,'10/10/2004')

insert into tabview(name,salary,birthdate) values('Ziad',1000,'10/10/2004') insert into tabview(name,salary,birthdate) values('Alaa',1000,'10/10/2004') insert into tabview(name,salary,birthdate) values('Sameh',1000,'10/10/2004') insert into tabview(name,salary,birthdate)

values('Kareem',1000,'10/10/2004')

------------------------------------------------------------------------------

--Creat new view create view view1 as select name,birthdate from tabview go

--------------------------------------------------------------------------------

--Using view select * from view1

--------------------------------------------------------------------------------

--drop underlying table drop table tabview

--------------------------------------------------------------------------------

--Using view select * from view1

--------------------------------------------------------------------------------

--To Solve This Problem --create new table create table tabview (id int not null identity(1,1), name char(10), salary money not null, birthdate datetime) go

------------------------------------------------------------------------------

--Insert data into table insert into tabview(name,salary,birthdate)

values('Mohamed',1000,'10/10/2004')

insert into tabview(name,salary,birthdate)

values('Jacklin',1000,'10/10/2004')

insert into tabview(name,salary,birthdate) values('Ziad',1000,'10/10/2004') insert into tabview(name,salary,birthdate) values('Alaa',1000,'10/10/2004') insert into tabview(name,salary,birthdate) values('Sameh',1000,'10/10/2004') insert into tabview(name,salary,birthdate)

values('Kareem',1000,'10/10/2004')

------------------------------------------------------------------------------

--Alter new view and using with schemabinding option alter view view1 with schemabinding as select name,birthdate from dbo.tabview go

------------------------------------------------------------------------

--Using view select * from view1

--------------------------------------------------------------------------------

--drop underlying table drop table tabview

----------------------------------------------------------------------------------

--Using With Encryption Option select * from sysobjects where name='view1'

select * from syscomments where id=951674438

--Alter new view and using with schemabinding option alter view view1 with schemabinding,encryption

as

select name,birthdate from dbo.tabview go

-----------------------

select * from syscomments where id=951674438

----------------------------------------------------------------------------------

--Droping Views drop view view1

-----------------------------------------------------------------------------------

--Sources Of Info About Views select * from sys.views sp_helptext 'view1'

-----------------------------------------------------------------------------------

--Indexed View --1- Create View --2- Then create index on view

-----------------------------------------------------------------------------------

--Partitioned View

--1- Joins Horizontally patitiond data from a set of tables accross one or more servers --2- Using Union or Union All to combine results from all member tables --3- Types of Partitioned Views --Local Partitioned Views-->all participating tables reside on the same instance of SQL Server --Distribution Partitioned Views-->At least one of the participating tables resides on a different(remote) serve

---------------------------------------------------------------------------------------

--Stored Procedures --1- A named Collection of Transact-SQL Statements or Microsoft .NET Framework Code --2- Accepts input parameters and returns output parameter values --3- Returns status value to indicate success or failure

--Create Stored Procedure create proc production.LongLeadProducts as select name,productnumber from production.product where daystomanufacture>=1 go

--Using Stored Procedure exec production.LongLeadProducts

------------------------------------------------------------------------------

--Alter Stored Procedure alter proc production.LongLeadProducts as

select name,productnumber from production.product where daystomanufacture>=1 order by daystomanufacture desc,name go

--Using Stored Procedure exec production.LongLeadProducts

------------------------------------------------------------------------------

--Drop Stored Procedure drop proc production.LongLeadProducts

----------------------------------------------------------------------------------

--Create Stored Procedure that take input parameters create proc production.LongLeadProducts @MinimumLength int=1

as

if(@MinimumLength<0)

begin

raiserror('Invalid lead time',14,1) return

end select name,productnumber from production.product where daystomanufacture>=1 order by daystomanufacture desc,name

go

--Using Stored Procedure exec production.LongLeadProducts 4 --OR --Using Stored Procedure exec production.LongLeadProducts @MinimumLength=4

------------------------------------------------------------------------------------------

--Create Stored Procedure that take input parameters and Return Values create proc humanresources.adddepartment @Name nvarchar(50),@GroupName nvarchar(50), @DeptID smallint Output

as

if((@Name='')or(@GroupName='')) return -1

insert into humanreources.department(name,groupname) values(@Name,@GroupName)

return 0

go --Using Stored Procedure

Declare @dept int,@result int exec @result=humanresources.adddepartment 'Refunds','',@dept output

if(@result=0)

select @dept

else

select 'Error during insert'

go

----------------------------------------------------------------------------------------

--Functions

--1- Types Of Functions --Scalar Functions --Inline Table-Values Functions --Multi-Statement Table Valued Functions

--First Type -->Create Scalar Function

create function sales.sumsold (@productid int) returns int

as

begin

declare @ret int select @ret=sum(orderqty) from sales.salesorderdetail where productid=@productid if(@ret is null) set @ret=0 return @ret

end go --Using Scalar Function select sales.sumsold(774) go

----------------------------------------------------------------------------

--Second Type-->Inline Table-Values Functions

create function humanresources.EmployeesForManager (@Managerid int) returns table

as

return( select firstname ,lastname from humanresources.employee as e inner join person.contact as c on e.contactid=c.contactid

where managerid=@Managerid)

go

--Using Inline Table-Values Functions select * from humanresources.EmployeesForManager(3)

-----------------------------------------------------------------------------

--Second Type-->Multi-Statement Table-Valued Functions create function humanresources.EmployeeNames (@format nvarchar(9)) returns @tab1_Employee table (employeeid int primary key,employeename nvarchar(100))

as

begin

if(@format='SHORTNAME') insert @tab1_Employee select employeeid,lastname from humanresources.vemployee else if(@format='LONGNAME') insert @tab1_Employee select employeeid,(firstname+' '+lastname) from humanresources.vemployee

return

end go --Using Multi-Statement Table-Valued Functions select * from humanresources.EmployeeNames('LONGNAME')

---------------------------------------------------------------------------------------

--Structured Exception Handling

create procedure dbo.adddata @a int, @b int

as

--Handling Errors

begin try insert into sales.store(customerid,name) values(@a,@b) end try begin catch rollback tran select error_number() errornumber, error_message() [message]

--raiserror('aa',15,1)

end catch

go

--Execture the previous procedure exec dbo.adddata 10,'10'

-----------------------------------------------------------------------------

--Managed Stored Procedure create proc Test @a int,@b int

as

external name TestCode.[TestCode.Class1].[add]

go --By Default, execution of the user code in the .net framework --is disabled within SQL Server 2005. sp_configure 'clr enabled',1 reconfigure

--Using Managed Stored Procedure and Retrieve the result declare @x int exec @x=Test 10,10 select @x as Result

----------------------------------------------------------------

--Using XML Data

--Topic 1-- Retrieving Data By Using For XML

--Raw Mode Quieries

use adventureworks go

select cust.customerid,customertype,salesorderid from sales.customer as cust join sales.salesorderheader as [order] on cust.customerid=[order].customerid order by cust.customerid for xml raw

go

--Retrieve the same data as elements instead of attributes by specifying the Elements option

use adventureworks go

select cust.customerid,customertype,salesorderid from sales.customer as cust join sales.salesorderheader as [order] on cust.customerid=[order].customerid order by cust.customerid

for xml raw,elements

go --Retrieve the same data as elements instead of attributes by specifying the Elements option

use adventureworks go

select cust.customerid,customertype,salesorderid from sales.customer as cust join sales.salesorderheader as [order] on cust.customerid=[order].customerid order by cust.customerid for xml raw,elements

go

--Retrieve the same data by Using a root element and a customized row element name

use adventureworks go

select cust.customerid,customertype,salesorderid from sales.customer as cust join sales.salesorderheader as [order] on cust.customerid=[order].customerid order by cust.customerid for xml raw('order'),root('orders')

go

--Retrieve the same data by Using Auto Mode Quieries

--XML Representation of Data Entities --Each row returned by the query is represented by an XML Element with the same name --Each Join in the query results in nested XML Element --Each Column in the result set is represented by an attribute --To Ensure that the chid elements are collated correctly with thier parent, --Use an order by clause to return the data in the correct hierarchical order.

use adventureworks go

select cust.customerid,customertype,salesorderid from sales.customer as cust join sales.salesorderheader as [order] on cust.customerid=[order].customerid order by cust.customerid for xml auto

go

---------------------------------------------------------------

--Path Mode

SELECT

EmployeeID "@EmpID",

 

FirstName "EmpName/First",

LastName

"EmpName/Last"

FROM

Person.Contact INNER JOIN

HumanResources.Employee

ON Person.Contact.ContactID = Employee.ContactID FOR XML PATH('Employee'),root('Employees'),type

Select * From Person.Contact Select * From HumanResources.Employee

---------------------------------------------------------------------

---------------------------------------------------------------------

SELECT

EmployeeID , FirstName , LastName

FROM

Person.Contact INNER JOIN

HumanResources.Employee

ON Person.Contact.ContactID = Employee.ContactID

FOR XML Auto

------------------------------------------------------------------------

--Topic 2--Shredding XML By Using OPENXML Statement

--1-Is the process of Transforming XML Data to a rowset --2- It does this by providing a rowset view of the internal representation of an XML document --3- The records in the rowset can be stored in database tables. --4- To write queries against an XML document by using OPENXML, --you must first call sp_xml_preparedocument. This parses the XML document --and returns a handle to the parsed document that is ready for --consumption. The parsed document is a document object model (DOM) tree --representation of various nodes in the XML document. --The document handle is passed to OPENXML. OPENXML then provides --a rowset view of the document, based on the parameters passed to it. --5- OPENXML Parameters --5-1-The parameters to OPENXML include the following:

--5-2-An XML document handle (idoc) --5-3-An XPath expression to identify the nodes to be mapped to rows (rowpattern)

--5-4-A description of the rowset to be generated --5-5-Mapping between the rowset columns and the XML nodes

--5-1--XML Document Handle (idoc) --The document handle is returned by the sp_xml_preparedocument

stored procedure.

--5-2--XPath Expression to Identify the Nodes to Be Processed (rowpattern) --The XPath expression specified as rowpattern identifies a set of nodes in the XML document. --Each node that is identified by rowpattern corresponds to a --single row in the rowset that is generated by OPENXML.

--5-3-Description of the Rowset to Be Generated --A rowset schema is used by OPENXML to generate the resulting

rowset.

--5-4-Mapping Between the Rowset Columns and the XML Nodes --In the OPENXML statement, you can optionally specify the type --of mapping, such as attribute-centric or element-centric, --between the rowset columns and the XML nodes that are identified --by the rowpattern.

---------------------------------------------------------------------------------------

--Using FOR XML and OPENXML to Publish and Process XML Data

USE AdventureWorks GO SELECT Cust.CustomerID, OrderHeader.CustomerID, OrderHeader.SalesOrderID, OrderHeader.Status, Cust.CustomerType FROM Sales.Customer Cust INNER JOIN Sales.SalesOrderHeader OrderHeader ON Cust.CustomerID = OrderHeader.CustomerID FOR XML AUTO

-- create tables for later population using OPENXML. CREATE TABLE Customers (CustomerID varchar(20) primary key, ContactName varchar(20), CompanyName varchar(20))

go CREATE TABLE Orders( CustomerID varchar(20), OrderDate datetime) go

-- Prepare XMLDocument DECLARE @docHandle int declare @xmlDocument nvarchar(max) -- or xml type set @xmlDocument = N'<ROOT> <Customers CustomerID="XYZAA" ContactName="ahmed"

CompanyName="Company1">

<Orders CustomerID="XYZAA" OrderDate="2000-08-25T00:00:00"/> <Orders CustomerID="XYZAA" OrderDate="2000-10-03T00:00:00"/> </Customers> <Customers CustomerID="XYZBB" ContactName="Ali" CompanyName="IBM"> No Orders yet! </Customers> </ROOT>'

--Generate an internal tree representation of the document EXEC sp_xml_preparedocument @docHandle OUTPUT, @xmlDocument

INSERT Orders SELECT * FROM OPENXML(@docHandle, N'//Orders') WITH orders

-- Use OPENXML to provide rowset consisting of customer data. INSERT Customers SELECT * FROM OPENXML(@docHandle, N'/ROOT/Customers') WITH Customers select * From orders Customers

-- Use OPENXML to provide rowset consisting of order data.

Select * from Customers Select * from Orders

--Again DECLARE @docHandle int declare @xmlDocument xml set @xmlDocument = N'<ROOT> <Customers CustomerID="XYZAA" ContactName="ahmed"

CompanyName="Company1">

<Orders CustomerID="XYZAA" OrderDate="2000-08-25T00:00:00"/> <Orders CustomerID="XYZAA" OrderDate="2000-10-03T00:00:00"/> </Customers> <Customers CustomerID="XYZBB" ContactName="Ali" CompanyName="IBM"> No Orders yet! </Customers> </ROOT>'

EXEC sp_xml_preparedocument @docHandle OUTPUT, @xmlDocument

-- Using OPENXML in a SELECT statement. SELECT * FROM OPENXML(@docHandle, N'/ROOT/Customers/Orders') WITH (OrderDate datetime ,CustomerID nchar(5))

-- Remove the internal representation of the XML document. EXEC sp_xml_removedocument @docHandle

--------------------------------------------------------------------------------------------------

N' <Employees> <Employee EmpID="3"> <EmpName> <First>ahmed</First> <Last>Sameer</Last> </EmpName> </Employee> <Employee EmpID="4"> <EmpName> <First>Abd alrahima</First> <Last>Ahmed</Last> </EmpName> </Employee> <Employee EmpID="5"> <EmpName> <First>Attia</First> <Last>Ahmed</Last> </EmpName> </Employee> <Employee EmpID="6"> <EmpName>

<First>Osama</First>

<Last>Khalil</Last>

</EmpName>

</Employee>

</Employees>'

--Topic 3-- Using the XML Data Type

--1- The xml data type lets you store XML documents and fragments in a SQL Server database

--Reasons for Storing XML Data in SQL Server 2005 --**-- you may want to extract some of the sections within an XML document, or you may want to insert a new section without replacing your whole document --**-- You want indexing of XML data for efficient query processing

--Step 1--Creating xml Data Type Variables and Columns

--**-- The xml data type is a built-in data type in SQL Server and is somewhat similar to other built-in types such as int and varchar. --**-- As with other built-in types, you can use the xml data type as a column type when you create a table as a variable type, a parameter type, a function-return type --**--Exposes Methods To Query and Modify XML

--You can store your XML data in an xml data type column at the server. This is an appropriate choice if the following applies:

--You want a straightforward way to store your XML data at the server and, at the same time, preserve document order and document structure. --You may or may not have a schema for your XML data. --You want to query and modify your XML data. --You want to index the XML data for faster query processing.

--Example: Modeling XML Data Using the xml Data Type --Consider a product manual in XML format that is made up of a separate chapter

for

 

--each topic and that has multiple sections within each chapter. A section can

contain

 

--subsections. As a result, <section> is a recursive element. Product manuals

contain

--a large amount of mixed content, diagrams, and technical material; the data is --semi-structured. Users may want to perform a contextual search for topics of interest such as searching for the section on "clustered index" within the chapter on "indexing", and query technical quantities.

--An appropriate storage model for your XML documents is an xml data type

column.

 

--This preserves the InfoSet content of your XML data. Indexing the XML column --benefits query performance.

--Example A

CREATE TABLE T2(Col1 int primary key, Col2 xml)

--Example B

declare @x xml

--Example: Inserting Data into Untyped XML Column from File

CREATE TABLE docs (pk INT PRIMARY KEY identity(1,1), xCol XML not

null)

 

--Uses the BULK rowset provider for OPENROWSET to read data from a file --Bulk importing XML as a binary byte stream --the following INSERT statement inserts an XML instance in a single column

table.

INSERT INTO docs (xCol) SELECT xCol FROM (SELECT * FROM OPENROWSET (BULK 'C:\Doc.xml', SINGLE_BLOB) AS xCol) AS docs(xCol)

Select * From docs

-- Methods on XML Data Type

--You can retrieve entire XML values or you can retrieve parts of XML instances. This is possible by using four XML data type methods that take an XQuery expression as argument: query(), value(), exist() and nodes(). A fifth method, modify(), allows modification of XML data and accepts an XML data modification statement as input.

--

--The query() method is useful for extracting parts of an XML instance. The XQuery expression evaluates to a list of XML nodes. The subtree rooted at each of these nodes is returned in document order. The result type is untyped XML. --The value() method extracts a scalar value from an XML instance. It returns the value of the node the XQuery expression evaluates to. This value is converted to a Transact-SQL type specified as the second argument of the value() method.

--The exist() method is useful for existential checks on an XML instance. It returns 1 if the XQuery expression evaluates to non-null node list; otherwise it returns 0. --The nodes() method yields instances of a special XML data type, each of which has its context set to a different node that the XQuery expression evaluates to. The special XML data type supports the query(), value(), nodes(), and exist() methods, and can be used in count(*) aggregations and NULL checks. All other uses result in an error. --The modify() method permits modifying parts of an XML instance, such as adding or deleting subtrees, or replacing scalar values such as the price of a book from 9.99 to a 39.99.

select * from docs

--query() Method --Is used to extract XML From an XML data type

SELECT xCol.query('/Employees/Employee/EmpName/Last')

FROM

docs

--value() --extract a scalar value from XML instance

SELECT xCol.value(

'data((/Employees/Employee/EmpName)[3])', 'nvarchar(max)')

FROM

docs

--The exist() --method is useful for existential checks on an XML instance.

SELECT xCol.query('/Employees/Employee[@EmpID=3]') FROM docs WHERE xCol.exist ('/Employees/Employee/EmpName/text()="ahmed"')=1

Select xCol.exist ('/Employees/Employee/EmpName[1]/text()="ahmed"') FROM docs

--The modify() --method permits modifying parts of an XML instance --insert section after the first section UPDATE docs SET xCol.modify(' insert element Emp {"Ibrahim"} as first

into (/Employees/Employee/EmpName)[2]')

select * from Docs

--Create XML Indexes --**-- XML data is stored in an internal binary form and can be up to 2 GB

in storage.

--**-- Each query parses the XML blob at run time one or more times in

each row of the table. This makes query processing slow. --**-- To Speed up the performance of the queries on the xml columns, You create an index on this column --**-- In this case SQL Server Creates a clustered B-tree representation of nodes in the xml data and store it in an internal table

--**-- The first index on an XML column is the primary XML index

-----------------------------

--**--Primary XML Index

-----------------------------

--1-- requires a clustered index on the primary key of the base table (that is, the table in which the XML column is defined). --2-- It creates a B+tree on a subset of the Infoset items of XML nodes. Columns of the B+tree represent tags such as element and attribute names, node values, and node types. --3-- The primary key of the base table is duplicated in the primary XML index to correlate index rows with base table rows.

--Example: Creating Primary XML Index CREATE PRIMARY XML INDEX idx_xCol on docs (xCol)

--Secondary XML Indexes --Three types of secondary XML indexes—PATH, PROPERTY, and

VALUE

--The PATH index builds a B+-tree on the columns (path, value) of the primary XML index --The PROPERTY index creates a B+-tree on the columns (PK, path, value) of the primary XML index --The VALUE index creates a B+-tree on the columns (value, path) of the primary XML index

---------------------------------------------------------------------------------------------------------------------

------------------------------------------------------------

--Service Broker

--Service Broker provides queuing and reliable messaging for SQL Server. --Service Broker is used both for applications that use a single SQL Server instance --and applications that distribute work across multiple instances. --Service Broker uses TCP/IP to exchange messages between instances. --Service Broker is designed around the basic functions of sending and receiving messages. --Each message forms part of a conversation -- a reliable, persistent communication channel. --Each message and conversation has a specific type that Service Broker enforces to help developers write reliable applications. --New Transact-SQL statements allow applications to reliably send and receive the messages.

--An application sends messages to a service, which is a name for a set of related tasks. An application receives messages from a queue, which is a view of an internal table. --Messages for the same task are part of the same conversation. Within each conversation, Service Broker guarantees that an application receives each message exactly once, in the order in which the message was sent.

--

--Example --One way to understand Service Broker is to think of it as a postal service. --To hold a conversation with a distant colleague, you can communicate with letters --sent through the postal service, which sorts and delivers the letters. --You and your colleague retrieve the letters from your mailboxes, read them, --write responses, and send new letters—until the conversation has ended. Letter --delivery happens "asynchronously"—while you and your colleague handle other tasks.

--In the postal service analogy, the letters are messages. A Service Broker service --is the address to which the post office delivers the letters. Queues are the --mailboxes that hold the letters once they are delivered. Applications receive the --messages, act on the messages, and send responses.

-----------------------------------------------------------------------------------------------

--Service Broker Programming Basics

--Service Broker applications are made up of one or more programs and the database objects that --those programs use. Applications communicate by creating conversations between --independent components called services and then exchanging messages within those --conversations. Applications use Service Broker by executing Transact-SQL statements --in a SQL Server database.

--Consistes of the following --1-- Application Components --A Service Broker application is made up of:

--One or more programs that implement a task or related set of tasks.

Outside SQL Server, applications can be written in any programming environment that can run Transact-SQL statements in SQL Server. Inside SQL Server, applications can be written as stored procedures using Transact-SQL or a common language runtime (CLR) compliant language. --A service that exposes the tasks to other services. A service is a Service Broker object that provides an addressable name for a set of related tasks. Other services start conversations with this service to perform the tasks. --A contract and message types that define the structure and direction of the messages that are used in communications between the services. --A queue to hold messages for the service.

--2--Service Broker DML --Usually, an application sets up the service definition objects at the time of --installation. While running, the application sends and receives messages by --using Service Broker Data Manipulation Language (DML). The DML statements

fall

--into three broad categories: messages, conversations, and conversation groups:

Messages --Service Broker provides the following operations to support working with messages:

--

--The SEND statement sends a message on a specific conversation.

--

--The RECEIVE statement receives one or more messages from a

queue. All messages received belong to the same conversation group.

 

--

--

Conversations

--Service Broker provides the following operations to support working with conversations:

--

--The BEGIN DIALOG CONVERSATION statement begins a

conversation between two services. Because the conversation involves exactly two services, the conversation is a dialog.

--

--The END CONVERSATION statement ends one side of a

conversation.

------------------------------------------------------------------------------------

--Creating Service Broker Objects --An application uses Service Broker by executing Transact-SQL statements that --operate on Service Broker objects defined in a database. This section describes --general considerations when you create the Service Broker objects for an --application.

--Overview

--Service Broker objects define the metadata and storage for a specific set of

tasks:

--Message types define the data that is exchanged in a conversation. --Contracts define tasks. Each contract specifies the message types that can be used in a particular conversation, and which side of the conversation can send the message.

--A queue stores incoming messages for a service. --A service represents a related set of business tasks. The name of the service is also used to locate the queue for the service.

---------------------------------------------------------------------------------------

--To create the objects for a service, do the following:

--1-- Create message types that define the messages your service will use to accomplish any required communication. --2-- Create one or more contracts that define the structure of the conversations in which this service may participate --3-- Create a queue. Service Broker uses this queue to receive and store incoming messages for the service. --4-- Create a service. The service definition specifies the queue that the service uses and the contracts for which this service is the target.