Wednesday, March 28, 2012

how to insert into a table using a select from xml

Good Day,

I am passing some XML into a stored procedure:

<answers>
<answer id="60" text="" />
<answer id="65" text="A moderate form of learning disability" />
<answer id="68" text="We will keep ASD checked" />
<answer id="70" text="" />
</answers>

Along with a memberid and questionid.

I was wondering how I can get this into a table

CREATE TABLE [dbo].[Answers]([PrimaryKeyID] [int]NOT NULL,[MemberID] [int]NOT NULL,[QuestionID] [int]NOT NULL,[AnswerID] [int]NOT NULL,[FreText] [varchar](255) COLLATE Latin1_General_CI_ASNULL)ON [PRIMARY]
What I would also like to do is if the text attribute is empty then put a NULL in the FreText field.
I think I am looking for
 
Insert into MyTable (Select @.MemID, @.QuesID,'somexpathforanswer','somexpathfortext'-- if empty then NULLFrom @.MyXML )
Any ideas - places to to look - thoughts Aprreciated
Kal

you can try to use OPENXML see example from T_SQL help below

DECLARE @.idoc intDECLARE @.doc varchar(1000)SET @.doc ='<ROOT><Customer CustomerID="VINET" ContactName="Paul Henriot"> <Order CustomerID="VINET" EmployeeID="5" OrderDate="1996-07-04T00:00:00"> <OrderDetail OrderID="10248" ProductID="11" Quantity="12"/> <OrderDetail OrderID="10248" ProductID="42" Quantity="10"/> </Order></Customer><Customer CustomerID="LILAS" ContactName="Carlos Gonzlez"> <Order CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00"> <OrderDetail OrderID="10283" ProductID="72" Quantity="3"/> </Order></Customer></ROOT>'--Create an internal representation of the XML document.EXEC sp_xml_preparedocument @.idoc OUTPUT, @.doc-- Execute a SELECT statement that uses the OPENXML rowset provider.SELECT *FROM OPENXML (@.idoc, '/ROOT/Customer',1) WITH (CustomerID varchar(10), ContactName varchar(20))

No comments:

Post a Comment