HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Variable for element name

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
elementvariablenamefor

Problem

I have this tSQL code which works OK:

SELECT 
c.logguid,
a.b.value('./PropertyValue', 'varchar(max)') asd
  FROM [dnn].[dbo].[EventLog2] c

cross apply sss.nodes('/LogProperties/LogProperty[PropertyName=sql:variable("@x") and PropertyValue=sql:variable("@y")]') as a(b)


However, what I want to be able to do is pass in a dynamic list of many pairs of values which are OR'd between each one, i.e.

SELECT 
c.logguid,
a.b.value('./PropertyValue', 'varchar(max)') asd
  FROM [dnn].[dbo].[EventLog2] c

cross apply sss.nodes(
'/LogProperties/LogProperty[PropertyName=sql:variable("@x") and PropertyValue=sql:variable("@y")
or
PropertyName=sql:variable("@a") and PropertyValue=sql:variable("@b")
]'
) as a(b)


Is there a way of doing this?

Solution

Any parameter that needs a variable list or array is probably a good candidate for a user-defined table type. I would create the type as:

CREATE TYPE [PropertyVariableTableType] AS TABLE (
    PropertyName nvarchar(255),
    PropertyValue nvarchar(255) )


Table types can be used as parameters to stored procedures just as any other type. You can then either join on the user-defined table or iterate the rows to dynamically build the query.

Code Snippets

CREATE TYPE [PropertyVariableTableType] AS TABLE (
    PropertyName nvarchar(255),
    PropertyValue nvarchar(255) )

Context

StackExchange Database Administrators Q#18233, answer score: 2

Revisions (0)

No revisions yet.