Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Function to check if an XML is valid..

Author  Topic 

xpandre
Posting Yak Master

212 Posts

Posted - 2010-11-22 : 09:20:52
Hi,

Scenario:
I have a column which is ntext (just moved from 2000 to 2008) which stores XML.

We have no check on the XML before storing it into this column.

Is there any SQL function that can be used to check if this XML is valid before I read it and process it?

I dont need an error as this would be used inside a trigger, so every error would result in a rollback, and I want to continue even if the XML is invalid....

I tried creating a function and just tried to assign this xml to an XML datatype variable and return 0 for YES XML and 1 for NO XML.
But couldnt use TRY-Catch block in it (UDF), so still it gave me an error. :(

Has anyone created/used this kind of function which can be used to validate XML's?

Thanks

xpandre
Posting Yak Master

212 Posts

Posted - 2010-11-22 : 09:35:31
Here is wjat I am doing:

CREATE TABLE GG_TEST (ID INT, XMLL NTEXT)


INSERT INTO GG_TEST VALUES (1,'<ROOT>SAM</RoOT>')



CREATE FUNCTION ISXML(@XMLDOCUMENT ntext) RETURNS INT
AS
BEGIN

DECLARE @XMLDOCUMENT_XML XML
SET @XMLDOCUMENT_XML = @XMLDOCUMENT
RETURN @@ERROR

END
GO


CREATE TRIGGER trg_GG_insupd
ON dbo.GG_TEST
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
BEGIN TRY
BEGIN TRY

DECLARE @T TABLE ( ID INT)
INSERT INTO @T
SELECT dbo.ISXML(GG_TEST.xmlL)
FROM INSERTED I
INNER JOIN GG_TEST (NOLOCK)
ON I.ID = GG_TEST.ID
END TRY

BEGIN CATCH

END CATCH

END TRY

BEGIN CATCH

END CATCH



END
GO



UPDATE GG_TEST SET ID = 2


Msg 3616, Level 16, State 1, Line 1
An error was raised during trigger execution. The batch has been aborted and the user transaction, if any, has been rolled back.


I dont want this error even if the XML is invalid..it should just move ahead
Go to Top of Page

xpandre
Posting Yak Master

212 Posts

Posted - 2010-11-23 : 00:39:08
Tried using a proc instead of function; Have to loop through records which I myself dont recommend:-(
Go to Top of Page
   

- Advertisement -