5,702,921 members and growing! (21,304 online)
Email Password   helpLost your password?
Web Development » Web Services » General     Intermediate

Serving SQL XML through a WebService (SQL2005)

By Russ Quinn

How to server XML from SQL2005 through a WebService
SQL, C# 2.0, C#Windows, .NET, .NET 2.0, WinXP, ASP.NET, WebForms, SQL 2005, VS2005, SQL Server, Visual Studio, DBA, Dev

Posted: 4 Feb 2007
Updated: 4 Feb 2007
Views: 20,877
Bookmarked: 39 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
8 votes for this Article.
Popularity: 4.02 Rating: 4.45 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
1 vote, 12.5%
3
2 votes, 25.0%
4
5 votes, 62.5%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

I recently needed to create a feed for a customer from some data held within SQL Server so looked around for the best (and quickest) way to do this. Knowing that I use SQL 2005 and that XML was an intregal part of it, I looked at ways to leverage this.

After some thought I came up with the idea of serving XML from the database and creating a WebService that the customer can call whenever they need some data (with some parameters if required).

Now, I know you're all saying "This is nothing new or difficult" and that's exactly the point of writing this article. It is easy and as such may be easily overlooked. I couldn't believe how simple it was and there didn't seem to be any other articles on CodeProject telling anyone how to solve this.

Using the code

Firstly, using your SQL 2005 database (with some data already in it), create a stored procedure like so

CREATE PROCEDURE [dbo].[GetStories]
    @fromDate datetime,
    @toDate datetime
AS 
    BEGIN
 
        select  dbo.Story.id,
                description,
                notes,
                text,
                publicationdate,
                authorsnames,
                keywords
        from    dbo.Story
                inner join dbo.Status on dbo.Story.StatusId = dbo.Status.id
        where   publicationdate between @fromDate and @toDate
                and dbo.Status.status = 'live'
        order by publicationDate
        FOR     XML PATH('story'),
                    ROOT('stories')
    END

The key to this step is the FOR XML PATH(###), ROOT(###) part. This tells SQL Server to return XML with each row having the element name of story and the root of the XML document to be stories

Next, create a normal WebService using the usual project options and add a new WebMethod. In this method, connect to the database and get the data.

Now, as I want XML back I call the ExecuteXmlReader method on the SqlCommand class like so:

  XmlReader reader = command.Command.ExecuteXmlReader();

This reader can then be streamed into an XmlDataDocument which can then be returned from the WebMethod. Below is my copy of the WebMethod, where you'll notice a simple Database class and App_Data.SqlSPCommand to simplify the calls to the database

[WebMethod(Description = "Get stories based on a centre, and a from and to date",
CacheDuration = 600, MessageName = "GetStoriesForCentre")]
public XmlDataDocument GetStoriesForCentre(string centre, DateTime fromDate, DateTime toDate)
{
 Database db = new Database("TarkStoriesConnectionString");
 
 using (db.Connection)
 {
  db.OpenConnection();
 
  App_Data.SqlSPCommand command = new App_Data.SqlSPCommand("GetStoriesForCentre", db.Connection);
  command.AddParameter("@centre", SqlDbType.VarChar, centre);
  command.AddParameter("@fromDate", SqlDbType.DateTime, fromDate);
  command.AddParameter("@toDate", SqlDbType.DateTime, toDate);

  XmlReader reader = command.Command.ExecuteXmlReader();
 
  XmlDataDocument xml = new XmlDataDocument();
  xml.Load(reader);

  return xml;
 }
}

And that's it.....

Call the WebService in the normal way, supply some query string parameters (in my example 2 dates) and you should get some XML back like so:

<?xml version="1.0" encoding="utf-8" ?>
<stories>
    <story>
        <id>514</id>
        <description>some description</description> 
        <notes>no notes available</notes> 
        <text>blah blah blah</text> 
        <publicationdate>2007-01-30T00:00:00</publicationdate> 
        <authorsnames>Sue Williams</authorsnames>
        <keywords>boring story</keywords>
    </story>
</stories>

You may want to tidy up the loading of the XmlReader into the XmlDataDocument class by first checking to see if there is any content (use MoveToContent and check the result), but for now i'll leave that up to you all..

Points of Interest

This is just so simple that hopefully I can help someone by pointing out the obvious that may have been overlooked.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Russ Quinn


Web developer with 12 years of commercial and industrial experience in the software world.
Now working as a contractor through his own company http://codeconsults.com/. See his blog here
Personal homepage http://russquinn.com/
Occupation: Web Developer
Location: United Kingdom United Kingdom

Other popular Web Services articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 5 of 5 (Total in Forum: 5) (Refresh)FirstPrevNext
GeneralWCF Sample?memberRruedi5:47 7 Sep '07  
GeneralRe: WCF Sample?memberRuss Quinn5:51 7 Sep '07  
GeneralNested XMLmemberTancev Sasa20:00 6 Feb '07  
GeneralRe: Nested XMLmemberRuss Quinn7:33 7 Feb '07  
GeneralRe: Nested XMLmemberTancev Sasa8:44 7 Feb '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 4 Feb 2007
Editor:
Copyright 2007 by Russ Quinn
Everything else Copyright © CodeProject, 1999-2008
Web12 | Advertise on the Code Project