Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this OpenXML?

ALTER PROCEDURE GetSingersGenere
(@SingerData ntext)
AS
BEGIN
    DECLARE @hDoc int      
    exec sp_xml_preparedocument @hDoc OUTPUT,@SingerData


    IF OBject_id('SingerTable') IS NOT NULL
    BEGIN
        DROP TABLE SingerTable

    END

    CREATE TABLE SingerTable
    (
    SingerName varchar(200)
    )

    INSERT INTO SingerTable 
    (
    SingerName
    )
    SELECT * FROM OpenXML (@hDoc,'/Singers/Singer')
    WITH (SingerName varchar(200)) XMLSinger

    SELECT * FROM SingerTable
END

and the way I am executing is this:-

EXEC GetSingersGenere
 '<Singers>
<Singer>
Joe
</Singer>
<Singer>
ACDC
</Singer>
</Singers>'

I see NULL getting inserted in the table. Could anyone point out the mistake?

like image 620
Ashish Gupta Avatar asked May 31 '26 23:05

Ashish Gupta


2 Answers

By default the OPENXML will look at attribute values or child elements for the data. If you write your select as:

SELECT * FROM OpenXML (@hDoc,'/Singers/Singer')
    WITH (SingerName varchar(200) 'text()') XMLSinger

It should work ok. Note the addition of 'text()' in to the schema mapping to specify that we just want the text value of the node instead of any attribute value.

like image 99
Chris W Avatar answered Jun 04 '26 13:06

Chris W


Why even bother with the clunky OpenXML stuff?? Just use the basic XQuery support in SQL Server to do this much more elegantly:

ALTER PROCEDURE GetSingersGenre(@SingerData XML)
AS
BEGIN
   INSERT INTO dbo.SingerTable(SingerName)
      SELECT
         Singer.Node.value('(.)[1]', 'varchar(50)')
      FROM
         @SingerData.nodes('/Singers/Singer') AS Singer(Node)
like image 22
marc_s Avatar answered Jun 04 '26 12:06

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!