-- XPathFunctions_ID-IDREF_BookPublisher_Complete_Script
-- Step 1
-- Switch to tempdb to prevent any "accidents" in your current database.
use tempdb
go
-- Step 2
-- Drop the BookPublisher XML Schema Collection if it already exists,
-- and then re-create it.
if (exists (
select *
from sys.xml_schema_collections
where (xml_schema_collections.[schema_id] = schema_id('dbo'))
and (xml_schema_collections.name = 'BookPublisher')
))
begin
drop xml schema collection dbo.BookPublisher
end
go
create xml schema collection dbo.BookPublisher
as
N'
'
go
-- Step 3
-- Assign the XML document to a variable and execute the queries.
-- The XML document is typed, making it possible to utilize the ID/IDREF XML Schema data types.
declare @pubs xml(dbo.BookPublisher)
set @pubs = N'
New Moon Books
Boston
MA
USA
Algodata Infosystems
Berkeley
CA
USA
The Busy Executive''s Database Guide
business
19.99
Cooking with Computers: Surreptitious Balance Sheets
business
11.95
You Can Combat Computer Stress!
business
2.99
Straight Talk About Computers
business
19.99
'
-- The XML document:
select @pubs as [BookPublisher]
-- Publishers whose books cost less than $11:
-- (Using the ID XPath function.)
begin
with xmlnamespaces
(
'http://www.w3.org/2001/XMLSchema' as xs
,'http://schemas.milambda.net/pubs' as bp
)
select Pubs.Publisher.query('bp:name').value('.', 'varchar(40)') as PublisherName
from @pubs.nodes
('
id(data(/bp:pubs/bp:titleCollection/bp:title[bp:price < 11]/@bp:publisherId))
') Pubs (Publisher)
end
-- Books published by a publisher in Berkeley:
-- (Using XQuery, because the IDREF XPath function has not been implemented in SQL Server.)
begin
with xmlnamespaces
(
'http://www.w3.org/2001/XMLSchema' as xs
,'http://schemas.milambda.net/pubs' as bp
)
select Titles.Title.query('bp:title').value('.', 'varchar(80)') as Title
from @pubs.nodes
('
for $p in /bp:pubs/bp:publisherCollection/bp:publisher
[bp:city = "Berkeley"]/@bp:publisherId
return /bp:pubs/bp:titleCollection/bp:title[@bp:publisherId = $p]
') Titles (Title)
end
go