Re: Using XML data for query
- From: Kent Tegels <ktegels@xxxxxxxxxxx>
- Date: Tue, 5 Sep 2006 13:09:56 +0000 (UTC)
Hello Han,
I am getting XML as a parameter in my stored procedure. Something
like,
<a col1='val-1' col2='val-2' ... />
I would like to use the key-value pair in my SQL query dynamically.
Something like,
select * from T where col1=@col2 and col2=@col2, ...
Weird is I can't know the column name in runtime. Earlier I used XSL
with output=text to compose the query dynamically. But I am seeking
better idea.
The essential problem here is that since the XQuery is done as part of the underlying execution plan, you'd have to construct this as a dynamic query -- a first query to resolve the where predicate columns and values and a second to actually do the work. e.g.
declare @xquery xml
declare @query nvarchar(4000)
declare @predicates int
set @xquery = '<q emailPromotion="0" title="Ms."/>'
set @query = 'select contactId,firstName,lastName from person.contact where '
set @predicates = @xquery.value('count(/q/@*)','int')
while @predicates > 0
begin
print @predicates
set @query = @query + @xquery.value('local-name((/q/@*)[sql:variable("@predicates")])','nvarchar(100)')+'=' + @xquery.value('(/q/@*)[sql:variable("@predicates")]','nvarchar(100)')
set @predicates = @predicates - 1
if @predicates > 0
set @query = @query + ' and ' end
select cast(@query as xml)
--execute(@query)
go
However, this doesn't actually work. It seems that the use of the sql:varaible function to get the current attribute's messes up the rest of the XQuery. Using the same value as a constant doesn't. I'll see if Dan has any ideas.
And, oh, you have another problem. How are you going to decide when a parameter value needs to be quoted on not?
"Once you start down the dark parth, forever dominate your future it will"
Thanks,
Kent Tegels, DevelopMentor
http://staff.develop.com/ktegels/
.
- Follow-Ups:
- Re: Using XML data for query
- From: Kent Tegels
- Re: Using XML data for query
- From: Han
- Re: Using XML data for query
- References:
- Using XML data for query
- From: Han
- Using XML data for query
- Prev by Date: Using XML data for query
- Next by Date: Re: Using XML data for query
- Previous by thread: Using XML data for query
- Next by thread: Re: Using XML data for query
- Index(es):
Relevant Pages
|