Robyn Page and Phil Factor
XML Jumpstart Workbench
27 June 2007

/* Some of the frustration of learning XML is in not being able to see clearly an entire process. So many of the existing manuals concentrate on just one step in a chain and leave the reader saying 'very technological. So what?'

In other cases, XML is used in illustrations with tiny fragments of real data, losing sight of the great value of XML as a means of exchanging large amounts of information

We'll try to take a different approach here in order to give it all some purpose. We're not going to even try to provide anything comprehensive here, more of a quick spin around the block

OK. Let's assume that we want an application which seeks to list out the nearest hundred pubs to any postcode in Britain. (apologies to our many friends outside Britain).

We have two XML files that gives the raw data, collected from several Publicly available sources. they are supplied with the article. One gives the location of every 'outcode', and the other every pub, with their postcode. Tantalising?

In this Workbench we will
   Read an XML file into a SQL Server XML Variable
   Shred a document fragment in an XML variable into a SQL Server table
   Query a the contents of an XML variable for a set of values as an XML result
   Assign the result of a SQL query to an XML variable
   Store the contents of an XML variable to a table
   Save an XML document fragment to a file.

Let's read the XML location information from a file into a table!

Reading an XML file into a SQL Server XML Variable
--------------------------------------------------

Assume we have  the XML file unzipped in C:\workbench\locations.xml. The
files can be downloaded from the links at the top of the page in the Speech
bubble. ('UK Locations XML Xipped' and 'UK Pubs XML Zipped')
The data is over a Mb in size, so be warned! You'll need to unzip
them too! 

First pull the file into a conventional relational table... 

*/
DECLARE @xmlLocations XML
SELECT  @xmlLocations BulkColumn
FROM    OPENROWSET(BULK 'C:\workbench\locations.xml'SINGLE_BLOBAS 

/* we can store this XML data in  a table with an XML column */

CREATE TABLE xTable
    
(
      
xTable_ID INT IDENTITY
                    
PRIMARY KEY,
      
xCol XML
    
) ;

/* we then insert a row into the table from the XML variable */
INSERT  INTO xTable xCol )
        
SELECT  @xmlLocations

/*
Shredding a document fragment in an XML variable into a SQL Server table
------------------------------------------------------------------------

 now we'll put it into a conventional table for working on. First 
we define it */
CREATE TABLE [dbo].[location]
    
(
      
[location_ID] [int] IDENTITY(11)
                          NOT NULL,
      
[whereabouts] [varchar](100) NULL,
      
[Town] [varchar](80) NULL,
      
[city] [varchar](80) NULL,
      
[county] [varchar](40) NULL,
      
[region] [varchar](40) NULL,
      
[outcode] [varchar](4) NULL,
      
[x] [int] NULL,
      
[y] [int] NULL,
      
[latitude] [numeric](183) NULL,
      
[longitude] [numeric](183) NULL
    )
ON  [PRIMARY]

/* and now we can simply shred the XML data type that we've read in
into the table, using the XML Data type nodes() method.  */

INSERT  INTO location
        
(
          
whereabouts,
          
town,
          
city,
          
county,
          
region,
          
outcode,
          
x,
          
y,
          
latitude,
          
Longitude
        
)
        
SELECT  x.location.value(
                    
'whereabouts[1]''varchar(100)'AS whereabouts,
                
x.location.value(
                    
'town[1]''varchar(80)'AS town,
                
x.location.value(
                    
'city[1]''varchar(80)'AS city,
                
x.location.value(
                    
'county[1]''varchar(40)'AS county,
                
x.location.value(
                    
'region[1]''varchar(40)'AS region,
                
x.location.value(
                    
'outcode[1]''varchar(4)'AS outcode,
                
x.location.value(
                    
'x[1]''int'AS x,
                
x.location.value(
                    
'y[1]''int'AS y,
                
x.location.value(
                    
'latitude[1]''numeric(18, 3) 'AS latitude,
                 
x.location.value(
                    
'longitude[1]''numeric(18, 3)'AS longitude
        
FROM    @xmlLocations.nodes('//locations/location'
                                    
AS location )

/* now we can try it out by finding the nearest places to a particular 
postcode*/
GO

CREATE PROCEDURE spWhereIsThis @Postcode VARCHAR(10)
/*
spWhereIsThis 'cm2'
*/
AS 
    DECLARE 
@x INT,
        
@y INT


    SELECT TOP 
1--find out our coordinates
            
@x x,
            
@y y
    
FROM    location
    
WHERE   outcode LIKE RTRIM(LEFT(SUBSTRING(@Postcode1,
                              
CHARINDEX(' '@Postcode ' ',
                                                 
1) - 1), 4))
    
IF @@Rowcount --typo!
        
BEGIN
            RAISERROR 
'I don''t recognise the postcode ''%s'''161,
                
@postcode )
            
RETURN 1
        
END

    SELECT TOP 
100--list the 100 nearest locations
            
whereabouts,
            
region,
            
[miles] ROUND(SQRT(SQUARE(@X) + SQUARE(@Y)) 
                       * 
0.0006214,0)
    
FROM    location
    
WHERE   IS NOT NULL
    
ORDER BY miles
GO

/*
   Querying the contents of an XML variable for a set of values as an XML result
    ----------------------------------------------------------------------------

we can extract data directly from the XML column if we wish
*/
SELECT  xCol.query('
   for $LOC in /locations/location
   where $LOC/outcode[.="CM2"]
   return
     <coordinate>
      { $LOC/x }
      { $LOC/y }
      { $LOC/town }
     </coordinate>
'
AS Result
FROM    [XTable]

/* but as the XQUERY string must be a string literal and not a 
string variable, we need to put parameters in via a sql:variable
parameter like this....*/

DECLARE @Postcode VARCHAR(10)
SELECT  @Postcode 'CO8'

SELECT  xCol.query('
   for $LOC in /locations/location
where $LOC/outcode = sql:variable("@Postcode") 
   return
     <locations>
      { $LOC/whereabouts }
      { $LOC/county }
     </locations>
'
AS Result
FROM    [XTable]


/* Now, this is an open-ended workbench. You have a nice large
source of data, and BOL is now screaming at you to be read. Try
out some FLWOR!

When you tire, it is time to  pull in a list of british pubs.  */

DECLARE @xmlPubs XML
SELECT  @xmlPubs BulkColumn
FROM    OPENROWSET(BULK 'C:\workbench\pubs.xml'SINGLE_BLOBAS 

CREATE TABLE dbo.Pub
    
(
      
Pub_ID INT IDENTITY(11)
                 NOT NULL,
      
[Name] VARCHAR(30) NOT NULL,
      
Address VARCHAR(100) NOT NULL,
      
outcode VARCHAR(4) NOT NULL,
      
INT NULL,
      
INT NULL
    )
ON  [PRIMARY]

INSERT  INTO Pub
        
(
          
[name],
          
address,
          
outcode
        
)
        
SELECT  x.pub.value('name[1]''varchar(30)'),
                
x.pub.value('address[1]''varchar(100)'),
                
RTRIM(LEFT(
                     
SUBSTRING(x.pub.value('postcode[1]''varchar(10)'),
                                     
1,
                                     
CHARINDEX(' ',
                                               
x.pub.value('postcode[1]',
                                                           
'varchar(10)')
                                               + 
' '1) - 1), 4
                    
))
        
FROM    @xmlPubs.nodes('//pubs/pub'AS pub )

UPDATE  pub
SET     f.xf.y
FROM    pub
        
INNER JOIN location f ON pub.outcode f.outcode


CREATE PROCEDURE spNearestPubs @Postcode VARCHAR(10)
/*
spNearestPubs 'co10'
*/
AS 
    DECLARE 
@x INT,
        
@y INT


    SELECT TOP 
1--find out our coordinates
            
@x x,
            
@y y
    
FROM    location
    
WHERE   outcode LIKE RTRIM(LEFT(SUBSTRING(@Postcode1,
                                         
CHARINDEX(' '@Postcode ' ',
                                                            
1) - 1), 4))
    
IF @@Rowcount --typo!
        
BEGIN
            RAISERROR 
'I don''t recognise the postcode ''%s'''161,
                
@postcode )
            
RETURN 1
        
END

    SELECT TOP 
100--list the 100 nearest locations
            
name ' ' address,
            
[miles] ROUND(
                           
SQRT(SQUARE(@X) + SQUARE(@Y))
                           * 
0.0006214,0)
    
FROM    pub
    
WHERE   IS NOT NULL
    
ORDER BY miles
GO

/*
   Assigning the result of a SQL query to an XML variable
    ------------------------------------------------------

 well, nice as far as it goes, but why not pass the result back as
an XML variable, and we'll then we can save it direct to disk, or
send it happily to an application, store it in a table as a variable?

XML could be quite handy!
*/ 
CREATE PROCEDURE spNearestPubsXML
    
@Postcode VARCHAR(10),
    
@XMLPubList XML OUTPUT
/*
e.g.
Declare @PubList xml
execute spNearestPubsXML 'co10',   @XMLPubList=@PubList output
Select @PubList
*/
AS 
    DECLARE 
@x INT,
        
@y INT


    SELECT TOP 
1--find out our coordinates
            
@x x,
            
@y y
    
FROM    location
    
WHERE   outcode LIKE RTRIM(LEFT(SUBSTRING(@Postcode1,
                                        
CHARINDEX(' '@Postcode ' ',
                                                           
1) - 1), 4))
    
IF @@Rowcount --typo!
        
BEGIN
            RAISERROR 
'I don''t recognise the postcode ''%s'''161,
                
@postcode )
            
SET @XMLPubList '<pubs />'
            
RETURN 1
        
END

    SET 
@XMLPubList SELECT TOP 100--list the 100 nearest locations
                                
[name] name ', ' address,
                                
[miles] CONVERT(INT
                                            
ROUND(SQRT(
                                               
SQUARE(@X
                                               + 
SQUARE(@Y))
                                            * 
0.00062140))
                        
FROM    pub
                        
WHERE   IS NOT NULL
                        
ORDER BY miles
                      
FOR
                        
XML PATH('pub'),
                            
ROOT('pubs'),
                            
TYPE
                      
)
GO
--we can then save the results to disk very easily
DECLARE @PubList XML
EXECUTE spNearestPubsXML 'BR2'@XMLPubList @PubList OUTPUT

-- We Store the contents of an XML variable to a table
CREATE TABLE xNearestPubs
    
(
      
xPubs_ID INT IDENTITY
                   
PRIMARY KEY,
      
xCol XML
    
) ;

INSERT  INTO xNearestPubs xCol )
        
SELECT  @PubList

/*
   We Save an XML value to a file.
*/
DECLARE @Command VARCHAR(255)
DECLARE @Filename VARCHAR(100)

SELECT  @Filename 'C:\workbench\Nearestpubs.xml'
/* we then insert a row into the table from the XML variable */
/* so we can then write it out via BCP! */
SELECT  @Command 'bcp "select xCol from ' DB_NAME()
        + 
'..xNearestPubs" queryout ' 
       
@Filename ' -w -T -S' @@servername
EXECUTE master..xp_cmdshell @command
--so now the xml is written out to a file

/*
So there we have it. Hopefully, if you enjoyed this approach to XML by
example, we'll try out more complex examples in further Workbenches.

In the meantime, there are other resources on the Simple-Talk ;site ...;
Beginning SQL Server 2005 XML Programming
Srinivas Sampath 21 February 2006
XML has been used to represent semi-structured (as well as unstructured) data such as documents and emails. If information in these models has to be queried, then XML is probably the simplest way to represent such information. Read more...
Understanding XML web services for testers
Helen Joyce - 13 April 2003
This White Paper investigates how XML web services are implemented, considers the customizable features of web services and looks at load testing a web service, specifically so that test strategies can be formulated. Read more...
XML and RDBMS: 10 years on
Jim Fuller - 25 August 2006
As we approach the 10-year anniversary of XML Jim Fuller provides a personal retrospective, focussing on how XML has been and will be used with the RDBMS. Read more...
SQL Server XML Cribsheet
Robyn Page
- 29 March 2007
If you find XML a bit of an acronym minefield, Robyn's Cribsheet will help sort out your XSLT from your XDM. Read more...

and we would also
recommend you to read Jacob Sebastian's excellent articles....

...on SQL Server Central

 



This article has been viewed 13584 times.
Robyn Page and Phil Factor

Author profile: Robyn Page and Phil Factor

Robyn Page is a consultant with Enformatica and USP Networks. She is also a well known actress, being most famous for her role as Katie Williams, barmaid in the Television Series Family Affairs.

Phil Factor (real name withheld to protect the guilty), aka Database Mole, has 20 years of experience with database-intensive applications. Despite having once been shouted at by a furious Bill Gates at an exhibition in the early 1980s, he has remained resolutely anonymous throughout his career.

Search for other articles by Robyn Page and Phil Factor

Rate this article:   Avg rating: from a total of 23 votes.


Poor

OK

Good

Great

Must read
 
Have Your Say
Do you have an opinion on this article? Then add your comment below:


Subject: Top stuff
Posted by: Dan Kennedy (view profile)
Posted on: Friday, June 29, 2007 at 2:24 AM
Message: I've done a fair bit of the postcode/coordinate/nearest stuff before but I've never used the OPENROWSET, BULK method to open a file. Brilliant !!

And if that wasn't enough the sample data is also excellent. I've been looking for a list of postcode/coordinate data for a while. Is the stuff here available from somewhere ? updated regularly ?

Subject: re: top stuff
Posted by: Robyn Page (view profile)
Posted on: Friday, June 29, 2007 at 3:20 AM
Message:

Sadly not. All done laboriously some years ago, in both cases, and cannot be used commercially but great for this sort of work.

Thanks for the comments on the article. Much appreciated. Phil is rather pleased with the BCP method of saving the XML fragment to file using queryout. Can it be done wothout using a permanent table?


Subject: Is Robyn Page for real ??!!??
Posted by: Anonymous (not signed in)
Posted on: Saturday, June 30, 2007 at 1:34 AM
Message: TV star and a Software Geek .. hard to believe..maybe she has a geeky boyfriend RedGate who comes up with these articles to make her look supernatural !! wat say folks ??

Subject: Re: Is Robyn Page for real ??!!??
Posted by: Robyn Page (view profile)
Posted on: Saturday, June 30, 2007 at 2:50 AM
Message: Was a TV star, not any more, I'm afraid. Married too. And, did you get your girlfriend to write the comment?

Subject: Robyn is for real !!
Posted by: Anonymous (not signed in)
Posted on: Monday, July 02, 2007 at 7:44 AM
Message: Hi !! did not mean to put you down ..
i have read a few articles of yours and they are very well written.
So are you a full time Techie now ??

Subject: Re: Robyn is for real
Posted by: Phil Factor (view profile)
Posted on: Monday, July 02, 2007 at 11:57 AM
Message: On Robyn's behalf, may I just say that she is currently on maternity leave from a job working for a City of London Financial Services company. I've been helping her with her writings, as you'll notice from the head of this article. Now back to XML......

Subject: Child Elements
Posted by: Anonymous (not signed in)
Posted on: Thursday, July 05, 2007 at 2:49 PM
Message: Hi There,

This has been of great help. Just one thing I'm stumbling on. What if I need to import a child of a child element into the same row.

For example, in your locations example. if the xml sample is:

<locations>
<location>
<whereabouts>
<town>Prehen Park</town>
<city>Londonderry</city>
</whereabouts
<county>County Londonderry</county>
<region>Northern Ireland</region>
</location>
</locations>

In the above the <whereabouts> has two child nodes, and I want to import those into the table into the SAME row as the other info. For example, one row of data would be: town, city, county, and region. What would the sql insert into-select statement be when the town and city are child nodes?

Thanks!
kc

Subject: Child elements
Posted by: Dan Kennedy (view profile)
Posted on: Friday, July 06, 2007 at 1:58 AM
Message:

kc, you can extend Robyn's sample and simply reference the child elements through a different xpath expression like this (Don't forget to fix the missing close bracket on the whereabouts element in your sample xml ;)) :



SELECT x.location.value
         
'whereabouts[1]/town[1]''varchar(100)'AS whereaboutstown
       
x.location.value
         
'whereabouts[1]/city[1]''varchar(100)'AS whereaboutscity
       
x.location.value
         
'county[1]''varchar(80)'AS county
       
x.location.value
         
'region[1]''varchar(80)'AS region
FROM @xml.nodes('locations/location'AS x(location)

Subject: re: Child elements
Posted by: Phil Factor (view profile)
Posted on: Friday, July 06, 2007 at 3:08 AM
Message: Thanks, Dan. That is a great help.
The coordinates in the locations XML would also be much neater as
  <coordinate>
    <x>3948</x>
    <y>267</y>
  </coordinate>
likewise latitude/longitude.
Robyn and I were wondering whether to do it this way but we decided that we wanted to keep everything plain and simple for this workbench!

Subject: Great Article
Posted by: Anonymous (not signed in)
Posted on: Friday, July 06, 2007 at 5:27 AM
Message: Well done Robyn! (we all know that Phil doesn't really contribute :))

In all seriousness, it was a great article. As something I haven't used much, but get asked about occasionally, this was a great starting point.

Subject: Extended Query Time - inserting records from XML variable
Posted by: Eric Flamm (not signed in)
Posted on: Friday, July 06, 2007 at 9:14 AM
Message: Did anyone else experience very long processing time to insert the rows from @XMLLocations into the Location table - I let the query run for 20 minutes or more before killing it. Even inserting just 100 records (Select Top 100) is taking many minutes.

This seems odd to me - any ideas?

Subject: Re: Extended Query Time
Posted by: Robyn Page (view profile)
Posted on: Friday, July 06, 2007 at 10:11 AM
Message: Yes. Odd. It took a few seconds when we did it. we were surprised how quick it was. Puzzled. Have you tried taking out any indexes?

Subject: Re: Extended Query Time
Posted by: Anonymous (not signed in)
Posted on: Friday, July 06, 2007 at 11:50 AM
Message: Thanks Dan for the help with the child elements. That was very helpful!

I too am experiencing the slowness issue. I don't have any indexes defined as far as I'm aware. I took the sample data and query right off the site to test.

I'm using SQL Server 2005. Any ideas

Subject: Re: Extended Query Time
Posted by: Anonymous (not signed in)
Posted on: Friday, July 06, 2007 at 1:03 PM
Message: Thanks Dan for the help with the child elements. That was very helpful!

I too am experiencing the slowness issue. I don't have any indexes defined as far as I'm aware. I took the sample data and query right off the site to test.

I'm using SQL Server 2005. Any ideas

Subject: Trouble loading the XML file into Location
Posted by: David B (not signed in)
Posted on: Monday, July 09, 2007 at 12:32 PM
Message: The INSERT into the LOCATION table never seems to end. Watching the connection through SP_WHO2. I saw only the CPU count going up. The disk count stayed at 763.

I've tried 2 free XML editors trying to read the file. One never finished reading the file. The other said it could not find the file after tring to read it.

Could I have the wrong MXSML6 file? I am in the USA and would not be surprised Microsoft released a slightly different version in England.

Subject: Re: Extended Query Time (KnownIssue + Workaround)
Posted by: Michael Brönnimann (not signed in)
Posted on: Wednesday, July 25, 2007 at 10:35 AM
Message: The long query time in the context of combination of INSERT INTO .. SELECT FROM @xml.node is a known issue, which hopefully will be solved with an upcoming service pack:
https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=250407

Suggested workaround

1) create linked server, which points to own server instance

2) modify INSERT INTO to use FROM OPENQUERY as follows.

with best regards
michael.broennimann@ibax.ch
--------------------

INSERT INTO location
(
whereabouts,
town,
city,
county,
region,
outcode,
x,
y,
latitude,
Longitude
)

SELECT * FROM OPENQUERY(SERVER_MYSELF,'
DECLARE @xmlLocations XML
SELECT @xmlLocations = BulkColumn
FROM OPENROWSET(BULK ''C:\Documents and Settings\Michael\Desktop\locations.xml'', SINGLE_BLOB) AS x

SELECT x.location.value(
''whereabouts[1]'', ''varchar(100)'') AS whereabouts,
x.location.value(
''town[1]'', ''varchar(80)'') AS town,
x.location.value(
''city[1]'', ''varchar(80)'') AS city,
x.location.value(
''county[1]'', ''varchar(40)'') AS county,
x.location.value(
''region[1]'', ''varchar(40)'') AS region,
x.location.value(
''outcode[1]'', ''varchar(4)'') AS outcode,
x.location.value(
''x[1]'', ''int'') AS x,
x.location.value(
''y[1]'', ''int'') AS y,
x.location.value(
''latitude[1]'', ''numeric(18, 3) '') AS latitude,
x.location.value(
''longitude[1]'', ''numeric(18, 3)'') AS longitude

FROM @xmlLocations.nodes(''//locations/location'')
AS x ( location )
')

Subject: Re: Extended Query Time (KnownIssue + Workaround)
Posted by: Phil Factor (view profile)
Posted on: Wednesday, August 01, 2007 at 2:45 AM
Message:

Michael's code put through the Refactor/Prettifier combination ...



INSERT  INTO location
     
whereaboutstowncitycountyregionoutcodexylatitude,
        
Longitude )
      
SELECT  *
        
FROM    OPENQUERY(SERVER_MYSELF'
DECLARE @xmlLocations XML
SELECT  @xmlLocations = BulkColumn
FROM    OPENROWSET
     (BULK ''C:\Documents and Settings\Michael\Desktop\locations.xml'',
                   SINGLE_BLOB) AS x 

SELECT  
   x.location.value(''whereabouts[1]'', ''varchar(100)'') AS whereabouts,
   x.location.value(''town[1]'', ''varchar(80)'') AS town,
   x.location.value(''city[1]'', ''varchar(80)'') AS city,
   x.location.value(''county[1]'', ''varchar(40)'') AS county,
   x.location.value(''region[1]'', ''varchar(40)'') AS region,
   x.location.value(''outcode[1]'', ''varchar(4)'') AS outcode,
   x.location.value(''x[1]'', ''int'') AS x,
   x.location.value(''y[1]'', ''int'') AS y,
   x.location.value(''latitude[1]'', ''numeric(18, 3) '') AS latitude,
   x.location.value(''longitude[1]'', ''numeric(18, 3)'') AS longitude
FROM
    @xmlLocations.nodes(''//locations/location'') AS x ( location )
'
)

Thanks for that, Michael. This was causing us a lot of headscratching, as it worked fine on all our servers.


Subject: Re: Is Robyn Page for real ??!!??
Posted by: Anonymous (not signed in)
Posted on: Friday, August 10, 2007 at 4:00 PM
Message: Just as Phil Factor and his image are contrived, so it seems for Robyn Page.

How else to explain the bare shouldered, vampy picture? Does she tilt her head and pout provocatively at code reviews? I doubt so.

In any case, Robyn and Phil's articles (particularly the workbenches) are always quite good and appreciated. Thanks you two, whoever you are!

Subject: retrieving from relative and static xml nodes
Posted by: Anonymous (not signed in)
Posted on: Friday, August 31, 2007 at 11:59 AM
Message: I need to retrieve both the value for all relative nodes in an xml, but then I also need to identify when that path is from a particular node. For example, see the snippet of my code:

select
x.location.value( 'locations[1]/location[1]/header[1]/RecordId[1]', 'varchar(100)') AS HeaderRecordID,
x.location.value( 'locations[1]/location[1]/subHead[1]/RecordId[1]', 'varchar(100)') AS subHeadRecordID,
x.location.value( 'RecordId[1]', 'varchar(100)') AS RecordID,
into TEST
FROM @xmlLocations.nodes('location/locations/*')
AS x ( location )


Different nodes have the RecordiD child element. I am using the relative path in the from statement to retrieve all RecordID values from all elements. But I want to be able to identify when the RecordID is coming from the header tag or from a subhead tag. I don't care about other tags that the RecordId may be retrieved from.

Any advice as to how I can do this?
Thanks!

Subject: Using the alternate for xml insert...
Posted by: Winston (view profile)
Posted on: Monday, December 10, 2007 at 6:45 AM
Message: hello guys,
greate article... I started working through this article but am having some difficulties. Firstly I have had the same issue with the long running time on insert of xml into the locations table (over 35 mins) so I killed it.
The suggested workaround is to created a linked server which points to my own server instance before using the alternate script. However SQL2005 won't allow me to create such a link to the local server.
Can anyone help clarify this for me? I thought it would have been pretty straight forward but I guess being a newbie...

Thanks in advance

Subject: Re: Using the alternate for xml insert...
Posted by: Winston (view profile)
Posted on: Monday, December 10, 2007 at 6:58 AM
Message: Hi Guys me again,
Please disregard last post from me. I solved the issue myself.
Apparently I was trying to use the wrong technique for created the linkedserver (and a bit too hasty in seeking help :)). The stored proc for linking works when done by specifying the provider name 'SQLNCLI' along with the default which is ONLY the name of the server.

And so I continue on... great site and have a good day.

Subject: Thanks
Posted by: MG (not signed in)
Posted on: Tuesday, April 29, 2008 at 8:41 AM
Message: At last a clear "workshop"
I am Now able to load lots of bulk xml data into a relational database and find a lot of pubs in the UK as well ;-)


i searched weeks for this


Subject: Saved XML with random line-feeds
Posted by: DavidB (view profile)
Posted on: Thursday, June 19, 2008 at 10:51 AM
Message: I was overjoyed to find the creative use of xp_cmdshell and bcp to dump SP result set to an XML file.

I was able to get the mechanics working OK. However, the XML file that is produced is not well-formed. Despite trying all the bcp switches for -c (character) -n (native) and -w, the XML file contains a line-feed character where it should not.

The SP uses FOR XML syntax to produce what is otherwise a valid XML document.

Is there a combination of bcp switches I'm missing here?

Subject: SQL data into XML Type
Posted by: Simon LineBarger (not signed in)
Posted on: Wednesday, July 02, 2008 at 9:55 AM
Message: I was saving this until I really needed Article!
Great - Tnx

But How do I get 'standard' SQL data types into 'xml' data type! Currntly use
snippet:
INSERT INTO [dbo].[fs_invoice]
( [Tag], [Parent], [Invoices!1!!hide],
[Invhead!4!invno],
[Invhead!4!traid],
[Invhead!4!tname!element],
[Invhead!4!ourid!element],
[Invhead!4!taxdt],...........
etc to 'BUILD sql invoice Table

THEN THROUGH SQL_Server AGENT, xp_cmdshell
bcp SELECT * FROM fs_invoice WHERE [Invoices!1!!hide] = '???' ORDER BY 1,2 FOR XML EXPLICIT" queryout E:\Formscape\???.xml
FOR PRINTING

-- this has been working well, for ages BUT I would like to add a field of XML datatype to my Invoices Table, and on Creation of NEW invoice row, populate xml datatype with output ready for Printer Programme, then I can save this for repeat prints/document management

The article shows how I can get XML data back from bcp output file for population of XML datatype, but this seems v.long winded!

Subject: OOPS
Posted by: Simon LineBarger (not signed in)
Posted on: Wednesday, July 02, 2008 at 10:16 AM
Message: I'ad crashed & burned 75% thru article

The last 25% may do the trick

Enter your comment here:

  Name: 
  Subject: 
  Message: 
 
 









Phil Factor
The Wrong Fabia
 There is often more than a twinge of embarrassment when an Email goes astray, and is received by the wrong person.... Read more...



 View the blog
Investigating SQL Server 2008 Wait Events with XEVENTS
 Some reasons for the slow-running of database applications aren't obvious. Occasionally, even the... Read more...</