Quantcast
Viewing all articles
Browse latest Browse all 20

Parameters in SQL Server XPath Queries

If you have forgotten the syntax for using parameters in XPath queries within SQL Server 2005 and SQL Server 2008 the following should refresh your memory.

Hard coded example:

SELECT

       *

FROM

       dbo.AuditLog

WHERE

       InsertedRows.exist(‘/LOG/@USERID[contains(.,"DOMAIN\JSmith")]‘) = 1

 

This XPath query works, but it is hard coded for one value.

 

Concatenated example:

DECLARE @affectedUserName NVARCHAR(50)

SET @affectedUserName = ‘DOMAIN\JSmith’

 

SELECT

       *

FROM

       dbo.AuditLog

WHERE

       InsertedRows.exist(‘/LOG/@USERID[contains(.,"' + @affectedUserName + '"))]‘) = 1

This XPath query does not work.  You will receive the following error message if you try to use this code: The argument 1 of the XML data type method “exist” must be a string literal.

 

SQL variable example:

DECLARE @affectedUserName NVARCHAR(50)

SET @affectedUserName = ‘DOMAIN\JSmith’

 

SELECT

       *

FROM

       dbo.AuditLog

WHERE

       InsertedRows.exist(‘/LOG/@USERID[contains(.,sql:variable("@affectedUserName"))]‘) = 1

This XPath query works and accepts a parameter to work with multiple values.

 

SQL Server Expert, Steve Abraham, holds 8 Microsoft certifications and specializes in SQL Server and .Net Framework architecture, high availability, capacity planning, development, and performance tuning, and SQL Server Recovery.


Filed under: Programming SQL Server, SQL Server 2005, SQL Server 2008, T-SQL, XML Tagged: SQL Server, SQL Server 2005, SQL Server 2008, SQL Server Expert, SQL Server Recovery, sql:variable, XML, XPath Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 20

Trending Articles