简体   繁体   中英

Searching XML column in sql server

Trying to search column Data, its an xml column

[dbo].[HistoryData].[Data].exist('//text()[CONTAINS(., 'Request viewed' )]') = 1

I get error Incorrect syntax near 'Request'. What am i missing here? kindly assist.

Column Data has this:

<MessageNotification xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AttorneyID xsi:nil="true" />
<MatterID xsi:nil="true" />
<NotificationID xsi:nil="true" />
<MessageId>3566913</MessageId>
<ParentMessageGuid xsi:nil="true" />
<MessageGuid>fc54e518-e45d-4564-8b80-2593796d5b</MessageGuid>
<Subject>Firm not registered </Subject>
<MessageDate>2015-06-19T10:05:48.4493646+02:00</MessageDate><Body>

This is just a message

Thank you

</Body>
<ContactPerson> N/A </ContactPerson><ContactDetails xsi:nil="true" />
<PreferredContactMethod>NotApplicable</PreferredContactMethod>
</MessageNotification>

The syntax error are the single quotes obviously.

But I think there is more around... What are you trying to achieve?

The exist() is checking for the pure existance and in most cases used within a WHERE clause in order to reduce the rows before a more expensive operations.

Try this:

DECLARE @dummyTable TABLE(ID INT IDENTITY, YourXML XML);
INSERT INTO @dummyTable VALUES
 (N'<root>
    <a>test</a>
    <a>Some other</a>
   </root>')
,(N'<root>
    <a>no</a>
    <a>Some other</a>
   </root>')
,(N'<root>
    <a>no</a>
    <a>test</a>
   </root>');

SELECT * 
FROM @dummyTable
WHERE YourXML.exist(N'//*[contains(text()[1],"test")]')=1;

The result set comes without line 2

UPDATE: Use a variable

In order to get this more generic I'd suggest to use a variable:

DECLARE @SearchFor NVARCHAR(100)='other';

SELECT * 
FROM @dummyTable
WHERE YourXML.exist(N'//*[contains(text()[1],sql:variable("@SearchFor"))]')=1;

This comes without line 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM