Below codes are working and it outputs the first name:
DECLARE @xmlData XML = '<CustomerExtract><Delete User="Customer Deleter" ReasonCode="2"><Customer><CustomerID>9</CustomerID><Name><Title></Title><First>MOCHA</First><MI></MI><Last>MOCHA</Last><Suffix></Suffix></Name></Customer></Delete></CustomerExtract>'
DECLARE @xmlPath VARCHAR(MAX) = '(/CustomerExtract/Delete/Customer/'
select @xmlData.value('(/CustomerExtract/Delete/Customer/Name/First)[1]','VARCHAR(8000)')
Now, I need to use a dynamic variable so the XML path can change depending on the situation, but the outer elements doesn't change. Codes are something like this:
-- Check the CustomerUpdate type (Create / Update / Delete)
IF (@dataXML.exist('(/CustomerExtract/New)') = 1)
SET @xmlPath = '/CustomerExtract/New/Customer/'
ELSE IF (@dataXML.exist('(/CustomerExtract/Change)') = 1)
SET @xmlPath = '/CustomerExtract/Change/After/Customer/'
ELSE IF (@dataXML.exist('(/CustomerExtract/Delete)') = 1)
SET @xmlPath = '/CustomerExtract/Delete/Customer/'
ELSE --Not supported!
RETURN
However, when I try to use an SQL implicit variable like mentioned here: The argument 1 of the XML data type method "value" must be a string literal , I got some weird errors:
Sample 1: Starting parenthesis inside variable @xmlPath
DECLARE @xmlPath VARCHAR(MAX) = '(/CustomerExtract/Delete/Customer/'
select @xmlData.value('sql:variable("@xmlPath")Name/First)[1]','VARCHAR(8000)')
It throws this exception:
XQuery [value()]: No more tokens expected at the end of the XQuery expression. Found 'Name'.
Sample 2: Starting parenthesis NOT on variable
DECLARE @xmlPath VARCHAR(MAX) = '/CustomerExtract/Delete/Customer/'
select @xmlData.value('(sql:variable("@xmlPath")Name/First)[1]','VARCHAR(8000)')
It throws this exception:
XQuery [value()]: ")" was expected.
Sample 3:
DECLARE @xmlPath VARCHAR(MAX) = '/CustomerExtract/Delete/Customer'
select @xmlData.value('(sql:variable("@xmlPath")/Name/First)[1]','VARCHAR(8000)')
It throws this exception:
XQuery [value()]: A node or set of nodes is required for /
Can someone please explain me why does this happen and what is the correct syntax to achieve my desired results? Thanks