简体   繁体   中英

SQL XML contains() with fn:lowercase()

I'm trying to make this Xpath query using the lowercase text() value in my contains() statement. For example, searching "New York" versus "New york" will return different results.

I plan to make sure the parameter is lowercase going into the stored procedure from now on, but I need to make sure the text() in the XML is also lowercase. I've tried a few different ways but keep getting syntax errors. Note: I'm searching the <Company> node for New York to ensure I don't get any records that match the <City> node. I had started with regular full-text contains() but have since gone to XPath for accuracy.

DECLARE @Company nvarchar(100) = "new york"

SELECT ...
FROM OrderObject o
WHERE o.Address.exist('//Company/text()[contains(.,sql:variable("@Company"))]') = 1)

XML is like this... shorted for brevity
<Address>
<Company>1</Company>
<City>2</City>
<State>3</State>
</Address>

Thanks

Here is a correct way to it.

You need to apply lower-case() function for both parameters of the contains() function.

This way stored procedure parameter could be in absolutely any case: upper, lower, mixed, etc.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, xmldata XML);
INSERT INTO @tbl (xmldata) VALUES
(N'<Address>
    <Company>1</Company>
    <City>NeW YoRk</City>
    <State>NY</State>
</Address>'),
(N'<Address>
    <Company>2</Company>
    <City>Miami</City>
    <State>FL</State>
</Address>');
-- DDL and sample data population, end

DECLARE @City NVARCHAR(100) = 'new york';

SELECT * 
FROM @tbl
WHERE xmldata.exist('/Address/City[contains(lower-case((./text())[1]),lower-case(sql:variable("@City")))]') = 1;

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