How to insert with namespace - sql

U have a XML file. I want to add this data to an SQL table. But something is wrong with the namespace. But I don't know what. please help me.
<?xml version="1.0" encoding="utf-8"?>
<sl:bagStand>
<Customer>
<Document>000 000 000</Document>
<names>
<Name>Mary Angel</Name>
</names>
<Address>Your City, YC 1212</Address>
<prop><Profession>Systems Analyst</Profession></prop>
</Customer>
</sl:bagStand>
I want to run this insert query
;WITH XMLNAMESPACES('sl' as x)
INSERT INTO CUSTOMERS_TABLE (DOCUMENT, NAME, ADDRESS, PROFESSION)
SELECT
MY_XML.Customer.query('Document').value('.', 'VARCHAR(20)'),
MY_XML.Customer.query('Name').value('.', 'VARCHAR(50)'),
MY_XML.Customer.query('Address').value('.', 'VARCHAR(50)'),
MY_XML.Customer.query('Profession').value('.', 'VARCHAR(50)')
FROM (SELECT CAST(MY_XML AS xml)
FROM OPENROWSET(BULK 'C:\temp\MSSQLTIPS_XML.xml', SINGLE_BLOB) AS T(MY_XML)) AS T(MY_XML)
CROSS APPLY MY_XML.nodes('x:bagStand/Customer') AS MY_XML (Customer);
Now i get a error:
Msg 9459, Level 16, State 1, Line 1
XML parsing: line 2, character 13, undeclared prefix
what am i doing wrong?

Related

Import xml data in SQL Server 2017

I have XML data like this:
<?xml version="1.0" ?>
<SettlementFile>
<Transaction>
<Identifier>
<StationID>049215901 </StationID>
<TransactionTimestamp>2021-04-01T10:39:32</TransactionTimestamp>
</Identifier>
<TerminalInfo>
<TerminalID>21590151</TerminalID>
<TerminalType>2</TerminalType>
</TerminalInfo>
<TransactionInfo>
<TransactionType>0</TransactionType>
<TransactionAmount>3.74</TransactionAmount>
<CurrencyCode>978</CurrencyCode>
<CustomerInput>
<Mileage>0</Mileage>
</CustomerInput>
<TicketNumber>213510037</TicketNumber>
<AuthorisationType>1</AuthorisationType>
</TransactionInfo>
</Transaction>
</SettlementFile>
My SQL Server table structure:
CREATE TABLE dbo.Import_Oase
(
StationID varchar(50) NULL,
TransactionTimestamp datetime NULL,
TicketNumber int NULL,
Mileage varchar(50) NULL
) ON PRIMARY
I'm trying to use this SELECT query:
SELECT
MY_XML.Details.query('StationID') .value('.', 'VARCHAR(50)'),
MY_XML.Details.query('TransactionTimestamp').value('.', 'Datetime'),
MY_XML.Details.query('TicketNumber') .value('.', 'Integer'),
MY_XML.Details.query('Mileage') .value('.', 'VARCHAR(50)')
FROM
(SELECT
CAST(MY_XML AS XML)
FROM
OPENROWSET(BULK '\\EO-TEST\SQL-Daten\Temp\MY_XML.xml', SINGLE_BLOB) AS T(MY_XML)
) AS T(MY_XML)
CROSS APPLY
MY_XML.nodes('SettlementFile/Transaction/Identifier, SettlementFile/Transaction/TransactionInfo, SettlementFile/Transaction/TransactionInfo/CustomerInput') AS MY_XML (Details);
I need to get the result in one line because it is all for 1 transactions. But it is in three different line in SQL.
Please try the following solution.
When you are satisfied with the outcome, just uncomment the INSERT INTO line.
SQL
WITH rs (xmlData) AS
(
SELECT TRY_CAST(BulkColumn AS XML)
FROM OPENROWSET(BULK N'e:\Temp\ daryosmitan.xml', SINGLE_BLOB) AS x
)
-- INSERT INTO dbo.Import_Oase (StationID, TransactionTimestamp, TicketNumber, Mileage)
SELECT c.value('(Identifier/StationID/text())[1]', 'VARCHAR(50)') AS StationID
, c.value('(Identifier/TransactionTimestamp/text())[1]', 'DATETIME') AS TransactionTimestamp
, c.value('(TransactionInfo/TicketNumber/text())[1]', 'VARCHAR(50)') AS TicketNumber
, c.value('(TransactionInfo/CustomerInput/Mileage/text())[1]', 'INT') AS Mileage
FROM rs
CROSS APPLY xmlData.nodes('/SettlementFile/Transaction') AS t(c);

How can i load an XML file to SQL

Im trying to load an XML file to SQL Server, but i m not getting anything
Here is my XML File:
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="http://www.demandware.com/xml/impex/catalog/2006-10-31" catalog-id="master-catalog-sso-us">
<header>
<image-settings>
<internal-location base-path="/"/>
<view-types>
<view-type>large</view-type>
<view-type>medium</view-type>
<view-type>small</view-type>
<view-type>swatch</view-type>
</view-types>
<alt-pattern>${productname}</alt-pattern>
<title-pattern>${productname}</title-pattern>
</image-settings>
</header>
<category category-id="root">
<display-name xml:lang="x-default">root Category</display-name>
<description xml:lang="x-default">root Category</description>
<online-flag>true</online-flag>
<template/>
<page-attributes/>
<refinement-definitions>
<refinement-definition type="attribute" bucket-type="none" attribute-id="shops" system="false">
<display-name xml:lang="x-default">Shops</display-name>
<value-set>search-result</value-set>
<sort-mode>value-name</sort-mode>
<sort-direction>ascending</sort-direction>
<cutoff-threshold>5</cutoff-threshold>
</refinement-definition>
</refinement-definitions>
</category>
<category category-id="default">
<display-name xml:lang="x-default">default Category</display-name>
<description xml:lang="x-default">default Category</description>
<online-flag>true</online-flag>
<parent>root</parent>
<template/>
<page-attributes/>
</category>
<product product-id="0217328320-sso-us">
<ean/>
<upc/>
<unit/>
<min-order-quantity>1</min-order-quantity>
<step-quantity>1</step-quantity>
<display-name xml:lang="x-default">Magnetibook - 4 Seasons</display-name>
<long-description xml:lang="x-default">48 magnets that stick to the metallic &#34;canvas&#34; where your child can choose between any of the four season &#34;back drops&#34; and then pick out the appropriate outfits and dress the family for a day outside. Comes in a magnetic closing &#34;book&#34; for safe keeping and easy storage.</long-description>
<store-force-price-flag>false</store-force-price-flag>
<store-non-inventory-flag>false</store-non-inventory-flag>
<store-non-revenue-flag>false</store-non-revenue-flag>
<store-non-discountable-flag>false</store-non-discountable-flag>
<online-flag>true</online-flag>
<online-from>2017-01-01T05:00:00.000Z</online-from>
<available-flag>true</available-flag>
<searchable-flag>false</searchable-flag>
<tax-class-id>standard</tax-class-id>
<brand>Janod</brand>
<manufacturer-name>Juratoys Company</manufacturer-name>
<sitemap-included-flag site-id="rco-us">true</sitemap-included-flag>
<sitemap-changefrequency site-id="rco-us">weekly</sitemap-changefrequency>
<sitemap-priority site-id="rco-us">1.0</sitemap-priority>
<page-attributes/>
<custom-attributes>
<custom-attribute attribute-id="ID">6339080</custom-attribute>
How do i load that ID field into SQL? I tried this:
But i believe my cross apply c.nodes is wrong! What Markups should i use?
Thanks
SELECT a.id.query('id').value('.','varchar(50)') as id FROM
( SELECT CAST(C AS XML) FROM OPENROWSET (BULK '\\test\master.xml', SINGLE_BLOB ) as T(c) ) AS S(c)
cross apply c.nodes('product/id') as A(id)
You ca try this:
SELECT c.id.query('id').value('.','varchar(50)') as id FROM
( SELECT CAST(C AS XML) FROM OPENROWSET (BULK '\\test\master.xml', SINGLE_BLOB ) as T(c) ) AS T(c)
cross apply c.nodes('product/id') as c(id)
But in your shared xml couldn't find an id tag within product tag.
Here I am sharing an Example:
XML File content:
<?xml version="1.0" encoding="utf-8"?>
<Customers>
<Customer>
<Document>000 000 000</Document>
<Name>Mary Angel</Name>
<Address>Your City, YC 1212</Address>
<Profession>Systems Analyst</Profession>
</Customer>
<Customer>
<Document>000 000 001</Document>
<Name>John Lenon</Name>
<Address>Your City, YC 1212</Address>
<Profession>Driver</Profession>
</Customer>
<Customer>
<Document>000 000 002</Document>
<Name>Alice Freeman</Name>
<Address>Your City, YC 1212</Address>
<Profession>Architect</Profession>
</Customer>
<Customer>
<Document>000 000 003</Document>
<Name>George Sands</Name>
<Address>Your City, YC 1212</Address>
<Profession>Doctor</Profession>
</Customer>
<Customer>
<Document>000 000 004</Document>
<Name>Mark Oliver</Name>
<Address>Your City, YC 1212</Address>
<Profession>Writer</Profession>
</Customer>
</Customers>
Copy above content and save as a xml file in d drive named testxmlfile.xml
Then try below query:
SELECT
MY_XML.Customer.query('Document').value('.', 'VARCHAR(20)') Document,
MY_XML.Customer.query('Name').value('.', 'VARCHAR(50)') Name,
MY_XML.Customer.query('Address').value('.', 'VARCHAR(50)')Address,
MY_XML.Customer.query('Profession').value('.', 'VARCHAR(50)' )Profession
FROM (SELECT CAST(MY_XML AS xml)
FROM OPENROWSET(BULK 'd:\testxmlfile.xml', SINGLE_BLOB) AS T(MY_XML)) AS T(MY_XML)
CROSS APPLY MY_XML.nodes('Customers/Customer') AS MY_XML (Customer);
Output:
Document Name Address Profession
000 000 000 Mary Angel Your City, YC 1212 Systems Analyst
000 000 001 John Lenon Your City, YC 1212 Driver
000 000 002 Alice Freeman Your City, YC 1212 Architect
000 000 003 George Sands Your City, YC 1212 Doctor
000 000 004 Mark Oliver Your City, YC 1212 Writer
You haven't been clear about what exactly you want, but it looks like you want the attribute product-id from here:
<product product-id="0217328320-sso-us">
You haven't taken into account namespaces, you need to add that.
It's also unclear if you have multiple product nodes. If you do, then you need this
WITH XMLNAMESPACES (DEFAULT 'http://www.demandware.com/xml/impex/catalog/2006-10-31')
SELECT A.product.value('#product-id','varchar(50)') as id
FROM
( SELECT CAST(C AS XML)
FROM OPENROWSET (BULK '\\test\master.xml', SINGLE_BLOB ) as T(c)
) AS S(c)
cross apply S.c.nodes('/catalog/product') as A(product)
If you have only one product node then you don't need .values at all:
WITH XMLNAMESPACES (DEFAULT 'http://www.demandware.com/xml/impex/catalog/2006-10-31')
SELECT S.c.value('/catalog/product/#product-id','varchar(50)') as id FROM
FROM
( SELECT CAST(C AS XML)
FROM OPENROWSET (BULK '\\test\master.xml', SINGLE_BLOB ) as T(c)
) AS S(c)

Uniqueidentifier conversion failed when Importing XML file to SQL Server

I'm trying to import data from an XML file into a SQL Server table. However, I'm getting the error:
Conversion failed when converting from a character string to uniqueidentifier
It says it's in state 2 of Line 6 (Id3), but I assume the conversion is failing in other places.
XML:
<ImportExportObject>
<Objects>
<MyObject>
<Id>123e5c8c-a7fc-40da-440e-12348bc612e8</Id>
<Id2>123e5c8c-a7fc-40da-440e-12348bc612e8</Id2>
<Name>en</Name>
<Id3>123e5c8c-a7fc-40da-440e-12348bc612e8</Id3>
</MyObject>
</Objects>
</ImportExportObject>
SQL code:
INSERT INTO MyTable(ID, Id2, Name, Id3)
SELECT
MyXMLDocument.query('Id').value('.', 'uniqueidentifier'),
MyXMLDocument.query('Id2').value('.', 'uniqueidentifier'),
MyXMLDocument.query('Name').value('.', 'NVARCHAR(50)'),
MyXMLDocument.query('Id3').value('.', 'uniqueidentifier'),
FROM (SELECT CAST(MyXMLDocument AS xml)
FROM OPENROWSET(BULK 'C:\Users\myUser\Documents\MyXMLDocument.xml', SINGLE_BLOB) AS T(MyXMLDocument)) AS T(MyXMLDocument)
CROSS APPLY MyXMLDocument.nodes('ImportExportObject/Objects/MyObject') AS MyXMLDocument (MyObject);
How do I resolve this error?
I've been unable to get Select Cast and Convert to work - and .value() requires string literals so '#Id' doesn't seem to work.
Quite unsure here - any help is much appreciated!
How about having MyTable with an automatically imported id and not importing that? Would that work for what you want?
You can the code below to find which values cannot be converted to uniqueidentifier:
SELECT
MyXMLDocument.query('Id').value('.', 'NVARCHAR(50)'),
MyXMLDocument.query('Id2').value('.', 'NVARCHAR(50)'),
MyXMLDocument.query('Id3').value('.', 'NVARCHAR(50)')
FROM (SELECT CAST(MyXMLDocument AS xml)
FROM OPENROWSET(BULK 'C:\Users\myUser\Documents\MyXMLDocument.xml', SINGLE_BLOB) AS T(MyXMLDocument)) AS T(MyXMLDocument)
CROSS APPLY MyXMLDocument.nodes('ImportExportObject/Objects/MyObject') AS MyXMLDocument (MyObject)
WHERE TRY_CAST(MyXMLDocument.query('Id').value('.', 'NVARCHAR(50)') AS uniqueidentifier) IS NULL
OR TRY_CAST(MyXMLDocument.query('Id2').value('.', 'NVARCHAR(50)') AS uniqueidentifier) IS NULL
OR TRY_CAST(MyXMLDocument.query('Id3').value('.', 'NVARCHAR(50)') AS uniqueidentifier) IS NULL
The idea is to use TRY_CAST which will return NULL if the data cannot be converted.
declare #x xml = N'<ImportExportObject>
<Objects>
<MyObject>
<Id>123e5c8c-a7fc-40da-440e-12348bc612e8</Id>
<Id2>123e5c8c-a7fc-40da-440e-12348bc612e8</Id2>
<Name>en</Name>
<Id3>123e5c8c-a7fc-40da-440e-12348bc612e8</Id3>
</MyObject>
</Objects>
</ImportExportObject>';
SELECT
MyXML.MyObject.value('Id[1]', 'uniqueidentifier'),
MyXML.MyObject.value('Id2[1]', 'uniqueidentifier'),
MyXML.MyObject.value('Name[1]', 'NVARCHAR(50)'),
MyXML.MyObject.value('Id3[1]', 'uniqueidentifier')
FROM
(
SELECT #x
-- CAST(MyXMLDocument AS xml) FROM OPENROWSET(BULK 'C:\Users\myUser\Documents\MyXMLDocument.xml', SINGLE_BLOB)
) AS T(MyXMLDocument)
CROSS APPLY MyXMLDocument.nodes('./ImportExportObject/Objects/MyObject') AS MyXML(MyObject);

Add XML attribute in mssql using stored procedure

i want output
<CustomerName>
<Customer id='1'>
<Name>xyz</Name>
</Customer>
<Customer id='2'>
<Name>Abc</Name>
</Customer>
</CustomerName>
for this output i wrote SP
SELECT
'' AS [CustomerName],
(SELECT
Name[Customer/Name]
FOR XML PATH(''), TYPE) AS[CustomerName/Customer]
FOR XML PATH('')
not able to add Id attribute, please help me
Try this:
DECLARE #tblCust TABLE(id INT, CustomerName VARCHAR(100));
INSERT INTO #tblCust VALUES
(1,'xyz')
,(2,'Abc');
SELECT id AS [#id]
,CustomerName AS [Name]
FROM #tblCust
FOR XML PATH('Customer'),ROOT('CustomerName')
This is the result
<CustomerName>
<Customer id="1">
<Name>xyz</Name>
</Customer>
<Customer id="2">
<Name>Abc</Name>
</Customer>
</CustomerName>
SELECT [#id] = t.id, [Name] = t.name
FROM (
VALUES (1, 'name'), (2, 'name2')
) t (id, name)
FOR XML PATH('Customer'), ROOT('CustomerName')

Unable to read data into SQL Server 2005 from an XML file

I am trying to use the following script to read data from an XML file and insert it into a table called TermsTree on SQL Server 2005.
INSERT INTO TermsTree (TermID,ParentID,Name)
SELECT X.TermsTree.query('TermID').value('.', 'INT'),
X.TermsTree.query('ParentID').value('.', 'INT'),
X.TermsTree.query('Name').value('.', 'VARCHAR(2000)')
FROM (
SELECT CAST(x AS XML)
FROM OPENROWSET(
BULK 'C:\Users\MehtabM\Desktop\GetAllTermTree.xml',
SINGLE_BLOB) AS T(x)
) AS T(x)
CROSS APPLY x.nodes('ArrayOfTerm_Child/Term_Child') AS X(TermsTree);
A sample of the XML file is
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfTerm_Child xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<Term_Child>
<TermID>2021</TermID>
<Name>A. Geographic locations</Name>
<ParentID>0</ParentID>
</Term_Child>
<Term_Child>
<TermID>3602</TermID>
<Name>Oceania</Name>
<ParentID>2021</ParentID>
</Term_Child>
<Term_Child>
<TermID>3604</TermID>
<Name>Australasia</Name>
<ParentID>3602</ParentID>
</Term_Child>
</Term_Child>
</ArrayOfTerm_Child>
http://www.sqlfiddle.com/#!3/18f84/15
declare #xml xml
select #xml='<?xml version="1.0" encoding="utf-8"?>
<ArrayOfTerm_Child xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<Term_Child>
<TermID>2021</TermID>
<Name>A. Geographic locations</Name>
<ParentID>0</ParentID>
</Term_Child>
<Term_Child>
<TermID>3602</TermID>
<Name>Oceania</Name>
<ParentID>2021</ParentID>
</Term_Child>
<Term_Child>
<TermID>3604</TermID>
<Name>Australasia</Name>
<ParentID>3602</ParentID>
</Term_Child>
</ArrayOfTerm_Child>'
;WITH XMLNAMESPACES(DEFAULT 'http://tempuri.org/')
SELECT X.TermsTree.query('TermID').value('.', 'INT'),
X.TermsTree.query('ParentID').value('.', 'INT'),
X.TermsTree.query('Name').value('.', 'VARCHAR(2000)')
FROM #xml.nodes('/ArrayOfTerm_Child/Term_Child') X(TermsTree)