The following code will return select $f/field/text() from table1
declare @x xml = '<meta><field>Column1</field></meta>';
select @x.query('
for $f in /meta
return
"select $f/field/text() from table1"
')
I tried to change the return part to "select"+$f/field or "select" $f/field and these cannot be parsed.
Update:
The @x will be generated from a table with for xml raw,elements. The purpose to use xml/xquery is to avoid the boilerplate string concatenations. It seems XQuery cannot transform xml to text?
Updated question:
The following is the code I want to write.
declare @meta table (field sysname primary key, validate varchar(8000));
insert into @meta values ('Col1', '< 100'), ('Col2', '> Col1');
declare @x xml = (select * from @meta for xml path('meta'));
select @x;
-- The following code cannot be parsed. It will be nice to replace /meta/field/text() with shorter variable too
select @x.query('
"select 1"
{"," /meta/field/text() "= case when" /meta/field/text() /meta/validate/text() "then" /meta/field/text()}
"from table1"
"where 1=1 "
{ "or (" /meta/field/text() /meta/validate/text() ")" }
')
And the generated result should be,
select 1
, Col1 = case when Col1 < 100 then Col1 end
, Col2 = case when Col2 > Col1 then Col2 end
from table1
where 1=1
or (Col1 < 100)
or (Col2 > Col1)
Just need to wrap everything in an outer xml tag.