I'm looking to return value for my where condition from an XML.
I'd like to return a value from messages table's Request column. Which is in XML data format. Unfortunately all I could achieve is retrieving nothing.
Then I tried to put the value as a column but I always get nulls for the values
Here's an XML from Request column:
<InvoiceRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/InternalReuqests">
<ActiveUserID xmlns="http://schemas.datacontract.org/2004/07/Fix.ServiceBase">0</ActiveUserID>
<LinqConfigId xmlns="http://schemas.datacontract.org/2004/07/Fix.ServiceBase">0</LinqConfigId>
<RequestHeaderInfo xmlns:d2p1="Fix.Services" xmlns="http://schemas.datacontract.org/2004/07/Fix.ServiceBase">
<d2p1:MapArchive i:nil="true" />
<d2p1:HandledSuccessCategory>rscNone</d2p1:HandledSuccessCategory>
</RequestHeaderInfo>
<Username xmlns="http://schemas.datacontract.org/2004/07/Fix.ServiceBase" i:nil="true" />
<SSID>S-1-6-25-123456789-123456789-123456789-12345</SSID>
<miscdata xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>date:2020.02.26 08:27:00</d2p1:string>
<d2p1:string>hours:0</d2p1:string>
<d2p1:string>Ready:True</d2p1:string>
<d2p1:string>disct:False</d2p1:string>
<d2p1:string>extdisct:False</d2p1:string>
<d2p1:string>Matmove:False</d2p1:string>
<d2p1:string>Matlim:0</d2p1:string>
<d2p1:string>Comments:</d2p1:string>
</miscdata>
<ffreeID>468545</ffreeID>
</InvoiceRequest>
here's my sql query:
select id, Request.value('(/*:InvoiceRequest/*:ffreeID)[1]','varchar(max)')
from messages
I thought I should get in the first column the id from the database, and next to it the value of the ffreeID, but the Request.value is always null.
Could anyone look into it what am I missing?
You need for declare the default namespace, which for your xml is http://schemas.datacontract.org/2004/07/InternalReuqests:
--Sample XML
DECLARE #xml xml = '<InvoiceRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/InternalReuqests">
<ActiveUserID xmlns="http://schemas.datacontract.org/2004/07/Fix.ServiceBase">0</ActiveUserID>
<LinqConfigId xmlns="http://schemas.datacontract.org/2004/07/Fix.ServiceBase">0</LinqConfigId>
<RequestHeaderInfo xmlns:d2p1="Fix.Services" xmlns="http://schemas.datacontract.org/2004/07/Fix.ServiceBase">
<d2p1:MapArchive i:nil="true" />
<d2p1:HandledSuccessCategory>rscNone</d2p1:HandledSuccessCategory>
</RequestHeaderInfo>
<Username xmlns="http://schemas.datacontract.org/2004/07/Fix.ServiceBase" i:nil="true" />
<SSID>S-1-6-25-123456789-123456789-123456789-12345</SSID>
<miscdata xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>date:2020.02.26 08:27:00</d2p1:string>
<d2p1:string>hours:0</d2p1:string>
<d2p1:string>Ready:True</d2p1:string>
<d2p1:string>disct:False</d2p1:string>
<d2p1:string>extdisct:False</d2p1:string>
<d2p1:string>Matmove:False</d2p1:string>
<d2p1:string>Matlim:0</d2p1:string>
<d2p1:string>Comments:</d2p1:string>
</miscdata>
<ffreeID>468545</ffreeID>
</InvoiceRequest>'; --Assumed this should be </InvoiceRequest>, not <InvoiceRequest>.
--Get value
WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/InternalReuqests')
SELECT X.Request.value('(/InvoiceRequest/ffreeID/text())[1]','int')
FROM (VALUES(#XML))X(Request);
Here is another way by simulating a mock table. Everything else resembles #Larnu's solution. All credit goes to #Larnu.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (ID INT IDENTITY PRIMARY KEY, Request XML);
INSERT INTO #tbl (Request)
VALUES
(N'<InvoiceRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/InternalReuqests">
<ActiveUserID xmlns="http://schemas.datacontract.org/2004/07/Fix.ServiceBase">0</ActiveUserID>
<LinqConfigId xmlns="http://schemas.datacontract.org/2004/07/Fix.ServiceBase">0</LinqConfigId>
<RequestHeaderInfo xmlns:d2p1="Fix.Services"
xmlns="http://schemas.datacontract.org/2004/07/Fix.ServiceBase">
<d2p1:MapArchive i:nil="true"/>
<d2p1:HandledSuccessCategory>rscNone</d2p1:HandledSuccessCategory>
</RequestHeaderInfo>
<Username xmlns="http://schemas.datacontract.org/2004/07/Fix.ServiceBase" i:nil="true"/>
<SSID>S-1-6-25-123456789-123456789-123456789-12345</SSID>
<miscdata xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>date:2020.02.26 08:27:00</d2p1:string>
<d2p1:string>hours:0</d2p1:string>
<d2p1:string>Ready:True</d2p1:string>
<d2p1:string>disct:False</d2p1:string>
<d2p1:string>extdisct:False</d2p1:string>
<d2p1:string>Matmove:False</d2p1:string>
<d2p1:string>Matlim:0</d2p1:string>
<d2p1:string>Comments:</d2p1:string>
</miscdata>
<ffreeID>468545</ffreeID>
</InvoiceRequest>');
-- DDL and sample data population, end
WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/InternalReuqests')
SELECT ID
, c.value('(ffreeID/text())[1]','INT') AS ffreeID
FROM #tbl AS tbl
CROSS APPLY tbl.Request.nodes('/InvoiceRequest') AS t(c);
Output
+----+---------+
| ID | ffreeID |
+----+---------+
| 1 | 468545 |
+----+---------+
Related
in my database I have an XML-column that looks like this:
<Root>
<Row>
<Einheit>Stck</Einheit>
<Faktor>1</Faktor>
<VkPreisEinheit>1</VkPreisEinheit>
<VkMengenEinheit>1</VkMengenEinheit>
<EkMengenEinheit>1</EkMengenEinheit>
<StcklEinheit>1</StcklEinheit>
<StcklDefinition>1</StcklDefinition>
<KonsumentenEinheit>1</KonsumentenEinheit>
</Row>
<Row>
<Einheit>Stück</Einheit>
<Faktor>100</Faktor>
<EinheitFaktor>Stck</EinheitFaktor>
<EkPreisEinheit>1</EkPreisEinheit>
</Row>
</Root>
What I want to achieve ist that I get the value from 'Faktor' only from the row where 'EkPreisEinheit' is 1
I have tried something with:
CASE WHEN isnull(convert(xml,xmlcolumn).value('(/Root/Row/EkPreisEinheit)[1]','nvarchar(max)'),'') = '1'
THEN isnull(convert(xml,xmlcolumn).value('(/Root/Row/Faktor)[1]','nvarchar(max)'),'')
WHEN isnull(convert(xml,xmlcolumn).value('(/Root/Row/EkPreisEinheit)[2]','nvarchar(max)'),'') = '1'
THEN isnull(convert(xml,xmlcolumn).value('(/Root/Row/Faktor)[2]','nvarchar(max)'),'')
ELSE ''
END AS Faktor
which would work if EKPreiseinheit would be found in both columns, but it only is in one. Also it could be that it is in the first row, or in the third if there was any. Is there any way to tackle this?
When dealing with multiple of the same node, you want to use nodes in the FROM to create a row for each one. This means you end up with something like this:
DECLARE #XML xml = '<Root>
<Row>
<Einheit>Stck</Einheit>
<Faktor>1</Faktor>
<VkPreisEinheit>1</VkPreisEinheit>
<VkMengenEinheit>1</VkMengenEinheit>
<EkMengenEinheit>1</EkMengenEinheit>
<StcklEinheit>1</StcklEinheit>
<StcklDefinition>1</StcklDefinition>
<KonsumentenEinheit>1</KonsumentenEinheit>
</Row>
<Row>
<Einheit>Stück</Einheit>
<Faktor>100</Faktor>
<EinheitFaktor>Stck</EinheitFaktor>
<EkPreisEinheit>1</EkPreisEinheit>
</Row>
</Root>';
WITH YourTable AS(
SELECT V.YourXML
FROM (VALUES(#XML)) V(YourXML))
SELECT R.R.value('(EkPreisEinheit/text())[1]','int') AS EkPreisEinheit
FROM YourTable YT
--Due to the misuse of datatypes you'll need a CONVERT in a VALUES clause here instead
CROSS APPLY YT.YourXML.nodes('/Root/Row') R(R)
WHERE R.R.value('(EkPreisEinheit/text())[1]','int') IS NOT NULL;
Here is a solution for you. Few points to mention. (0) It handles XML directly from the table. (1) It converts XML data into XML data type via TRY_CAST(). So it will emit NULL when XML is not well-formed without generating any error. (2) It checks via XPath predicate for the <Row> element where 'EkPreisEinheit' element value is 1, and filters out anything else.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (ID INT IDENTITY(1,1) PRIMARY KEY, xmlcolumn NVARCHAR(MAX));
INSERT INTO #tbl
VALUES (N'<Root>
<Row>
<Einheit>Stck</Einheit>
<Faktor>1</Faktor>
<VkPreisEinheit>1</VkPreisEinheit>
<VkMengenEinheit>1</VkMengenEinheit>
<EkMengenEinheit>1</EkMengenEinheit>
<StcklEinheit>1</StcklEinheit>
<StcklDefinition>1</StcklDefinition>
<KonsumentenEinheit>1</KonsumentenEinheit>
</Row>
<Row>
<Einheit>Stück</Einheit>
<Faktor>100</Faktor>
<EinheitFaktor>Stck</EinheitFaktor>
<EkPreisEinheit>1</EkPreisEinheit>
</Row>
</Root>');
-- DDL and sample data population, end
;WITH rs AS
(
SELECT ID, TRY_CAST(xmlcolumn AS XML) AS xml_data
from #tbl
)
SELECT ID
, col.value('(Faktor/text())[1]','INT') AS Faktor
, col.value('(EkPreisEinheit/text())[1]','INT') AS EkPreisEinheit
FROM rs as tbl
CROSS APPLY tbl.xml_data.nodes('/Root/Row[EkPreisEinheit="1"]') AS tab(col);
Output
+----+--------+----------------+
| ID | Faktor | EkPreisEinheit |
+----+--------+----------------+
| 1 | 100 | 1 |
+----+--------+----------------+
I have the following output from SQL using FOR XML clause:
<q17:DestinationSection xmlns:q17="http://ITrack.Transmission/2011/02/25/Objects">
<q17:DestinationCode>1</q17:DestinationCode>
<q17:DestinationName>Strada Rampei 9, Iasi</q17:DestinationName>
<q17:DestinationAddress1>Strada Rampei 9, Iasi</q17:DestinationAddress1>
<q17:DestinationAddress2>
xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
</q17:DestinationAddress2>
</q17:DestinationSection>
The DestinationSection is the main root for this block of data. Is there any possibility to do some workaround and to have something like below in the <q17:DestinationAddress2></q17:DestinationAddress2> tag?
<q17:DestinationAddress2 xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"</q17:DestinationAddress2>
I have tried something but I get an error that says that I need to declare the namespace but I really don't know where to "introduce" that definition.
My SQL statement
DECLARE #XMLFINAL VARCHAR(MAX)
SET #XMLFINAL=''
DECLARE #XMLFINAL2 VARCHAR(MAX)
SET #XMLFINAL2=''
DECLARE #NUMBER NVARCHAR(100)
DECLARE #NUMBER2 NVARCHAR(100)
DECLARE #XML VARCHAR(MAX)
DECLARE #XML2 VARCHAR(MAX)
DECLARE Rec CURSOR FAST_FORWARD FOR
SELECT GID FROM PurchaseDocumentsHeader
OPEN Rec
FETCH NEXT FROM Rec INTO #NUMBER2
WHILE ##FETCH_STATUS = 0
BEGIN
SET #XML2=''
;WITH XMLNAMESPACES ('http://ITrack.Transmission/2011/02/25/Objects' as q17)
SELECT #XML2= (
SELECT
DestCode AS 'q17:DestinationCode', DestDescr 'q17:DestinationName', DestAddr AS 'q17:DestinationAddress1', DestAddr2 AS 'q17:DestinationAddress2',
DestZIP AS 'q17:DestinationZIP'
FROM PurchaseDocumentsHeader WHERE GID=#NUMBER2
FOR XML RAW('q17:DestinationSection'),ELEMENTS
)
FETCH NEXT FROM Rec INTO #NUMBER2
SET #XMLFINAL2=#XMLFINAL2+#XML2
END
CLOSE Rec DEALLOCATE Rec
EDIT
Please find below my DDL. It's a view used to extract the data from an official table.
CREATE VIEW [dbo].[PurchaseDocumentsHeader]
AS
SELECT esd.GID, esd.ADRegistrationDate, esgo.Code AS DestCode, esgo.Description AS DestDescr, esgo.Address1 AS DestAddr, esgo.fCityCode AS DestCity,
esgp.TaxRegistrationNumber AS DestZIP, 'xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' AS DestAddr2, esgo.Description AS DestRomanized,
esgo.Address1 AS DestAddress1Romanized,
'xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' AS DestAddress2Romanized, esgp.TaxRegistrationNumber AS DestZIPRom,
esgo.fCityCode AS DestCityRomanized, esgo.fCountryCode AS DestCountry, cast('DestinationGLN xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>' AS XML) AS DestGLN,
'xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' AS DestCoord
FROM ESFIDocumentTrade esd
LEFT JOIN ESGOSites esgo on esd.fDeliverySiteGID=esgo.GID
LEFT JOIN ESFITradeAccount esc on esd.fTradeAccountGID=esc.GID
LEFT JOIN ESGOPerson esgp on esc.fPersonCodeGID=esgo.GID
LEFT JOIN ESFIDocumentType est on esd.fADDocumentTypeGID=est.GID
WHERE esd.fTransitionStepCode='APPROVED' AND est.Code='CVR'
AND YEAR(esd.ADRegistrationDate)=YEAR(GETDATE())
AND MONTH(esd.ADRegistrationDate)=MONTH(GETDATE())
AND DAY(esd.ADRegistrationDate)=DAY(GETDATE())
GO
Later edit
CREATE TABLE DocPurcharseHeader
(
ADRegistrationDate date,
Code NVARCHAR(4000),
Description NVARCHAR(4000),
Address1 NVARCHAR (4000),
Address2 NVARCHAR (4000),
City NVARCHAR (4000),
ZIPCode NVARCHAR(4000)
)
INSERT INTO DocPurcharseHeader (ADRegistrationDate, Code, Description, Address1, Address2, City, ZIPCode)
VALUES('2017-10-16', '01', 'MyPOS', 'MyPOSAddress1', 'MyPOSAddress2', 'BUCHAREST', '123456')
2nd Later edit
;WITH XMLNAMESPACES ('http://ITrack.Transmission/2011/02/25/Objects' as q17)
SELECT #XMLSalesOrders=(
SELECT DestCode AS [q17:DestinationCode]
,DestDescr AS [q17:DestinationName]
,DestAddr AS [q17:DestinationAddress1]
,DestAddr2 AS [q17:DestinationAddress2]
FROM PurchaseDocumentsHeader
FOR XML PATH('q17:DestinationSection'),ELEMENTS XSINIL,ROOT('q17:DestinationSections'))
This code above is generating the below output, without XSINL directive:
<q17:DestinationSections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q17="http://ITrack.Transmission/2011/02/25/Objects">
<q17:DestinationSection>
<q17:DestinationCode>1</q17:DestinationCode>
<q17:DestinationName>Strada Rampei 9, Iasi</q17:DestinationName>
<q17:DestinationAddress1>Strada Rampei 9, Iasi</q17:DestinationAddress1>
<q17:DestinationAddress2/>
</q17:DestinationSection>
<q17:DestinationSection>
you are trying to out-trick the very mighty XML engine.
As stated in your other question:
Never do this in a CURSOR! They are bad and evil, coming directly of the hell of procedural thinking and were invented by the devil of spaghetti code...
Try it like this:
I use your table DDL an insert some data. The second row will have a NULL in address2. Normally XML will simply omit NULL values. A not existing node is read as a NULL value. But you can force NULLs to be introduced as xsi.nil="true" with ELEMENTS XSINIL:
CREATE TABLE DocPurcharseHeader
(
ADRegistrationDate date,
Code NVARCHAR(4000),
Description NVARCHAR(4000),
Address1 NVARCHAR (4000),
Address2 NVARCHAR (4000),
City NVARCHAR (4000),
ZIPCode NVARCHAR(4000)
);
INSERT INTO DocPurcharseHeader (ADRegistrationDate, Code, Description, Address1, Address2, City, ZIPCode)
VALUES('2017-10-16', '01', 'MyPOS', 'MyPOSAddress1', 'MyPOSAddress2', 'BUCHAREST', '123456')
,('2017-10-16', '01', 'MyPOS', 'MyPOSAddress1', NULL, 'BUCHAREST', '123456');
WITH XMLNAMESPACES('http://ITrack.Transmission/2011/02/25/Objects' AS q17)
SELECT Code AS [q17:DestinationCode]
,Description AS [q17:DestinationName]
,Address1 AS [q17:DestinationAddress1]
,Address2 AS [q17:DestinationAddress2]
FROM DocPurcharseHeader
FOR XML PATH('q17:DestinationSection'),ELEMENTS XSINIL,ROOT('q17:DestinationSections');
The result
<q17:DestinationSections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q17="http://ITrack.Transmission/2011/02/25/Objects">
<q17:DestinationSection>
<q17:DestinationCode>01</q17:DestinationCode>
<q17:DestinationName>MyPOS</q17:DestinationName>
<q17:DestinationAddress1>MyPOSAddress1</q17:DestinationAddress1>
<q17:DestinationAddress2>MyPOSAddress2</q17:DestinationAddress2>
</q17:DestinationSection>
<q17:DestinationSection>
<q17:DestinationCode>01</q17:DestinationCode>
<q17:DestinationName>MyPOS</q17:DestinationName>
<q17:DestinationAddress1>MyPOSAddress1</q17:DestinationAddress1>
<q17:DestinationAddress2 xsi:nil="true" />
</q17:DestinationSection>
</q17:DestinationSections>
UPDATE: About NULL values:
Try this
DECLARE #DummyTable TABLE(SomeDescription VARCHAR(500), SomeValue VARCHAR(100));
INSERT INTO #DummyTable VALUES('A real NULL value',NULL)
,('An empty string','')
,('A blank string',' ')
,('Some Text','blah blah');
WITH XMLNAMESPACES('SomeURL' AS q17)
SELECT SomeDescription AS [q17:Description]
,SomeValue AS [q17:Value]
FROM #DummyTable
FOR XML PATH('q17:row'),ELEMENTS XSINIL,ROOT('root');
To get this
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q17="SomeURL">
<q17:row>
<q17:Description>A real NULL value</q17:Description>
<q17:Value xsi:nil="true" />
</q17:row>
<q17:row>
<q17:Description>An empty string</q17:Description>
<q17:Value></q17:Value>
</q17:row>
<q17:row>
<q17:Description>A blank string</q17:Description>
<q17:Value> </q17:Value>
</q17:row>
<q17:row>
<q17:Description>Some Text</q17:Description>
<q17:Value>blah blah</q17:Value>
</q17:row>
</root>
You can see, that the real NULL is encoded as xsi:nil="true", while the empty string is shown as <q17:Value></q17:Value> (which is exactly the same as <q17:Value />).
Check this answer for some examples about NULL and empty. Check this answer to understand more about text()
I have this XML in a table column in SQL Server:
<root>
<Request>
<RequestData>
<VendorLeadList>
<VendorLeadItem>
<CampaignOfferTypeID>REN</CampaignOfferTypeID>
<LeadDispositionID>Lead</LeadDispositionID>
<Jurisdiction>NY</Jurisdiction>
<FirstName>Shikasta</FirstName>
<LastName>Kashti</LastName>
<MessageId>1347_1483825159115_c8273</MessageId>
</VendorLeadItem>
</VendorLeadList>
</RequestData>
<DualMessageID/>
<AzureBlobFile/>
<AzureBlobImageList/>
</Request>
</root>
I want to query all the records where it matches some nodes with specific values. For example I want all records where LeadDispositionID=Lead and Jurisdiction=NY and CampaignOfferTypeID=REN and a MessageId element exists (doesn't matter what value.)
I tried this but it doesn't work (no errors but the conditions doesn't match and it returns other records):
SELECT TOP 10 *
FROM [Messages]
WHERE PayLoadXml.exist('//LeadDispositionID[.="Lead"] and //CampaignOfferTypeID[.="REN"] and //Jurisdiction[.="NY"] and //MessageId') = 1
ORDER BY ID DESC
Any idea as to what I'm doing wrong?
You cannot combine nodes within .exist() simply with and. Your own example would work like this:
SELECT TOP 10 *
FROM #Messages
WHERE PayLoadXml.exist('//VendorLeadItem[LeadDispositionID[.="Lead"] and CampaignOfferTypeID[.="REN"] and Jurisdiction[.="NY"] and MessageId/text()]') = 1
Try it like this:
First a declared table to mock-up your Messages table. Insert 3 cases:
DECLARE #messages TABLE(SomeDescription VARCHAR(100),PayLoadXml XML);
INSERT INTO #messages VALUES
('Your example'
,'<root>
<Request>
<RequestData>
<VendorLeadList>
<VendorLeadItem>
<CampaignOfferTypeID>REN</CampaignOfferTypeID>
<LeadDispositionID>Lead</LeadDispositionID>
<Jurisdiction>NY</Jurisdiction>
<FirstName>Shikasta</FirstName>
<LastName>Kashti</LastName>
<MessageId>1347_1483825159115_c8273</MessageId>
</VendorLeadItem>
</VendorLeadList>
</RequestData>
<DualMessageID/>
<AzureBlobFile/>
<AzureBlobImageList/>
</Request>
</root>'
)
,('LeadDispositionID=Slave'
,'<root>
<Request>
<RequestData>
<VendorLeadList>
<VendorLeadItem>
<CampaignOfferTypeID>REN</CampaignOfferTypeID>
<LeadDispositionID>Slave</LeadDispositionID>
<Jurisdiction>NY</Jurisdiction>
<FirstName>Bruno</FirstName>
<LastName>Kashti</LastName>
<MessageId>1347_1483825159115_c8273</MessageId>
</VendorLeadItem>
</VendorLeadList>
</RequestData>
<DualMessageID/>
<AzureBlobFile/>
<AzureBlobImageList/>
</Request>
</root>'
)
,('LeadDispositionID=Lead but No MessageId'
,'<root>
<Request>
<RequestData>
<VendorLeadList>
<VendorLeadItem>
<CampaignOfferTypeID>REN</CampaignOfferTypeID>
<LeadDispositionID>Lead</LeadDispositionID>
<Jurisdiction>NY</Jurisdiction>
<FirstName>Bruno</FirstName>
<LastName>Kashti</LastName>
<MessageId></MessageId>
</VendorLeadItem>
</VendorLeadList>
</RequestData>
<DualMessageID/>
<AzureBlobFile/>
<AzureBlobImageList/>
</Request>
</root>'
);
This is the query:
The CROSS APPLY will ensure, that only nodes with a MessageId are taken into account. The WHERE will apply an additional filter
SELECT m.*
FROM #messages AS m
CROSS APPLY m.PayLoadXml.nodes(N'/root/Request/RequestData/VendorLeadList/VendorLeadItem[not(empty(MessageId/text()))]') AS A(itm)
WHERE itm.exist(N'LeadDispositionID[text()="Lead"]')=1
If you need to check more than one condition you might use this:
WHERE itm.exist(N'.[LeadDispositionID="Slave" and FirstName="Bruno"]')=1
I have a scalar xml variable:
DECLARED #XML xml =
'<rows>
<row>
<column1 attrib="" />
<column2 attrib="" />
</row>
<!-- ... -->
</rows>';
I would like to split the data so that each row's xml is assigned to a new record in a table:
Id | ... | XML
1 | | '<row><column1 attrib="" /><column2 attrib="" /></row>'
2 | | etc.
3 | | etc.
I haven't quite grasped xquery so I'm having trouble writing an insert statement that does what I want.
INSERT into MyTable( [XML])
SELECT #XML.query('row')
Now I know something is happening but it appears rather than doing what I intended and inserting multiple new records it is inserting a single record with an empty string into the [XML] column.
What am I not getting?
Clarification
I am not trying to get the inner text, subelements or attributes from each row using value(...). I am trying to capture the entire <row> element and save it to a column of type xml
I've experimented with nodes(...) and come up with:
INSERT into MyTable([XML])
SELECT C.query('*')
FROM #XML.nodes('rows/row') T(C)
Which is closer to what I want but the results don't include the outer <row> tag, just the <column*> elements it contains.
You need to use .nodes(...) to project each <row .../> as a row and the extract the attributes of interest using .value(...). Something like:
insert into MyTable(XML)
select x.value('text()', 'nvarchar(max)') as XML
from #XML.nodes(N'/rows/row') t(x);
text() will select the inner text of each <row .../>. You should use the appropriate expression (eg. node() or #attribute etc, see XPath examples), depending on what you want from the row (your example does not make it clear at all, with all those empty elements...).
T-SQL Script:
SET ANSI_WARNINGS ON;
DECLARE #x XML =
'<rows>
<row Atr1="11" />
<row Atr1="22" Atr2="B" />
<row Atr1="33" Atr2="C" />
</rows>';
DECLARE #Table TABLE(Id INT NOT NULL, [XMLColumn] XML NOT NULL);
INSERT #Table (Id, XMLColumn)
SELECT ROW_NUMBER() OVER(ORDER BY ##SPID) AS Id,
a.b.query('.') AS [XML]
FROM #x.nodes('//rows/row') AS a(b);
SELECT *
FROM #Table t;
Results:
Id XMLColumn
-- --------------------------
1 <row Atr1="11" />
2 <row Atr1="22" Atr2="B" />
3 <row Atr1="33" Atr2="C" />
I have table which contains columns like
SiteID (identity_Col)
SiteName
POrderID
Location
Address
Cluster
VenderName
I want to use xml string to insert/update/delete data in this table. Apart from this column, XML string contains one more column viz. RowInfo. This column will have values like "Unchanged","Update","New","Delete". Based on this values the rows in the table should be inserted,updated,deleted.
My XML string is as below:
<NewDataSet>
<DataTable>
<SiteID>2</SiteID>
<SiteName>NIZAMPURA</SiteName>
<POrderID>7</POrderID>
<Location>NIZAMPURA</Location>
<SiteAddress>Vadodara</SiteAddress>
<Cluster>002</Cluster>
<SubVendorName>Test Vender-1</SubVendorName>
<RowInfo>UNCHANGED</RowInfo>
</DataTable>
<DataTable>
<SiteID>16</SiteID>
<SiteName>Site-1</SiteName>
<POrderID>7</POrderID>
<Location>Alkapuri</Location>
<SiteAddress>test</SiteAddress>
<Cluster>Test Cluster</Cluster>
<SubVendorName>Test Vender12</SubVendorName>
<RowInfo>UNCHANGED</RowInfo>
</DataTable>
<DataTable>
<SiteID>17</SiteID>
<SiteName>Site-3</SiteName>
<POrderID>7</POrderID>
<Location>Alkapuri123</Location>
<SiteAddress>test123</SiteAddress>
<Cluster>Test Cluster123</Cluster>
<SubVendorName>Test Vender123</SubVendorName>
<RowInfo>DELETE</RowInfo>
</DataTable>
</NewDataSet>'
This is the code that I have written to insert data in table if RowInfo = "NEW"
IF len(ISNULL(#xmlString, '')) > 0
BEGIN
DECLARE #docHandle1 int = 0;
EXEC sp_xml_preparedocument #docHandle1 OUTPUT, #xmlString
INSERT INTO [SiteTRS] (
[SiteName],
[POrderID],
[Location],
[SiteAddress],
[Cluster],
[SubVendorName])
SELECT SiteName,POrderID,Location,SiteAddress,Cluster,SubVendorName
FROM OPENXML (#docHandle1, '/NewDataSet/DataTable')
WITH (SiteName varchar(50) './SiteName',
POrderID varchar(50) './PorderID',
Location varchar(50) './Location',
SiteAddress varchar(max) './SiteAddress',
Cluster varchar(50) './Cluster',
SubVendorName varchar(50) './SubVendorName',
RowInfo varchar(30) './RowInfo')
WHERE RowInfo='NEW'
But I don't know how to use XML to update/delete records in the table. Please guide
I am novice in the XML so dont have any idea. Please forgive me if I am making something childish.
I would strongly recommend not to use the old, legacy OPENXML stuff anymore - with XML support in SQL Server, it's much easier to use the built-in XPath/XQuery methods.
In your case, I would use a CTE (Common Table Expression) to break up the XML into an "inline" table of rows and columns:
DECLARE #input XML = '<NewDataSet>
<DataTable>
<SiteID>2</SiteID>
<SiteName>NIZAMPURA</SiteName>
<POrderID>7</POrderID>
<Location>NIZAMPURA</Location>
<SiteAddress>Vadodara</SiteAddress>
<Cluster>002</Cluster>
<SubVendorName>Vender-1</SubVendorName>
<RowInfo>UPDATE</RowInfo>
</DataTable>
<DataTable>
<SiteName>Site-1</SiteName>
<POrderID>7</POrderID>
<Location>Alkapuri</Location>
<SiteAddress>test</SiteAddress>
<Cluster>Cluster-1</Cluster>
<SubVendorName>Test Vender</SubVendorName>
<RowInfo>NEW</RowInfo>
</DataTable>
</NewDataSet>'
;WITH XMLData AS
(
SELECT
NDS.DT.value('(SiteID)[1]', 'int') AS 'SiteID',
NDS.DT.value('(SiteName)[1]', 'varchar(50)') AS 'SiteName',
NDS.DT.value('(POrderID)[1]', 'int') AS 'POrderID',
NDS.DT.value('(Location)[1]', 'varchar(100)') AS 'Location',
NDS.DT.value('(SiteAddress)[1]', 'varchar(100)') AS 'SiteAddress',
NDS.DT.value('(Cluster)[1]', 'varchar(100)') AS 'Cluster',
NDS.DT.value('(SubVendorName)[1]', 'varchar(100)') AS 'SubVendorName',
NDS.DT.value('(RowInfo)[1]', 'varchar(20)') AS 'RowInfo'
FROM
#input.nodes('/NewDataSet/DataTable') AS NDS(DT)
)
SELECT *
FROM XMLDATA
This gives you rows and columns which you can work with.
SiteID SiteName POrderID Location SiteAddress Cluster SubVendorName RowInfo
2 NIZAMPURA 7 NIZAMPURA Vadodara 002 Vender-1 UPDATE
NULL Site-1 7 Alkapuri test Cluster-1 Test Vender NEW
Now if you're on SQL Server 2008 or newer, you could combine this with the MERGE command to do your INSERT/UPDATE in a single statement, basically.
If you're on 2005, you will need to either store this information into a temporary table / table variable inside your stored proc, or you need to do the select multiple times; the CTE allows only one single command to follow it.
Update: with this CTE, you can then combine it with a MERGE:
;WITH XmlData AS
(
SELECT
NDS.DT.value('(SiteID)[1]', 'int') AS 'SiteID',
NDS.DT.value('(SiteName)[1]', 'varchar(50)') AS 'SiteName',
NDS.DT.value('(POrderID)[1]', 'int') AS 'POrderID',
NDS.DT.value('(Location)[1]', 'varchar(100)') AS 'Location',
NDS.DT.value('(SiteAddress)[1]', 'varchar(100)') AS 'SiteAddress',
NDS.DT.value('(Cluster)[1]', 'varchar(100)') AS 'Cluster',
NDS.DT.value('(SubVendorName)[1]', 'varchar(100)') AS 'SubVendorName',
NDS.DT.value('(RowInfo)[1]', 'varchar(20)') AS 'RowInfo'
FROM
#input.nodes('/NewDataSet/DataTable') AS NDS(DT)
)
MERGE INTO dbo.SiteTRS t
USING XmlData x ON t.SiteID = x.SiteID
WHEN MATCHED AND x.RowInfo = 'UPDATE'
THEN
UPDATE SET
t.SiteName = x.SiteName,
t.POrderID = x.POrderID,
t.Location = x.Location,
t.SiteAddress = x.SiteAddress,
t.Cluster = x.Cluster,
t.SubVendorName = x.SubVendorName
WHEN MATCHED AND x.RowInfo = 'DELETE'
THEN DELETE
WHEN NOT MATCHED AND x.RowInfo = 'NEW'
THEN
INSERT(SiteID, SiteName, POrderID, Location, SiteAddress, Cluster, SubVendorName)
VALUES(x.SiteID, x.SiteName, x.POrderID, x.Location, x.SiteAddress, x.Cluster, x.SubVendorName)
;
See some more resources:
SQL SERVER – 2008 – Introduction to Merge Statement – One Statement for INSERT, UPDATE, DELETE
Using SQL Server 2008's MERGE statement