XML,SQL,cursor,stored,procedure,create,short,
Quick Search for:  in language:    
XML,SQL,cursor,stored,procedure,create,short,
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
SQL Stats

 Code: 31,327 lines
 Jobs: 372 postings

 
Sponsored by:

 

You are in:

 
Login



Latest Code Ticker for SQL.
Unix Date Convertor Function
By George Graff on 10/23


Insert pipe delimited rows into multiple rows.
By Charles Toepfer on 10/21


Logfiles by PL/SQL
By Stephan Rechberger on 10/21


To display a name in a default language if the given one doesn't exist
By Serge Alard on 10/18


Order by column except a few values
By Serge Alard on 10/18


Introduction to PL/SQL (Series 3) Cursors
By David Nishimoto on 10/14


Sorting a String using T-SQL
By Gaurav Pugalia on 10/12


Protecting against TSQL virii, worms and time bombs
By Joseph Gama on 10/11


Click here to see a screenshot of this code!Get size in bytes of SP, View, Trigger, UDF or Rule
By Joseph Gama on 10/11

(Screen Shot)

Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!





Affiliate Sites



 
 
   

Creating XML in a Stored Procedure

Print
Email
 

Submitted on: 10/9/2000 4:20:38 AM
By: The_Mat_in_the_Hat  
Level: Intermediate
User Rating: By 6 Users
Compatibility:SQL Server 7.0

Users have accessed this article 13787 times.
 
(About the author)
 
     Use a cursor in a stored procedure to create short XML string to output rather than recordsets. Also included is a simple VB application (with source) that generates the SQL

This article has accompanying files
 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
Creating the Procedure

This procedure runs on an table called "tbl_Scripts" and returns data on ID (int), and Title (varchar) fields in an XML string.
This is the simple version, you can use an ADODB.Connection to run this procedure

CREATE PROCEDURE [sp_TestXML]
AS
DECLARE
	@XML 	varchar(8000),		-- output var
	@ID		varchar(18),		-- var to insert the ID field into
	@Title		varchar(62)		-- var to insert the Title field into
DECLARE Script_curs CURSOR FOR			-- We need a cursor to do the looping in
SELECT ('ID="' + CAST([ID] AS varchar(10)) + '"') AS ID, ('Title="' + [Title] + '"') AS Title
	FROM tbl_Scripts
	FOR READ ONLY
SET @XML = '<recordset>'
OPEN Script_curs
FETCH NEXT FROM Script_curs
	INTO @ID, @Title
	WHILE (@@FETCH_STATUS = 0 )
    BEGIN
    	SET @XML = @XML + '<record ' + @ID + ' ' + @Title + ' />'
    	FETCH NEXT FROM Script_curs INTO @ID, @Title
END

SET @XML = (@XML + '</recordset>') -- Output result as a 1 field record SELECT XMLOUT = LTRIM(RTRIM(@XML)) CLOSE Script_curs DEALLOCATE Script_curs
Then on your ASP Page:
<%
Option Explicit
Response.Buffer = True
Dim cn
Set cn = Server.createObject("ADODB.Connection")
cn.open Application("MyDSN")		' MyDSN is some valid connection string
Response.ContentType = "text/xml"	' For browsers that read mime types and if this is the only data on the page
Response.Write cn.execute("sp_TestXML").getString
cn.close
Set cn = Nothing
%>
This is pretty easy, you could make life more interesting by adding parameters, WHERE's etc.

The biggest problem with this example is that you only get 8000 characters (actually not that much!) to play with and you may find that you quickly run out of room.
The second problem is that if you use text data you may find illegal characters are present in the data. I tend to do a Server.HTMLEncode before I put data into servers but you could do a series of replaces on the text column ie

-- Title has illegal characters
SET @safeXML = REPLACE(Title, CHAR(38), '&')
SET @safeXML = REPLACE(@safeXML, CHAR(96), ''')
SET @safeXML = REPLACE(@safeXML, CHAR(34), '"')
SET @safeXML = REPLACE(@safeXML, CHAR(60), '<')
SET @safeXML = REPLACE(@safeXML, CHAR(62), '<')
-- Now @safeXML has no illegal character
--     s
Since SQL is faster than both a compiled VB COM component and ASP if you need short XML strings this isn't a bad method and can be faster than the usual alternative of looping through RecordSets.
To make this reallt fly though we should avoid any recordset being created and just use an output parameter so combining the two bits of SQL we have a new *safer* stored procedure
CREATE PROCEDURE [sp_TestXML2]
	@XMLOUT		varchar(8000)		OUTPUT		-- this time use an output parameter
AS
DECLARE
	@XML 		varchar(8000),	
	@ID		varchar(18),	
	@Title		varchar(62)	
DECLARE Script_curs CURSOR FOR
SELECT [ID], [Title] 
	FROM tbl_Scripts
	FOR READ ONLY
SET @XML = '<recordset>'
OPEN Script_curs
FETCH NEXT FROM Script_curs
	INTO @ID, @Title
	WHILE (@@FETCH_STATUS = 0 )
    BEGIN
    	-- Create safe text
    	SET @Title = REPLACE(@Title, CHAR(38), '&')
    	SET @Title = REPLACE(@Title, CHAR(96), ''')
    	SET @Title = REPLACE(@Title, CHAR(34), '"quot;')
    	SET @Title = REPLACE(@Title, CHAR(60), '<lt;')
    	SET @Title = REPLACE(@Title, CHAR(62), '>gt;')
    	-- Create XML Node
    	SET @XML = @XML + '<record ID="' + CAST(@ID AS varchar(5)) + + '" Title="' + @Title + '" />'
    	FETCH NEXT FROM Script_curs INTO @ID, @Title
END

SET @XML = (@XML + '</recordset>') -- output the xml as a single parameter SELECT @XMLOUT = LTRIM(RTRIM(@XML)) CLOSE Script_curs DEALLOCATE Script_curs
And new ASP code
<%
Option Explicit
Response.Buffer = True
Dim cmd
Set cmd = Server.createObject("ADODB.Command")
cmd.activeConnection = Application("MyDSN")
cmd.commandText = "sp_TestXML2"
cmd.commandType = adcmdStoredProc	' assuming you include the TypeLib for ADO
cmd.parameters.refresh
cmd.execute
Response.contentType = "text/xml"
Response.write cmd.parameters(1).value
cmd.ActiveConnection = Nothing		' Nice for connection pooling
Set cmd = Nothing
%>

And there you have it, all you need to create an XML string in a stored Procedure, of course this WILL all become obselete when we can SELECT FOR ... XML AUTO in SQL2k

Something for the weekend?
I've attached a fairly undocumented VB application that helps you to generate these Stored Procedures.
Just type a valid connection string into the top left box, click Examine DB, select a table, the highlight the columns you want in the right hand drop down and click Generate SQL.
Thats the procedure done, then press Test SQL (requires IE5 or above) to view a sample XML file

Note
The EXE isnt guarenteed to work, I use it to generate the procedures then alter them by hand when i need more complex functionality, so if you have probs dont blame me!

"That SQL, that SQL, sometimes i wish it'd go to hell,
But you love that xml, even with it's funny smell..."

The Mat in the Hat

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzipto decompress it.

Virus note:All files are scanned once-a-day by Planet Source Code for viruses,but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:
1)Re-scan downloaded files using your personal virus checker before using it.
2)NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

If you don't have a virus scanner, you can get one at many places on the net including:McAfee.com

 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.


Other 1 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this article(in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
2/15/2001 5:41:17 PM:killcrazy
too much MS from the XML king!!! he he he he !!! see ya at work tomorrow mate.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | SQL Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.