views:

18

answers:

2

I have this XML Query in SQL Server 2005:

SElECT XmlField FROM tablename WHERE xmlField.exist('(/Root/Name[id="10")[1]') = 1

However, I want to replace the value "10" with a parameter that I pass to the Stored Procedure. How do I achieve this? I have tried using "@variablename" but it doesn't work.

Thanks in advance.

A: 

Probably, you want to have something like

SELECT XmlField FROM tablename WHERE xmlField.exist('(/Root/Name[id="{ sql:variable("@variablename") }")[1]') = 1

See http://msdn.microsoft.com/en-us/library/ms188254(v=SQL.100).aspx for how to access variables and columns in XQuery in SQL Server.

Frank
Thanks Frank for your response. I have tried your suggestion but am getting an error message. This is the exact line of code am using:`...WHERE Result_XML.exist('(/Root/Name[id="{sql:variable("@myId")}"])[1]') = 1`I have declared and assigned a value to the variable `@myId` before this line of codeAnd I get this error message:`Msg 9303, Level 16, State 1, Line 15XQuery [Staff_Process_Triggers.Result_XML.exist()]: Syntax error near '@', expected ']'.`
A: 

After a few minutes of hair pulling...i found an answer...

Result_XML.exist('(/Root/Name[id="{sql:variable("@myId")}"])[1]') = 1

should be written as

Result_XML.exist('(/Root/Name[id=(sql:variable("@myId"))])[1]') = 1

I replaced the "{ and }" with ( and ) to enclose the sql:variable keyword.

Maybe you can even leave the ( and ) away. Maybe the enclosing in "{ and }" that I took from the MSDN documentation is only necessary for construction of XML, not for XPath comparisons.
Frank
You are right Frank, the ( and ) are not necessary, it still works without them. Thanks again for your responses. Highly appreciated!